【问题标题】:how to include use of node_modules in rollup compile如何在汇总编译中包含使用 node_modules
【发布时间】:2016-12-02 21:30:30
【问题描述】:

我反复收到此消息,我正在尝试将 d3.js 包含到我的分发文件中。

将 'd3.js' 视为外部依赖项

我试过用这个插件

import includePaths from 'rollup-plugin-includepaths';

var includePathOptions = {
  paths: ['node_modules/d3/d3.min.js'],
  include: {
    d3: 'd3'
  },
};

我错过了什么?

【问题讨论】:

  • @gcampbell 不符合fengshuo.co/2016/03/10/…
  • 只有两者都对我有用:@rollup/plugin-node-resolve@rollup/plugin-commonjs 但显然互联网上的一些模块编写得非常糟糕,问题可能出在他们身上,而不是我们可怜的导入灵魂

标签: javascript d3.js rollup


【解决方案1】:

注意:这适用于 d3js v4(我不确定 v3 是否可行)

您需要使用 rollup-plugin-node-resolve 来让汇总了解 node_modules 中的依赖关系。

您通过npm install --save-dev rollup-plugin-node-resolve 安装它 (注意:我是新手,babel 插件可能不是必需的)

rollup.config.js

import babel from 'rollup-plugin-babel';
import nodeResolve from 'rollup-plugin-node-resolve';

export default {
  entry: 'path/to/your/entry.js',
  format: 'umd',
  plugins: [
    babel(),
    nodeResolve({
      // use "jsnext:main" if possible
      // see https://github.com/rollup/rollup/wiki/jsnext:main
      jsnext: true
    })
  ],
  sourceMap: true,
  dest: 'path/to/your/dest.js'
};

必须使用jsnext:main,否则会出现Export '<function>' is not defined by 'path/to/node_module/file.js'之类的错误

取自integrate with rollup and es2015上的帖子

这也记录在 rollup issue #473 中(注意它指的是这个插件 rollup-plugin-npm 的旧名称)

然后你可以通过rollup -c运行汇总

您还需要使用您需要的位“滚动您自己的”d3 模块。这样,您仍然可以使用带有 d3.* 前缀的网络示例。我最初是将相关位导入到我的客户端代码中,但无法将所有这些合并到一个命名空间中。

d3 master module 开始,将代码中需要的所有导出内容粘贴到本地./d3.js 文件中

自滚 d3.js 示例

/* 
 re-export https://github.com/d3/d3/blob/master/index.js for custom "d3" implementation.

 Include only the stuff that you need.
*/

export {
  ascending
} from 'd3-array';

export {
  nest,
  map
} from 'd3-collection';

export {
  csv, json
} from 'd3-request';

export {
  hierarchy,
  tree
} from 'd3-hierarchy';

export {
  select
} from 'd3-selection';

导入你的手卷 d3

import * as d3 from "./d3"

当您导入更多的 d3 时,您只需要让您的 ./d3.js 保持同步,您的客户端代码不会在意。

请记住,您需要在进行任何更改后重新运行汇总。

【讨论】:

  • 你能举例说明如何在 d3 版本 3.x 中实现这一点
  • 对不起,没有。我认为 v3 没有被适当地模块化来允许你做这些事情。但我不是 javascript 专家。
  • 这可以通过 CLI 实现吗?
  • 是的:rollupjs.org/guide down by Using config files and Getting started with plugins
【解决方案2】:

仅供参考 rollup-plugin-node-resolve 已弃用,您应该使用 https://www.npmjs.com/package/@rollup/plugin-node-resolve

npm install @rollup/plugin-node-resolve --save-dev

rollup.config.js:

import { nodeResolve } from '@rollup/plugin-node-resolve';

export default {
  input: 'main.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },
  plugins: [nodeResolve()]
};

使用配置文件和监视模式启动汇总:

rollup -c -w

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 2019-03-29
    • 2020-10-27
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多