[英]How can I make webpack treeshake my ES6 module?
I have followed every guide out there for turning on tree shaking in webpack 4 but webpack still bundles code from a NPM module that I have set up to be treeshaken. 我已经按照每个指南在webpack 4中打开树摇动但是webpack仍然捆绑了我已经设置为树木的NPM模块的代码。 How can I enable treeshaking and not include particular code in my web app?
如何在我的网络应用程序中启用树形图并且不包含特定代码?
Full source code in GitHub repo GitHub repo中的完整源代码
I have a CRA (create-react-app) that imports a NPM module I created to test it that looks like this: 我有一个CRA(create-react-app)导入我创建的NPM模块来测试它看起来像这样:
package
index.mjs
dist
esm
components
image
index.js
index.js
index.js
with package.json
like this: 像这样的
package.json
:
"main": "index",
"module": "index.jsm",
"sideEffects": false,
that transpiles using babel with babelrc like: 与babelrc一起使用babel的翻译如下:
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
],
"@babel/react",
"@babel/flow"
]
}
I have 3 React components: image
, avatar
(that imports image
) and login-button
that has this es6 code: 我有3个React组件:
image
, avatar
(导入image
)和具有此es6代码的login-button
:
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>
The index file for the NPM es6 module: NPM es6模块的索引文件:
import * as lib from './dist/esm'
export default lib
In the CRA's app.js
I have: 在CRA的
app.js
我有:
import TreeshakingTestModule from 'treeshaking-test-module'
function App() {
return (
<div className="App">
<TreeshakingTestModule.Avatar />
</div>
);
}
When I npm start
it builds and renders the avatar but I also see the message. 当我
npm start
它会构建并渲染头像,但我也会看到该消息。
Note that login-button
is never used however the default export of my NPM package which does export the component is imported, however I read tutorials that explained that even default exports and re-exports should still work with tree shaking if what is exported is never used. 请注意,从不使用
login-button
,但导入组件的NPM软件包的默认导出是导入的,但是我读到的教程解释说,如果导出的内容永远不会导致默认导出和重新导出仍然可以使用树抖动用过的。
What is happening? 怎么了? What am I doing wrong?
我究竟做错了什么?
As far as I know, webpack three shakes by analysing imports statically, not by reading your code. 据我所知,webpack三次静态分析导入,而不是通过读取代码。 You cannot expect webpack to realize you're only using
Avatar
from TreeshakingTestModule
. 您不能指望webpack意识到您只使用
TreeshakingTestModule
Avatar
。
So you need to declare what you want to use at import
level, by using named imports and exports: 因此,您需要使用命名导入和
import
声明要在import
级别使用的内容:
import {Avatar} from 'treeshaking-test-module'
function App() {
return (
<div className="App">
<Avatar />
</div>
);
}
So webpack knows you're only using the Avatar
export. 所以webpack知道你只使用
Avatar
导出。
This means that Avatar
needs to be a named export in your treeshaking-test-module
module. 这意味着
Avatar
需要成为treeshaking-test-module
模块中的命名导出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.