gpt4 book ai didi

javascript - 使用 rollup 创建一个 tree shakable 库

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:38 24 4
gpt4 key购买 nike

我正在尝试创建一个组件库 wie rollup 和 Vue,当其他人导入它时可以进行树摇动。我的设置如下:

package.json 的相关摘录

{
"name": "red-components-with-rollup",
"version": "1.0.0",
"sideEffects": false,
"main": "dist/lib.cjs.js",
"module": "dist/lib.esm.js",
"browser": "dist/lib.umd.js",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w"
},
"devDependencies": {
/* ... */
}

这是我的整个 rollup.config.js

import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import vue from "rollup-plugin-vue";
import pkg from "./package.json";

export default {
input: "lib/index.js",
output: [
{
file: pkg.browser,
format: "umd",
name: "red-components"
},
{ file: pkg.main, format: "cjs" },
{ file: pkg.module, format: "es" }
],
plugins: [resolve(), commonjs(), vue()]
};

我有一个相当简单的项目结构,包含一个 index.js 文件和 2 个 Vue 组件:

root
∟ lib
∟ index.js
∟ components
∟ Anchor.vue
∟ Button.vue
∟ package.json
∟ rollup.config.js

我的 index.js 导入和导出 Vue 文件:

export { default as Anchor } from "./components/Anchor.vue";
export { default as Button } from "./components/Button.vue";

export default undefined;

如果我不执行 export default undefined; 任何导入我的库的应用都无法找到任何导出。很奇怪。


现在,当我创建另一个应用程序并像这样导入 red-components-with-rollup 时:

import { Anchor } from "red-components-with-rollup";

然后我从我的应用程序中打开 bundle,我还会在我的 bundle 中找到 Button.vue 的源代码,它还没有被删除为死代码。

我做错了什么?

最佳答案

ES格式的构建结果是什么?它是单个文件还是多个文件,类似于您的来源?

考虑到您的 Rollup 选项,我猜它会将所有内容捆绑到一个文件中,这很可能是它无法对其进行 tree-shaking 的原因。

为了让你的 ES 构建成多个文件,你应该改变:

{ file: pkg.module, format: "es" }

进入:

{
format: "es",
// Use a directory instead of a file as it will output multiple
dir: 'dist/esm'
// Keep a separate file for each module
preserveModules: true,
// Optionally strip useless path from source
preserveModulesRoot: 'lib',
}

您需要更新您的 package.json 以将 module 指向新的构建文件,例如 "module": "dist/esm/index.js”

关于javascript - 使用 rollup 创建一个 tree shakable 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56775433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com