【发布时间】:2019-10-15 22:17:11
【问题描述】:
我已按照那里的所有指南在 webpack 4 中启用 tree shaking,但 webpack 仍然捆绑来自我已设置为 treeshaken 的 NPM 模块的代码。如何启用 treeshaking 并且不在我的网络应用程序中包含特定代码?
Full source code in GitHub repo
我有一个 CRA(create-react-app),它导入我创建的 NPM 模块来测试它,如下所示:
package
index.mjs
dist
esm
components
image
index.js
index.js
index.js
package.json 像这样:
"main": "index",
"module": "index.jsm",
"sideEffects": false,
使用带有 babelrc 的 babel 进行编译,例如:
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
],
"@babel/react",
"@babel/flow"
]
}
我有 3 个 React 组件:image、avatar(导入 image)和 login-button,它们有这个 es6 代码:
import React from 'react'
document.body.innerHTML = document.body.innerHTML + "<div>This is a side effect and should never have happened</div>"
export default () => <button>Login</button>
NPM es6 模块的索引文件:
import * as lib from './dist/esm'
export default lib
在 CRA 的 app.js 我有:
import TreeshakingTestModule from 'treeshaking-test-module'
function App() {
return (
<div className="App">
<TreeshakingTestModule.Avatar />
</div>
);
}
当我npm start 时,它会构建并渲染头像,但我也看到了消息。
请注意,login-button 从未使用过,但是我的 NPM 包的默认导出确实导出了组件,但是我阅读了解释说即使默认导出和重新导出仍然可以使用摇树摇晃的教程,如果什么是从不使用导出的。
发生了什么?我做错了什么?
【问题讨论】:
标签: javascript node.js reactjs webpack