Skip to content

Instantly share code, notes, and snippets.

@gilesdring
Last active May 16, 2019 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilesdring/8c73ca48086824e9aae48c2bd067e87c to your computer and use it in GitHub Desktop.
Save gilesdring/8c73ca48086824e9aae48c2bd067e87c to your computer and use it in GitHub Desktop.
Setting up a project for React with Rollup.js

Install required Rollup stuffs

npm install --save-dev rollup rollup-plugin-babel rollup-plugin-commonjs \
    rollup-plugin-copy rollup-plugin-node-resolve rollup-plugin-replace \
    rollup-plugin-uglify

Install required Babel stuffs

npm install --save-dev @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/preset-react @babel/runtime

Create the rollup.config.js file as defined below.

Add the following npm scripts:

  "build:rollup": "rollup --config",

If you run this with NODE_ENV=production (or in fact anything other than development), the resulting code will be minified. The target defaults to production.

import replace from 'rollup-plugin-replace';
import babel from 'rollup-plugin-babel';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import { uglify } from 'rollup-plugin-uglify';
import copy from 'rollup-plugin-copy';
const targetDir = 'public/js';
// Grab the NODE_ENV and store in targetEnv, default to 'production' if undefined
const { NODE_ENV: targetEnv = 'production' } = process.env;
// Work out if we're targetting development
const isDev = (targetEnv === 'development');
// Define baseline plugins for transformation
const jsPlugins = [
replace({
'process.env.NODE_ENV': JSON.stringify(targetEnv),
}),
babel({
configFile: false, // Read config from here, not babel config file
runtimeHelpers: true, // Include runtime Helpers
exclude: 'node_modules/**', // Only transpile our source code
presets: [ // Setup presets
['@babel/env', {
modules: false
}],
['@babel/react', {}],
],
plugins: [ // Setup plugins
'@babel/transform-runtime'
],
}),
resolve(),
commonjs(),
isDev || uglify(), // Uglify code unless we're targetting 'development'
copy({ // Copy modules to the vendor directory
targets: [
'node_modules/react/umd/react.development.js',
'node_modules/react/umd/react.production.min.js',
'node_modules/react-dom/umd/react-dom.development.js',
'node_modules/react-dom/umd/react-dom.production.min.js',
],
outputFolder: `${targetDir}/vendor`,
}),
];
export default [
{
input: 'src/main.js',
plugins: jsPlugins,
external: ['react', 'react-dom'],
output: {
dir: targetDir,
format: 'iife',
globals: {
react: 'React',
'react-dom': 'ReactDOM',
},
},
},
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment