Skip to content

Instantly share code, notes, and snippets.

@developit
Last active September 11, 2019 09:43
Show Gist options
  • Save developit/eac9a027db90248afa52a3904734924b to your computer and use it in GitHub Desktop.
Save developit/eac9a027db90248afa52a3904734924b to your computer and use it in GitHub Desktop.

Combines all bare imports (npm module imports) into a single packd-es import.

Input:

import { h, render } from 'preact@next';
import { useState } from 'preact@next/hooks';
import { html } from 'htm/preact';
render(h(() => html`<a />`), document.body);

Output:

import { h, render, useState, html } from "https://packd-es.herokuapp.com/preact@next,preact@next/hooks,htm/preact?flat";
render(h(() => html`<a />`), document.body);

License: Apache 2

View on ASTExplorer

export default function({ types: t }) {
const CDN = 'https://packd-es.herokuapp.com/';
return {
name: 'babel-plugin-import-cdn',
visitor: {
Program: {
exit(path, state) {
const imports = state.get('imports');
if (!imports) return;
const decl = t.importDeclaration(
imports.reduce((acc, p) => acc.concat(p.specifiers), []),
t.stringLiteral(CDN + imports.map(p => p.source).sort().join(',') + '?flat')
);
path.unshiftContainer('body', decl);
imports.map(p => p.path.remove());
}
},
ImportDeclaration(path, state) {
const source = path.node.source.value;
if (/^\.*\//.test(source)) return;
let imports = state.get('imports');
if (!imports) state.set('imports', imports = []);
imports.push({
path,
source,
specifiers: path.node.specifiers.map(t.clone)
});
}
}
};
}
{
"name": "babel-plugin-import-cdn",
"version": "0.1.0",
"main": "babel-plugin-import-cdn.js",
"license": "Apache-2.0",
"author": "Jason Miller (https://jasonformat.com)",
"homepage": "https://gist.github.com/developit/eac9a027db90248afa52a3904734924b",
"repository": "gist:eac9a027db90248afa52a3904734924b"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment