npm
installed on your computer. (You don't have it? Install Node.js here .)Rollup is the next generation tool for batch processing JavaScript modules. Build your application or library using ES2015 modules, then merge them into one file for efficient use in browsers and Node.js. This is similar to using Browserify and webpack. You can also call the Rollup a construction tool, which is on a par with tools like Grunt and Gulp. However, it is important to note that, although you can use Grunt and Gulp to solve JavaScript batch processing tasks, these tools will use similar Rollup, Browserify, or webpack functionality.
learn-rollup/
βββ build/
β βββ index.html
βββ src/
β βββ scripts/
β β βββ modules/
β β β βββ mod1.js
β β β βββ mod2.js
β β βββ main.js
β βββ styles/
β βββ main.css
βββ package.json
# Move to the folder where you keep your dev projects. cd /path/to/your/projects # Clone the starter branch of the app from GitHub. git clone -b step-0 --single-branch https://github.com/jlengstorf/learn-rollup.git # The files are downloaded to /path/to/your/projects/learn-rollup/
build/index.html
into your own code. HTML is not covered in this manual. npm install --save-dev rollup
rollup.config.js
in the learn-rollup
folder. Add the following to it. export default { entry: 'src/scripts/main.js', dest: 'build/js/main.min.js', format: 'iife', sourceMap: 'inline', };
./node_modules/.bin/rollup -c
build
in your project with a js
subfolder that will contain our generated main.min.js
file.build/index.html
in our browser:src/scripts/modules/mod1.js
there is a function sayGoodbyeTo ()
, which is not used in our application - and since it is never used, Rollup does not include it in the final package: (function () { 'use strict'; /** * Says hello. * @param {String} name a name * @return {String} a greeting for `name` */ function sayHelloTo( name ) { const toSay = `Hello, ${name}!`; return toSay; } /** * Adds all the values in an array. * @param {Array} arr an array of numbers * @return {Number} the sum of all the array values */ const addArray = arr => { const result = arr.reduce((a, b) => a + b, 0); return result; }; <habracut/> // Import a couple modules for testing. // Run some functions from our imported modules. const result1 = sayHelloTo('Jason'); const result2 = addArray([1, 2, 3, 4]); // Print the results on the page. const printTarget = document.getElementsByClassName('debug__output')[0]; printTarget.innerText = `sayHelloTo('Jason') => ${result1}\n\n` printTarget.innerText += `addArray([1, 2, 3, 4]) => ${result2}`; }()); //# sourceMappingURL=data:application/json;charset=utf-8;base64,...
sayGoodbyeTo ()
function is sayGoodbyeTo ()
, and the resulting packet is more than twice the size that the Rollup generates. # Install Rollup's Babel plugin. npm install --save-dev rollup-plugin-babel # Install the Babel preset for transpiling ES2015. npm install --save-dev babel-preset-es2015 # Install Babel's external helpers for module support. npm install --save-dev babel-plugin-external-helpers
.babelrc
..babelrc
in the project root directory (learn-rollup/
). Inside, add the following JSON: { "presets": [ [ "es2015", { "modules": false } ] ], "plugins": [ "external-helpers" ] }
2.15.11
) you may see an error with the es2015-rollup
preset. If you cannot upgrade npm
, see this problem for an alternative .babelrc
configuration..babelrc
video uses outdated configuration. See this pull request for configuration changes , and this for changes to package.json
.rollup.config.js
. // Rollup plugins import babel from 'rollup-plugin-babel'; export default { entry: 'src/scripts/main.js', dest: 'build/js/main.min.js', format: 'iife', sourceMap: 'inline', plugins: [ babel({ exclude: 'node_modules/**', }), ], };
exclude
property to ignore the node_modules
directory. ./node_modules/.bin/rollup -c
addArray ()
function: var addArray = function addArray(arr) { var result = arr.reduce(function (a, b) { return a + b; }, 0); return result; };
(arr.reduce ((a, b) => a + b, 0))
into a regular function.Array.prototype.reduce ()
available in IE8 and earlier versions. npm install --save-dev rollup-plugin-eslint
.eslintrc.json
. $ ./node_modules/.bin/eslint --init ? How would you like to configure ESLint? Answer questions about your style ? Are you using ECMAScript 6 features? Yes ? Are you using ES6 modules? Yes ? Where will your code run? Browser ? Do you use CommonJS? No ? Do you use JSX? No ? What style of indentation do you use? Spaces ? What quotes do you use for strings? Single ? What line endings do you use? Unix ? Do you require semicolons? Yes ? What format do you want your config file to be in? JSON Successfully created .eslintrc.json file in /Users/jlengstorf/dev/code.lengstorf.com/projects/learn-rollup
.eslintrc.json
: { "env": { "browser": true, "es6": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } }
.eslintrc.json
ENV
, so we need to whitelist it..eslintrc.json
setting - the globals
property and the indent
property setting: { "env": { "browser": true, "es6": true }, "globals": { "ENV": true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } }
rollup.config.js
// Rollup plugins import babel from 'rollup-plugin-babel'; import eslint from 'rollup-plugin-eslint'; export default { entry: 'src/scripts/main.js', dest: 'build/js/main.min.js', format: 'iife', sourceMap: 'inline', plugins: [ eslint({ exclude: [ 'src/styles/**', ] }), babel({ exclude: 'node_modules/**', }), ], };
./node_modules/.bin/rollup -c
, nothing seems to happen. The fact is that the application code in its current form passes linter without problems. $ ./node_modules/.bin/rollup -c /Users/jlengstorf/dev/code.lengstorf.com/projects/learn-rollup/src/scripts/main.js 12:64 error Missing semicolon semi 1 problem (1 error, 0 warnings)
require
.debug
package. Start by installing it: npm install --save debug
src/scripts/main.js
, let's add simple logging: // Import a couple modules for testing. import { sayHelloTo } from './modules/mod1'; import addArray from './modules/mod2'; // Import a logger for easier debugging. import debug from 'debug'; const log = debug('app:log'); // Enable the logger. debug.enable('*'); log('Logging is enabled!'); // Run some functions from our imported modules. const result1 = sayHelloTo('Jason'); const result2 = addArray([1, 2, 3, 4]); // Print the results on the page. const printTarget = document.getElementsByClassName('debug__output')[0]; printTarget.innerText = `sayHelloTo('Jason') => ${result1}\n\n`; printTarget.innerText += `addArray([1, 2, 3, 4]) => ${result2}`;
$ ./node_modules/.bin/rollup -c Treating 'debug' as external dependency No name was provided for external module 'debug' in options.globals β guessing 'debug'
rollup-plugin-node-resolve
, which allows you to load third-party modules from node_modules
.rollup-plugin-commonjs
, which provides support for connecting CommonJS modules. npm install --save-dev rollup-plugin-node-resolve rollup-plugin-commonjs
rollup.config.js
// Rollup plugins import babel from 'rollup-plugin-babel'; import eslint from 'rollup-plugin-eslint'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; export default { entry: 'src/scripts/main.js', dest: 'build/js/main.min.js', format: 'iife', sourceMap: 'inline', plugins: [ resolve({ jsnext: true, main: true, browser: true, }), commonjs(), eslint({ exclude: [ 'src/styles/**', ] }), babel({ exclude: 'node_modules/**', }), ], };
jsnext
property provides simple migration of ES2015 modules for Node packages . The main
and browser
properties help the plugin decide which files to use for the package../node_modules/.bin/rollup -c
, then check the browser again to see the result:ENV
IN main.js
src/scripts/main.js
, change the way we initialize our log()
: // Import a logger for easier debugging. import debug from 'debug'; const log = debug('app:log'); // The logger should only be disabled if we're not in production. if (ENV !== 'production') { // Enable the logger. debug.enable('*'); log('Logging is enabled!'); } else { debug.disable(); }
(./node_modules/.bin/rollup -c)
and see the browser, we will see that this gives us a ReferenceError
for ENV
.ENV = production ./node_modules/.bin/rollup -c
, it will not work anyway. This is due to the fact that setting the variable environment in this way makes it available only to the Rollup, and not to the package created using the Rollup.rollup-plugin-replace
, which is essentially just a find-and-replace utility. It can do many things, but for our purposes we will simply find the appearance of the environment variable and replace it with the actual value (for example, all occurrences of ENV
will be replaced with βproductionβ in the assembly). npm install --save-dev rollup-plugin-replace
rollup.config.js
rollup.config.js
and add it to our list of plugins. // Rollup plugins import babel from 'rollup-plugin-babel'; import eslint from 'rollup-plugin-eslint'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; export default { entry: 'src/scripts/main.js', dest: 'build/js/main.min.js', format: 'iife', sourceMap: 'inline', plugins: [ resolve({ jsnext: true, main: true, browser: true, }), commonjs(), eslint({ exclude: [ 'src/styles/**', ] }), babel({ exclude: 'node_modules/**', }), replace({ exclude: 'node_modules/**', ENV: JSON.stringify(process.env.NODE_ENV || 'development'), }), ], };
NODE_ENV=production ./node_modules/.bin/rollup -c
SET NODE_ENV = production ./node_modules/.bin/rollup -c
to avoid errors when working with environment variables. If you have problems with this command, see this problem for more information.rollup-plugin-uglify
. npm install --save-dev rollup-plugin-uglify
rollup.config.js
// Rollup plugins import babel from 'rollup-plugin-babel'; import eslint from 'rollup-plugin-eslint'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import uglify from 'rollup-plugin-uglify'; export default { entry: 'src/scripts/main.js', dest: 'build/js/main.min.js', format: 'iife', sourceMap: 'inline', plugins: [ resolve({ jsnext: true, main: true, browser: true, }), commonjs(), eslint({ exclude: [ 'src/styles/**', ] }), babel({ exclude: 'node_modules/**', }), replace({ ENV: JSON.stringify(process.env.NODE_ENV || 'development'), }), (process.env.NODE_ENV === 'production' && uglify()), ], };
uglify ()
, NODE_ENV
Β«productionΒ». NODE_ENV=production ./node_modules/.bin/rollup -c
build/js/main.min.js
:Source: https://habr.com/ru/post/331412/
All Articles