Skip to content

Commit

Permalink
Enable traversing non-ES modules imports
Browse files Browse the repository at this point in the history
This makes it so that if an ES module is only imported by non-ES
modules, it is still included in the tree-shaking algorithm and can be
tree-shaken.

Fixes #1068
  • Loading branch information
matthewp committed Aug 30, 2018
1 parent 6255900 commit 59ced05
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
19 changes: 13 additions & 6 deletions lib/graph/treeshake.js
Expand Up @@ -112,29 +112,36 @@ function loadFromGraph(getNode) {
}
}

let code = '';

if(node) {
// Add deps as regular imports
for(let specifier of node.load.metadata.deps) {
code += `import "${specifier}";\n`;
}
}

// Expose named exports so that dependant modules will tree-shake properly.
if(needToExport.size) {
let code = '';
for(let exp of needToExport) {
if(exp === "default") {
code += "export default {};\n";
} else {
code += `export let ${exp} = {};\n`;
}
}

return code;
} else {
// Prevent tree shaking modules that are side-effectual like CSS
if(sideEffectualModule(node)) {
return `
code += `
export function one() {window.ONE = {}};
one();
`.trim();
} else {
code += "export default {}";
}

return "export default {}";
}
return code;
}

return source.node(node);
Expand Down
2 changes: 1 addition & 1 deletion test/tree_shaking_test.js
Expand Up @@ -127,7 +127,7 @@ describe("Tree-shaking", function(){
});
});

describe.only("ES modules imported by CommonJS modules", function() {
describe("ES modules imported by CommonJS modules", function() {
it("Tree-shakes their ES module dependencies", function() {
let mod = app.dep5dep5AnotherESModule;
assert.equal(typeof mod.mainThing, "function", "Kept the used export");
Expand Down

0 comments on commit 59ced05

Please sign in to comment.