Before we do that, let’s take a look at the format types of generated plug-in packages

  • amd– Asynchronous Module Definition, used with Module loaders like RequireJS
  • cjs— CommonJS, Suitable for Node and Other Bundlers (Alias: CommonJS)
  • es— Keep the bundle as an ES module file, suitable for other bundlers and inclusion as a<script type=module> tag in modern browsers (alias: esm, module)
  • iife— A self-executing function, suitable for inclusion as A<script> tag. (If you want to create a bundle for your application, you probably want to use this.)
  • umd— Universal Module Definition, Works as AMD, CJS and iife all in One
  • system— Native format of the SystemJS loader (Alias: SystemJS)

Translate the definitions of these formats

  • amd– Asynchronous module definition, using a module loader such as RequireJS

When it comes to loaders, there are two types of SeaJS and RequireJS that support this format. RequireJS normalizes module definitions in the promotion process and produces AMD, while SeaJS normalizes module definitions in the promotion process and produces CMD.

  • cjs— CommonJS specification for Node modules and other packers, the standard usage ismodule.exports
  • es-ES module file, suitable for other bundled software, and as in modern browsers<script type = module>Tags contain (aliases: ESM, Module)
  • iife– Self-executing functions, suitable for<script>(You may want to use this if you are creating a bundle for your application.)
  • umd– Generic module definition, which can be used simultaneouslyamd.cjsandiife
  • system— Native format of the SystemJS loader (alias: SystemJS)

How to build without a build tool (listing three common format types)

  • iifeformat
var pluginName = (function(){
    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {}
})();
Copy the code
  • umdformat
// if the module has no dependencies, the above pattern can be simplified to; (function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports= = ='object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.pluginName = factory();
  }
}(this.function () {

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {};
}));
Copy the code
  • esformat
function pluginName() {
    // logical code
}

export default pluginName
Copy the code

Wouldn’t it be easy without a build tool? But once you use the latest API, you need to manually implement it yourself. Once you use build tools, you don’t need to worry so much

Compare webPack with Rollup

  • Webpack

    1. Handle various resource dependencies through the Loader
    2. HMR Hot Module Replacement
    3. According to the need to load
    4. Extract common modules
  • Rollup

    1. The compiled code is readable
    2. The bundle generated by rollup is very clean and has no redundant code. It just assembles each module in accordance with the dependent order. All modules are constructed in a function (Scope), and the execution efficiency is higher. Rollup has an unmatched performance advantage over Webpack, which generates runtime code such as __webpack_require__ when packaged, depending on how dependencies are handled, Compile-time dependency handling (rollup) naturally performs better than runtime dependency handling (Webpack)
    3. For ES mode-dependent libraries, rollup statically analyzes imports in code and excludes any code that is not actually used.
    4. Support for application flow analysis, more accurate determination of the side effects of the project code

Why rollup

  • Webpack is dedicated to complex SPA, MPA, SSR and other modular built business framework
  • Rollup is dedicated to creating libraries that perform well

Implement a simple build process manually

  • Create and initialize the directory
mkdir codeDemo && cd codeDemo && npm init -y
Copy the code
  • Install a rollup
NPM I rollup --save-dev # If the installation is successful, you can manually execute 'NPX rollup -h' in the directory to see the helpCopy the code
  • Setting up a Configuration Filerollup
touch rollup.config.js
Copy the code
  • Install the required plug-ins (for example@rollup/plugin-babelAnd other plug-ins for referenceThe official documentation)
npm install --save-dev @rollup/plugin-babel
Copy the code
  • Install the Babel core library and preset tools
npm install --save-dev @babel/core @babel/preset-env
Copy the code
  • The installation@babel/plugin-transform-runtime, you can reuse the helper code injected by Babel to save code size.
npm install --save-dev @babel/plugin-transform-runtime
Copy the code

@babel/plugin-transform-runtime depends on @babel/runtime, so install it.

npm install --save @babel/runtime
Copy the code

Note: The instance method “foobar”.includes(“foo”) only works with core-js@3. If you need to populate them, you can either import “core-js” directly or use the useBuiltIns option of @babel/ PRESET -env.

npm install --save @babel/runtime-corejs3
Copy the code

The dependencies needed for the sample project Babel are temporarily installed, so check the documentation if you want to do anything else

  • The installation@rollup/plugin-commonjsTo convert the built-in module formatcommonjs= >es6
npm install @rollup/plugin-commonjs --save-dev
Copy the code
  • The installation@rollup/plugin-node-resolveIn thenode_modulesTo locate the module
npm install @rollup/plugin-node-resolve --save-dev
Copy the code

Rollup configuration file writes code configuration

const path = require('path')
const { babel } = require("@rollup/plugin-babel");
const commonjs = require("@rollup/plugin-commonjs");
const { nodeResolve } = require("@rollup/plugin-node-resolve");

const pluginName = "xxx_plugin";
const outputDir = "./dist";

function fileFormat(type) {
    return path.join(__dirname, outputDir, `xxx_plugin.${type}.js`)}export default {
	input: path.resolve(__dirname, "./src/main.js"),
	output: [{name: pluginName,
			format: "es".file: fileFormat('es')}, {name: pluginName,
			format: "umd".file: fileFormat('umd')}, {name: pluginName,
			format: "iife".file: fileFormat('iife')}, {name: pluginName,
			format: "amd".file: fileFormat('amd')}, {name: pluginName,
			format: "cjs".file: fileFormat('cjs'),
			exports: "auto"}].plugins: [
		commonjs(),
        /* @babel/preset-env and @babel/plugin-transform-runtime have two configurations, and only one is recommended */
		babel({
			exclude: /\/node_modules\//,
			presets: [
				[
					"@babel/preset-env",
					{
						targets: "> 0.25%, not dead." " /* Configuration compatibility degree */}]],plugins: [["@babel/plugin-transform-runtime",
                    {
                        "corejs": 3."regenerator": true}]],babelHelpers: "runtime"
		}),
		nodeResolve()
	]
};

Copy the code

Create a project catalog

  • srcDirectory: place source code, need an entry file, configuration fileinputThe entry file for the Settings ismain.js
  • distDirectory: Output location after compilation

Configure the package.json file

Find the scripts field

"scripts": {
    "watch": "rollup -c --watch"."build": "rollup -c"
}
Copy the code

Before packaging, delete the remaining packages first. Let’s use a simple and violent way to solve this problem. Install a Rimraf and delete the dist output directory before packaging

npm install rimraf --save-dev
Copy the code

Then configure scripts

"scripts": {
    "watch": "rollup -c --watch --environment NODE_ENV:development"."build": "rimraf dist && rollup -c --environment NODE_ENV:production"
}
Copy the code
  • “-c, –config”: select the configuration file to run, defaultrollup.config.js
  • “–environment”: configures running environment variables and distinguishes them. Multiple environment variables are used.Separate and:Assign, do not assign defaultbooleanType true, for example--environment NODE_ENV:production,test

Click here for more rollup parameters

Development compile and package

Once you’ve configured the package.json file, you’re happy to compile and package

  • compile
npm run watch
Copy the code
  • packaging
npm run build
Copy the code

Finally, attached is the dependent version I used at that time

  • Example demo address point here
  • If need to be reproduced, please indicate the source, thank you