Redundant code goes away--front-end Module packaging tool Rollup.js Getting Started

Source: Internet
Author: User

Previously translated an article, introduced by the ES2015 the Deconstruction assignment syntax introduces the module, can let the packing tool (browserify) finally compiles the code quantity to minimize.

But in the Webpack 1.X version is unable to use this feature to avoid the introduction of redundant module code, resulting in the bundle file size is inevitably slightly bloated.

Today you will be introduced to a popular fried chicken--rollup.js, through which you can minimize the bundle and effectively reduce the size of the file request-so that even vue can quickly turn to it to pack modules.

Tree-shaking

In the process of compiling the Rollup module, the Tree-shacking method is used to reject the methods that are not ultimately referenced in the modules, and the bundle size is reduced by preserving only the code blocks that are called.

Let's look at the example of Xia Guan Net.

Page entry file Main.js:

Import {cube} from './maths.js '//  125, or 5 cubic value

The Math.js modules cited are as follows:

// Note that this method has not been called in the portal file. // will eventually be Rollup . function Square (x) {    return x * x;} // the method by which the import file needs to call the cube value function Cube (x) {    return x * x * x;}

After packing through Rollup, the following:

' Use strict '; function Cube (x) {    //  rewrite this as ' Square (x) * x '    //and see what happens !    return x * x *//  

It is evident that Tree-shaking's role in the--math module has a square method that has never been used, and we've wiped it out in the bundle file.

In addition, TS extracts the referenced module contents, puts them under the same scope, and then accesses the interface of each module directly with the variable name, rather than webpack a layer of function definitions in addition to each module, and then calls each other through the merged define/require.

Of course, this method needs ES2015 the deconstruction assignment syntax to match, thanks to it, the Rollup can effectively carry on the reliable static analysis to the module content.

How to use

Install naturally needless to say, take NPM's old routine:

NPM I Rollup

The way to do packaging is also simple to explode:

Rollup Src/main.js-o rel/bundle.js

This means that the portal file src/main.js is packaged as a rel/bundle.js file.

Many times we develop the ES2015 module syntax, but eventually the compiled module wants it to go COMMONJS syntax, just add the- F cjs Runtime parameters (F for format) :

Rollup Src/main.js-o rel/bundle.js-f CJs

Of course, if you want to compile to another format, you can change the CJS to:

AMD/  ES6/IIFE/UMD

Let's make a reference ~ assuming that the entry file Src/main.js is as follows:

var name = ' Vajoy '; function Main () {    default main;

Bundles compiled into various modes:

//////////////////////////////commonjs (-f CJS)' Use strict ';varname = ' Vajoy ';functionMain () {console.log (name);} Module.exports=main;//////////////////////////////AMD (-f AMD)Definefunction() {' Use strict '; varname = ' Vajoy '; functionMain () {console.log (name); }    returnmain;});//Es2015/es6 (-f ES6)varname = ' Vajoy ';functionMain () {console.log (name);} Exportdefaultmain;//////////////////////////////global (-f Iife)//Note that this method needs to be executed in the form of a configuration file (see the next section)varMain = (function () {    ' Use strict '; varname = ' Vajoy '; functionMain () {console.log (name); }    returnmain;} ());//////////////////////////////UMD (-f UMD)//Note that this method needs to be executed in the form of a configuration file (see the next section)(function(Global, factory) {typeofExports = = = ' object ' &&typeofModule!== ' undefined '? Module.exports =Factory ():typeofdefine = = = ' function ' && define.amd?define (Factory): (Global.main=Factory ());} ( This,function() {' Use strict '; varname = ' Vajoy '; functionMain () {console.log (name); }    return( Main;}));

Configuration file

Like Webpack, rollup also supports more flexible functionality through configuration files.

We create a new rollup.config.js in the project root directory:

default {  ' src/main.js ',  ' CJs ',  //  output file };

And then execute

Rollup-c

Can be packaged using the information set by the default configuration file (rollup.config.js) .

If your profile has a different name (for example, "Rollup.config.dev.js"), add the following configuration file name:

Rollup-c Rollup.config.dev.js

Rollup also supports the use of plug-ins, written to the configuration object plugin, here we take Rollup-plugin-babel as an example:

Import Babel from ' Rollup-plugin-babel 'default  {  ' src/main.js ',  ' CJs ' ,  plugins: [Babel ()],  ' rel/bundle.js '};

Rather uncomfortable, Babel presets are not like Webpack can be written directly in the configuration file, but still have to write a "SRC/.BABELRC"(note that we can write under SRC, rather than have to be placed in the project root directory):

{  "presets": ["Es2015-rollup"]}

Note that we have to make sure that the Rollup-plugin-babel and Babel presets are installed Babel-preset-es2015-rollup:

NPM I Rollup-plugin-babel Babel-preset-es2015-rollup

This time can be combined with Babel to the ES6 module compiled into ES5 bundle.

More interesting plug-ins can be found in the Rollup Project organization, seemingly no webpack as a special plug-in List page summary, which is not easy to find.

Rollup is also supported directly in the module to be called to execute, so it is convenient to work with Grunt/gulp and other tools to collaborate.

If we modify the Rollup.config.dev.js content as follows:

var rollup = require (' rollup ' ); var babel = require (' Rollup-plugin-babel '); Rollup.rollup ({    ' src/main.js ')    ,  function  (bundle) {    bundle.write ({        ' UMD ',        ///UMD or Iife mode, If the entry file contains export, you must add the attribute        dest: ' Rel/bundle.js '    }) ;

And then execute it directly with node.

Node Rollup.config.dev.js

You can get the same execution results.

Note that "Rollup.rollup ()" Returns a Promise object with the bundle as the resolve callback parameter, and we routinely package the output file directly using the syntax sugar bundle.write:

    bundle.write ({        ' UMD ',        ' main ',        ' rel/bundle.js '    });

It is equivalent to

  var // generate a bundle + Sourcemap    Format: ' UMD ',    ' main ',    ' rel/bundle.js ',  });  ' Rel/bundle.js ', result.code);

Sourcemap

To facilitate debugging of compiled files, rollup certainly won't forget to add the source Map feature, and its configuration is simple:

    {        '        UMD ', ' main ',        ' rel/bundle.js ',        true   // plus here you can    }

After this is compiled, rollup automatically generates a REL/BUNDLE.JS.MAP association to Rel/bundle.js.

It can also be directly inline in the bundle instead of generating a map file independently:

    {        ' UMD ',        ' main ',        ' rel/bundle.js ',        ' inline '    } 

If you want the map file to be able to customize the location and name, you have to use the Bundle.generate method mentioned above:

  var // generate a bundle + Sourcemap    // ...   });  ' Rel/bundle.js ', Result.code);  ' Map/bundle.js.map ', result.map.toString ());

Issue

Rollup Although the use of ES6 features help save a lot of file size, but it does not resemble the Webpack-p parameter to help you compress the confusing file.

Therefore, even official documents are recommended for use with UGLIFYJS to further reduce bundle volume.

In addition Webpack2 has come out several beta version, the same also added to the support of tree-shaking, I believe webpack2 out, Rollup heat will greatly reduce.

Mutual Encouragement ~

Redundant code goes away--front-end Module packaging tool Rollup.js Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.