unpkg/server/utils/unpkgRewriteBabelPlugin.js

45 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-02-18 02:00:56 +00:00
const URL = require("whatwg-url");
const warning = require("warning");
2018-01-10 05:41:19 +00:00
2018-02-18 02:00:56 +00:00
const BareIdentifierFormat = /^((?:@[^\/]+\/)?[^\/]+)(\/.*)?$/;
2018-01-10 05:41:19 +00:00
function unpkgRewriteBabelPlugin(dependencies = {}) {
return {
inherits: require("babel-plugin-syntax-export-extensions"),
visitor: {
"ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration"(path) {
2018-02-18 02:00:56 +00:00
if (!path.node.source) return; // probably a variable declaration
2018-01-10 05:41:19 +00:00
if (
URL.parseURL(path.node.source.value) != null ||
path.node.source.value.substr(0, 2) === "//"
)
2018-02-18 02:00:56 +00:00
return; // valid URL or URL w/o protocol, leave it alone
2018-01-10 05:41:19 +00:00
if ([".", "/"].indexOf(path.node.source.value.charAt(0)) >= 0) {
// local path
2018-02-18 02:00:56 +00:00
path.node.source.value = `${path.node.source.value}?module`;
2018-01-10 05:41:19 +00:00
} else {
// "bare" identifier
2018-02-18 02:00:56 +00:00
const match = BareIdentifierFormat.exec(path.node.source.value);
const packageName = match[1];
const file = match[2] || "";
2018-01-10 05:41:19 +00:00
warning(
dependencies[packageName],
'Missing version info for package "%s" in dependencies; falling back to "latest"',
packageName
2018-02-18 02:00:56 +00:00
);
2018-01-10 05:41:19 +00:00
2018-02-18 02:00:56 +00:00
const version = dependencies[packageName] || "latest";
2018-01-10 05:41:19 +00:00
2018-02-18 02:00:56 +00:00
path.node.source.value = `https://unpkg.com/${packageName}@${version}${file}?module`;
2018-01-10 05:41:19 +00:00
}
}
}
2018-02-18 02:00:56 +00:00
};
2018-01-10 05:41:19 +00:00
}
2018-02-18 02:00:56 +00:00
module.exports = unpkgRewriteBabelPlugin;