tobbe
tobbe

Reputation: 1807

Import npm packages

How should I import npm packages? If I just add lodash bundling goes from 6ms to 900ms!? Is there no way to cache static dependencies? If I add lodash to external, globals and customResolveOptions in rollup.config.js it is excluded from the bundle. But how could I add it in a libs.js file for example?

Here are my files:

app.js

import _ from 'lodash'

alert(_.concat(["hi", "hello"]))

rollup.config.js

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
import babel from 'rollup-plugin-babel';

const production = !process.env.ROLLUP_WATCH;

export default {
    input: 'src/index.js',
    output: {
        file: 'scripts/bundle.js',
        format: 'iife',
        sourcemap: true
    },
    plugins: [
        resolve(),
        commonjs(),
        babel({
          exclude: 'node_modules/**'
        }),
        production && uglify()
    ]
};

package.json

{
  "devDependencies": {
    "npm-run-all": "^4.1.2",
    "rollup": "^0.55.5",
    "rollup-plugin-commonjs": "^8.0.2",
    "rollup-plugin-node-resolve": "^3.0.0",
    "rollup-plugin-uglify": "^3.0.0",
    "babel-core": "^6.26.3",
    "babel-plugin-external-helpers": "^6.22.0",
    "babel-preset-env": "^1.7.0",
    "rollup-plugin-babel": "^3.0.4"
  },
  "dependencies": {
    "lodash": "^4.17.10"
  },
  "scripts": {
    "build": "rollup -c",
    "watch": "rollup -c -w",
    "dev": "npm-run-all --parallel watch"
  },
  ...
}

Upvotes: 0

Views: 251

Answers (1)

nathancahill
nathancahill

Reputation: 10850

You can manually separate the entrypoints for "libs" and source code to speed up your build:

rollup.config.js

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
import babel from 'rollup-plugin-babel';

const production = !process.env.ROLLUP_WATCH;

export default [{
    input: 'src/index.js',
    output: {
        file: 'scripts/bundle.js',
        format: 'iife',
        sourcemap: true,
        globals: {
            'lodash': '_',
        },
    },
    external: ['lodash'],
    plugins: [
        babel(),
        production && uglify()
    ]
}, {
    input: 'src/common.js',
    output: {
        file: 'scripts/common.js',
        format: 'umd',
        name: 'window',
        extend: true,
        sourcemap: true
    },
    plugins: [
        resolve(),
        commonjs(),
        production && uglify()
    ]
}];

common.js

export { default as _ } from 'lodash'

It does add the overhead of maintaining the common.js file with libraries. Personally, I find it gives the best control over file size and compile time. If you're constantly installing and including new npm packages, this will be be hard to maintain.

Upvotes: 1

Related Questions