This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

This article is based on rollup packaging, configuring its output format, and talking about the differences in modular specifications

rollup.rollup

Rollup provides the rollup. Rollup API

  • Receives an input option objectinputOptionsAs a parameter
  • Returns aPromise
  • Parse out abundleObject, while callingbundle.writeMethod, output configurationoutputOptionsAs a pass parameter, the result of the package is written to disk

This API works with Gulp to make custom packaging easier

The sample code

Package. json add command

 "build:demo": "gulp --gulpfile build-demo.mjs"
Copy the code

Demo. ts as the entry file

export const add: Function = (. arr: number[]) = > {
  return arr.reduce((acc, item) = > acc + item, 0)}Copy the code

build-demo.mjs

import path from 'path'
import gulp from 'gulp'
import { rollup } from 'rollup'
import typescript from 'rollup-plugin-typescript2'
const { resolve } = path

const formats = ['es'.'amd'.'cjs'.'iife'.'umd'.'system'] // The output format is optional
formats.map((format) = > {
  gulp.task(`${format}`.() = > {
    return rollup({
      input: './demo.ts'.plugins: [
        typescript({
          tsconfigOverride: {
            compilerOptions: {
              declaration: false.// Do not generate a type declaration file
            },
          },
        }),
      ],
    }).then((bundle) = > {
      return bundle.write({
        file: resolve(`.. /dist/${format}.js`),
        format,
        name: 'demo'.sourcemap: false,})})})})export default gulp.series(formats)
Copy the code

Modular specification

According to the above code, execute NPM run build:demo, corresponding output various formats of the package file

Different output formats for different operating environments

iife

var demo = (function (exports) {
  'use strict';
  const add = (. arr) = > {
      return arr.reduce((acc, item) = > acc + item, 0);
  };
  exports.add = add;
  Object.defineProperty(exports.'__esModule', { value: true });
  return exports; }) ({});Copy the code

Early evolution process of modular implementation:

  • File division: convention a JS file is a module

  • Namespace approach: Each module exposes a global object to which module members are mounted

  • IIFE: use immediate function expressions to provide private space for modules (function () {})())

    • It avoids external access to variables and avoids contaminating the global scope

    • It is executed immediately at definition and is suitable for direct reference using the

cjs

Packaging results for this format:

'use strict';
Object.defineProperty(exports.'__esModule', { value: true });
const add = (. arr) = > {
    return arr.reduce((acc, item) = > acc + item, 0);
};
exports.add = add;

Copy the code

This corresponds to the CommonJS specification, which features:

  • A file is a module, and each module has its own scope

    • Export via exports, as above exports.add = add

    • When using modules, you need to introduce them through the require function

  • Load modules synchronously

    • Suitable for server: Node.js synchronous loading, module files stored in the local disk, fast reading

    • It is not appropriate to use this specification directly on the browser side: if it causes a large number of synchronous load requests, it is limited by the network and inefficient

amd

Browser side suitable for asynchronous loading module, and AMD format corresponding AMD specification: asynchronous module definition specification, so suitable for browser side

define(['exports'], (function (exports) { 'use strict';
  const add = (. arr) = > {
      return arr.reduce((acc, item) = > acc + item, 0);
  };
  exports.add = add;
  Object.defineProperty(exports.'__esModule', { value: true });
}));

Copy the code
  • Implemented based on require.js

  • Use define() to define modules

  • The require() function is used to automatically load modules

    • When a module is loaded, script tags are automatically created internally to request and execute the corresponding module’s code

umd

The corresponding specification is UMD, the Common Module definition specification

This format packages the results, and you can see that there are many conditional (ternary) operators

(function (global, factory) {
  typeof exports= = ='object' && typeof module! = ='undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
  (global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, factory(global.demo = {})); }) (this, (function (exports) { 'use strict';
  const add = (. arr) = > {
      return arr.reduce((acc, item) = > acc + item, 0);
  };
  exports.add = add;
  Object.defineProperty(exports.'__esModule', { value: true });
}));
Copy the code

CommonJS –> AMD –> Other

When defining a module, check the current environment and how the module is defined

  • Set CommonJS, CMD specification in one, can be understood as a specification set

  • Applicable to browser and server

es

The es package results are concise and basically consistent with the sample code

const add = (. arr) = > {
    return arr.reduce((acc, item) = > acc + item, 0);
};
export { add };
Copy the code

The corresponding specification is the ES Modules specification followed by the current mainstream browser environment

ESM features:

  • Module specification defined after ECMAScript 2015 (ES6)

  • Exports makes modules available to external references, which are imported

    Import = import = export

    export { add };
    
    import { add } from 'es.js'
    Copy the code
  • You need to declare that the JS file is a module by putting type=”module” in the

system

SystemJS loader format, support AMD, CommonJS, ES Modules and other formats of JS module loading

System.register('demo', [], (function (exports) {
  'use strict';
  return {
    execute: (function () {
      const add = exports('add'.(. arr) = > {
          return arr.reduce((acc, item) = > acc + item, 0); }); })}; }));Copy the code

Link portal

# JavaScript modules

What problem does # Webpack solve

# What is UMD?

# Front-end engineering: The difference between CommonJS, AMD, CMD, UMD and ES Modules

# SystemJS profile

Last but not least

If there is anything wrong, please give me your advice