rollup 是否将 node_modules 捆绑到 bundle.js 中?

Does rollup bundle node_modules into bundle.js?

我正在试驾 rollupjs 将节点应用程序打包成 bundle.js 并且感到困惑。

Does rollup support bundling a full node app (including node_modules), or just the js files that are part of your project?

我有一个标准节点项目(1 index.jsnode_modules 中有数千个文件)并且只想要一个 bundle.js。我试过了:

rollup.config.js:

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

export default {
entry: 'index.js',
dest: 'bundle.js',
format: 'iife',
plugins: [

    commonjs({
        // non-CommonJS modules will be ignored, but you can also
        // specifically include/exclude files
        include: 'node_modules/**',  // Default: undefined

        // if true then uses of `global` won't be dealt with by this plugin
        ignoreGlobal: false,  // Default: false

        // if false then skip sourceMap generation for CommonJS modules
        sourceMap: false,  // Default: true
    }),

    nodeResolve({
    jsnext: true,
    main: false
    })
]
};

无论我尝试什么 rollup 都会变成这个 index.js:

module.exports = require('dat-node') // 88 MB node_modules

使用此命令:

rollup index.js --format iife --output dist/bundle.js -c

到这个 bundle.js 而不添加来自 node_modules 的任何内容:

(function () {
'use strict';

module.exports = require('dat-node');

}());

我试过了:

现在我在想,可能我对rollup的理解不正确,它不支持我想要的。非常感谢帮助!

试试这个:

import commonjs from "rollup-plugin-commonjs";
import nodeResolve from "rollup-plugin-node-resolve";

export default {
  entry      : "index.js",
  dest       : "bundle.js",
  moduleName : "myModule",
  format     : "iife",
  plugins    : [
    commonjs({
      // non-CommonJS modules will be ignored, but you can also
      // specifically include/exclude files
      include: [ "./index.js", "node_modules/**" ], // Default: undefined

      // if true then uses of `global` won't be dealt with by this plugin
      ignoreGlobal: false, // Default: false

      // if false then skip sourceMap generation for CommonJS modules
      sourceMap: false // Default: true
    }),

    nodeResolve({
      jsnext: true,
      main: false
    })
  ]
};

主要变化是您还需要在 commonjs 调用中包含 index.js,否则它不会转换为 ES6 模块(这就是 nodeResolve需要)。

您还需要设置moduleName

注意:我没有专门用 dat-node 测试,但是用 lodash.

我遇到了同样的问题并进行了很多搜索,但答案大多是旧语法。经过一番搜索,这对我有用。 我不是 100% 确定这是最好的方法。

It would be very helpful if someone more knowledgeable on rollup would verify it

所以我发现诀窍是将 modulesOnly 选项添加到 nodeResolve 插件,如下所示:

import nodeResolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";

export default {
  input: "src/index.js",
  output: [
    {
      format: "cjs",
      file: "dist/index.cjs.js",
    },
    {
      format: "esm",
      file: "dist/index.esm.js",
    },
  ],
  plugins: [
    commonjs(),
    nodeResolve({ modulesOnly: true }),
  ],
};