reactjs - 摇树不适用于使用命名导入的反应组件库
问题描述
我们公司的项目数量正在增长,因此我们决定将我们的 ui 工具包移动到一个单独的私有 npm 包中。对于发布前的构建工具包,我们决定使用汇总。ui 工具包的文件结构非常标准,我们已经:
src
- Components
- Alert
- Button
- Heading
- ...
HOC, static...
- index.js
根 index.js 文件仅用于重新导出所有组件。
export {default as Alert} from './Components/Alert';
export {default as Button} from './Components/Button';
...
我们的主要目标是能够使用命名导入从我们的套件中获取组件。
import {Alert, Button} from '@company/ui-kit';
正确工作的树抖动也很重要,因为我们的一些项目仅使用套件中的 2/31 组件,因此我们希望在最终构建中仅查看已使用的组件,这是主要挑战。我们尝试了许多带有单个输出文件或块的汇总配置选项,并意识到,摇树只适用于块,更有趣的是它只适用于直接导入块,而不是从 index.js 命名导入。
import Alert from '@company/ui-kit/Alert'; // tree shaking works, only Alert get into build
import {Alert} from '@company/ui-kit'; // tree shaking not working, all kit components are got into the build
有人可以解释一下为什么会这样吗?有没有办法使用命名导入和正常工作的摇树。也非常奇怪的是,我们尝试在一些流行的库(如 Material ui)中使用命名导入来测试 tree shaking,但它也不起作用。摇树仅适用于从块直接导入。
还需要提到的是,我们仅在使用 create-react-app 创建的项目中测试了 tree-shaking。我真的不认为问题可能出在 create-react-app bundler 配置中,但也许它有助于解决这个问题。
对于完整的图片,还附上我们的汇总配置:
import multiInput from 'rollup-plugin-multi-input';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import resolve from 'rollup-plugin-node-resolve';
import copy from 'rollup-plugin-copy'
import postcss from 'rollup-plugin-postcss';
import postcssUrl from 'postcss-url';
import asset from "rollup-plugin-smart-asset";
export default {
input: ['src/index.js', 'src/Components/**/*.js'],
output: [
{
dir: './',
format: 'cjs',
sourcemap: true,
exports: 'auto',
chunkFileNames: '__chunks/[name]_[hash].js'
}
],
plugins: [
multiInput({relative: 'src/'}),
external(),
postcss({
modules: false,
extract: true,
minimize: true,
sourceMap: true,
plugins: [postcssUrl({url: 'inline', maxSize: 1000})],
}),
copy({targets: [{src: 'src/static/icons/fonts/*', dest: 'fonts'}]}),
babel({exclude: 'node_modules/**'}),
asset({url: 'copy', keepImport: true, useHash: false, keepName: true, assetsPath: 'assets/'}),
resolve(),
commonjs({include: 'node_modules/**'})
]
};
提前感谢您的回复!
解决方案
推荐阅读
- salesforce - 在 Salesforce 中,是否有任何 API 可以获取已连接应用程序的 IDP URL?
- r - 将不带引号的字符参数列表传递给 apply/map/pmap 调用
- android - “SinchClient 未启动” android studio 中的主要问题
- flutter - Showcase 小部件中的空指针异常
- go - 读取 utf-8 并替换错误
- c# - AutoMapper 工厂方法和声明
- java - 内部连接联合不同数量的列
- javascript - 无法获取 /socket.io/1/
- javascript - 将组件添加到 React 页面的问题
- c# - 为什么 Unity 游戏运行的时间越长,帧数就会大幅下降?