|
| 1 | +# Rollup |
| 2 | + |
| 3 | +Rollup is a module bundler for JavaScript, and, while there are packages like [`gulp-rollup`] and [`rollup-stream`](https://www.npmjs.com/package/rollup-stream), which aim to help use Rollup with gulp, we can also use `rollup` directly. |
| 4 | + |
| 5 | +Let's say that we require the following features: |
| 6 | + |
| 7 | + - being able to use Node modules |
| 8 | + - interoperability between CommonJS and ES6 modules |
| 9 | + - Babel |
| 10 | + - Uglify in production |
| 11 | + |
| 12 | +To achieve this, we need to install the Rollup and its plugins: |
| 13 | + |
| 14 | +```sh |
| 15 | +npm install --save-dev gulp rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-babel @babel/core @babel/preset-env rollup-plugin-uglify |
| 16 | +``` |
| 17 | + |
| 18 | +Create a basic `babel.config.js`: |
| 19 | + |
| 20 | +```js |
| 21 | +module.exports = { |
| 22 | + presets: ["@babel/preset-env"], |
| 23 | +}; |
| 24 | +``` |
| 25 | + |
| 26 | +Use [Rollup's JavaScript API](https://rollupjs.org/guide/en/#javascript-api) to create tasks for compiling and recompiling: |
| 27 | + |
| 28 | +```js |
| 29 | +const rollup = require("rollup"); |
| 30 | +const nodeResolve = require("@rollup/plugin-node-resolve").default; |
| 31 | +const commonJs = require("@rollup/plugin-commonjs"); |
| 32 | +const babel = require("@rollup/plugin-babel").default; |
| 33 | +const uglify = require("rollup-plugin-uglify").uglify; |
| 34 | + |
| 35 | +const isProd = process.env.NODE_ENV === "production"; |
| 36 | + |
| 37 | +const inputOptions = { |
| 38 | + input: "scripts/index.js", |
| 39 | + plugins: [ |
| 40 | + nodeResolve(), |
| 41 | + commonJs(), |
| 42 | + babel({ babelHelpers: "bundled" }), |
| 43 | + ...(isProd ? [uglify()] : []), |
| 44 | + ], |
| 45 | +}; |
| 46 | + |
| 47 | +const outputOptions = { |
| 48 | + file: `dist/script.js`, |
| 49 | + format: "iife", |
| 50 | + sourcemap: !isProd, |
| 51 | +}; |
| 52 | + |
| 53 | +async function compileScripts() { |
| 54 | + const bundle = await rollup.rollup(inputOptions); |
| 55 | + await bundle.write(outputOptions); |
| 56 | +} |
| 57 | + |
| 58 | +function compileAndWatchScripts() { |
| 59 | + // this function already creates a build initially, hence the name |
| 60 | + // of the task, so you don't need to run "compileScripts" first |
| 61 | + const watcher = rollup.watch({ |
| 62 | + ...inputOptions, |
| 63 | + output: outputOptions, |
| 64 | + }); |
| 65 | + watcher.on("event", (event) => { |
| 66 | + if (event.code === "END") { |
| 67 | + console.log("Compiled scripts"); |
| 68 | + } |
| 69 | + }); |
| 70 | +} |
| 71 | +``` |
0 commit comments