5

我正在尝试使用rollup.js创建 2 个单独的构建:application.jsdependencies.js,分别包含我的应用程序代码和公共库代码(reactreact-dom等)。

文档说我应该能够简单地使用externals: ['react', 'react-dom']它并让它工作 - 但是当我检查生成的包时,我仍然最终包含了两个库的完整主体。这是我的例子app.config.js,我称之为rollup -c app.config.js

我究竟做错了什么?

import babel       from 'rollup-plugin-babel'
import commonjs    from 'rollup-plugin-commonjs'
import nodeResolve from 'rollup-plugin-node-resolve'
import replace     from 'rollup-plugin-replace'
import uglify      from 'rollup-plugin-uglify'
import { keys }    from 'lodash'    

const PRODUCTION = (process.env.NODE_ENV || 'development') === 'production'
const ENVIRONMENT = JSON.stringify(PRODUCTION ? 'production' : 'development')

const EXTERNALS = {
  'react': 'React',
  'react-dom': 'ReactDOM',
}

const plugins = [
  replace({ 'process.env.NODE_ENV': ENVIRONMENT }),
  babel({
    babelrc: false,
    exclude: ['node_modules/**', '**/*.json'],
    presets: ['es2015-rollup', 'react'],
  }),
  commonjs({
    ignoreGlobal: false,
    include: ['node_modules/**'],
  }),
  nodeResolve({
    browser: true,
    jsnext: true,
    main: true,
    preferBuiltins: false,
  }),
]

if (PRODUCTION) {
  plugins.push(uglify())
}

export default {
  entry: 'source/application.js',
  exports: 'none',
  external: keys(EXTERNALS),
  globals: EXTERNALS,
  plugins,
  targets: [{
    dest: 'build/js/application.js',
    format: 'iife',
    sourceMap: !PRODUCTION,
    sourceMapFile: '/js/application.js',
  }],
  treeshake: true,
}
4

1 回答 1

5

我找到的答案是在rollup-plugin-node-resolve插件调用中包含一个附加参数,如下所示:

nodeResolve({
  ignoreGlobal: false,
  include: ['node_modules/**'],
  skip: keys(EXTERNALS), // <<-- skip: ['react', 'react-dom']
}),

这显然是需要的,以便插件在其他包含的库导入它们时rollup-plugin-node-resolve知道skip导入这些外部依赖项。node_modules

例如:import someReactLib from 'some-react-lib'使用import React from 'react'. 如果没有skip语言,这似乎会导致React整体捆绑。

于 2017-01-02T19:08:17.890 回答