Skip to content

Commit

Permalink
Prevent tree shaking CSS imports
Browse files Browse the repository at this point in the history
Importing CSS is always side-effectual, and should not be tree-shaken.
Fixes #1050
  • Loading branch information
matthewp committed Jul 24, 2018
1 parent 4ded68f commit 3aa018f
Show file tree
Hide file tree
Showing 6 changed files with 28 additions and 1 deletion.
12 changes: 12 additions & 0 deletions lib/graph/treeshake.js
Expand Up @@ -125,6 +125,14 @@ function loadFromGraph(getNode) {

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

return "export default {}";
}
}
Expand All @@ -134,6 +142,10 @@ function loadFromGraph(getNode) {
};
}

function sideEffectualModule(node) {
return node && node.load.metadata.buildType === "css";
}

function transpile(getNode, data) {
let loader = data.loader;

Expand Down
5 changes: 5 additions & 0 deletions test/tree_shaking_test.js
Expand Up @@ -94,6 +94,11 @@ describe("Tree-shaking", function(){
assert.equal(browser.window.DEP3_SIDE_EFFECT, true,
"Includes a module with needed side effects.");
});

it("Works when the dependency is CSS", function(){
var mod = browser.window.steal.loader.get("treeshake@1.0.0#styles.css!treeshake@1.0.0#css");
assert.ok(mod, true, "Includes a CSS module");
});
})

describe("export *", function(){
Expand Down
1 change: 1 addition & 0 deletions test/treeshake/basics/css.js
3 changes: 3 additions & 0 deletions test/treeshake/basics/main.js
Expand Up @@ -13,6 +13,9 @@ import steal from "@steal";
// Importing a module for its side effects
import "dep3";

// CSS
import "./styles.css";

// Importing a module that itself should be tree-shaken
import {default as dep4} from "dep4";

Expand Down
5 changes: 4 additions & 1 deletion test/treeshake/basics/package.json
Expand Up @@ -11,7 +11,10 @@
"dep5": "1.0.0"
},
"steal": {
"bundle": ["treeshake/bundle-a"]
"bundle": ["treeshake/bundle-a"],
"ext": {
"css": "treeshake/css"
}
},
"sideEffects": false
}
3 changes: 3 additions & 0 deletions test/treeshake/basics/styles.css
@@ -0,0 +1,3 @@
body {
color: green;
}

0 comments on commit 3aa018f

Please sign in to comment.