Skip to content

feat(external): Options to disable adding all dependencies to external list by default. #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,35 @@
const readPkg = require('read-pkg');
const { walk } = require('estree-walker');
const MagicString = require('magic-string');
const readPkg = require("read-pkg");
const { walk } = require("estree-walker");
const MagicString = require("magic-string");
const padStr = str => `'${str}'`;

module.exports = ({ transform = (name, version) => `https://unpkg.com/${name}@${version}?type=module` } = {}) => {
module.exports = ({ transform = (name, version) => `https://unpkg.com/${name}@${version}?type=module`, autoDiscoverExternals = true } = {}) => {
const pkg = readPkg.sync();
const cache = {};
return {
name: 'unpkg',
name: "unpkg",
options(opts) {
let deps = (pkg && pkg.dependencies) || {};

let userDefinedExternal = Array.isArray(opts.external) ? opts.external : [];
Object.keys(deps).forEach(dep => {
const manifest = readPkg.sync(require.resolve(`${dep}/package.json`));
if (manifest.module) cache[manifest.name] = transform(manifest.name, manifest.version);
// If auto discover is set to false only add to cache if dep is in external list.
if (autoDiscoverExternals || userDefinedExternal.includes(dep)) {
const manifest = readPkg.sync({ cwd: `${process.cwd()}/node_modules/${dep}` });
if (manifest.module) cache[manifest.name] = transform(manifest.name, manifest.version);
}
});

let external = Object.values(cache);
if (Array.isArray(opts.external)) {
external = Array.from(new Set(opts.external.concat(external)));
}
external = Array.from(new Set(userDefinedExternal.concat(external)));

return Object.assign({}, opts, { external });
},
transform(code, id) {
const ast = this.parse(code);
const magicString = new MagicString(code);
walk(ast, {
enter(node, parent) {
if (node.type === 'Literal' && parent.type === 'ImportDeclaration') {
if (node.type === "Literal" && parent.type === "ImportDeclaration") {
if (cache[node.value])
magicString.overwrite(node.start, node.end, padStr(cache[node.value]), {
storeName: false
Expand Down