我有一个包含多个react组件的库,并且我想使该库可树状摇动,以便在导入类似
import { Checkbox } from 'my-react-components'
我不导入整个捆绑包。
我的index.js看起来像这样
export { default as Button } from './components/Button'
export { default as Checkbox } from './components/Checkbox'
export { default as FlexView } from './components/FlexView'
export { default as Radio } from './components/Radio'
export { default as Select } from './components/Select'
export { default as TextInput } from './components/TextInput'
export { default as Toggle } from './components/Toggle'
我捆绑使用webpack
module.exports = {
mode: 'production',
entry: './src/index.ts',
output: {
path: path.resolve('./lib'),
filename: 'react-components.js',
libraryTarget: 'commonjs2',
},
// loaders and stuff...
// terser-webpack-plugin...
externals: {
// don't include react in the bundle
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
},
optimization: {
splitChunks: false,
sideEffects: false,
},
}
在我的babel配置中,我当然有
['@babel/preset-env', {
modules: false,
}]
通过这种设置,当我仅导入一个组件时,整个捆绑包就包括在内(导入时我也在使用webpack)。我该如何预防?
最佳答案
我相信您还需要module
上的package.json
属性
{
...
"main": "lib/index.js",
"module": "lib/index.esm.js",
...
}