【问题标题】:Creating a tree shakable library with rollup使用汇总创建可摇树的库
【发布时间】:2019-11-08 13:18:36
【问题描述】:

我正在尝试创建一个组件库 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";

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

我做错了什么?

【问题讨论】:

  • 我相信每个导出都应该在一个单独的文件中,这样你的导入看起来像:import Anchor from "red-components-with-rollup/Anchor";

标签: javascript vue.js bundling-and-minification rollup tree-shaking


【解决方案1】:

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"

【讨论】:

    【解决方案2】:

    this 文章介绍了一些您可能感兴趣的关于摇树的有趣陷阱。

    除此之外 - 您的消费者应用程序的构建工具是否支持纯 es 模块并具有摇树功能?如果是这样,那么我会确保您导出的文件没有做任何可能混淆汇总的“副作用”事情。

    为了安全起见,我会为您的每个组件提供直接导入以及导出它们的一个主要 index.js。至少你给那些偏执于运送未使用代码的人提供了选择,即 -

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

    【讨论】:

    • 我见过这种做法,但一直不明白如何实现它。有没有机会解释一下如何配置一个库,以便它可以同时具有两种导出方法?
    猜你喜欢
    • 2019-08-15
    • 2023-03-13
    • 2017-03-18
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多