Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External dependencies are incorrectly bundled in rollup.js?

I am trying to create 2 separate builds using rollup.js: application.js and dependencies.js, contaning my application code, and common library code (react, react-dom, etc.), respectively.

The docs say I should be able to simply use externals: ['react', 'react-dom'] and have it work - but when I inspect the resulting bundle, I still wind up having the full body of both libs included. Here's my example app.config.js, which I call using rollup -c app.config.js:

What am I doing wrong?

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,
}
like image 665
Troy Alford Avatar asked Jan 02 '17 19:01

Troy Alford


1 Answers

The answer I found was to include an additional argument to the rollup-plugin-node-resolve plugin call, as follows:

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

This is apparently needed, so that the rollup-plugin-node-resolve plugin knows to skip importing these external dependencies when other node_modules included libraries import them.

e.g.: import someReactLib from 'some-react-lib' which uses import React from 'react'. Without the skip language, this seems to result in pulling in React to the overall bundle.

like image 140
Troy Alford Avatar answered Sep 25 '22 15:09

Troy Alford