Contents summary

  • 1. Modular evolution process
  • 2. Modular specification
  • 3, commonly used modular packaging tools
  • 4. Build modern Web applications based on modular tools
  • 5. Optimization techniques of packaging tools

1. Modular evolution process

File division mode

  • Contamination global scope
  • Name conflict problem
  • Unable to manage module dependencies
The original way is entirely convention dependentCopy the code

Namespace mode

IIFE

Modular specification + module loader

CommonJS
  • A file is a module
  • Each module has a separate scope
  • Exports members through module.exports
  • Load the module via the require function
CommonJS loads modules in synchronous modeCopy the code
AMD(Asynchronous Module Definition)
  • AMD is relatively complex to use
  • Module JS file requests are frequent
require.js
// jQuery is not in the same directory as jquery.js. // Define a module define('module1', ['jquery', './module2'], function ($, module2) {return {start: function () { $('body').animate({ margin: '200px'}) module2()}}}) // Load a module require(['./modules/module1'], function (module1) {module1.start()})Copy the code
Sea.js + CMD
Define (function (require, exports,) Module) {var $= require('jquery') // exports or module.exports = function () { console.log('module 2~') $('body').append('<p>module2</p>') } })Copy the code
Refer to the website

What are the differences between AMD and CMD? Differences between SeaJS and RequireJS Modular development AMD specification Modular development CMD specification modular development CommonJS specification Module syntax and load implementation in ES6

2. Modular specification

  • CommonJS in node.js
  • ES Modules in Browers

ES Modules feature

  • serve .

Feature list

  • Automatically adopt strict mode, ignoring ‘use strict’
  • Each ESM module is a separate private scope
  • ESM requests external JS modules through CORS
  • The ESM’s script tag delays the execution of the script defer

ES Modules Import and export

  • browser-sync . –file **/*.js

You can rename the variable as in the export and use the new renamed name for the import. Notice that default is the keyword.

ES Modules Import and export considerations

{name, hello} is not an object literal

Export default {name, age} this is a reference to the literal object to export the member, memory space reference, reference relationship to the external // it is just a syntax rule export {name, age}Copy the code

ES Modules Import and export Import import

1, path:./ relative path; / absolute path; The full URL;

2. Load the module without extracting it. // import {} from './module.js' // import './module.js' // import * from './module.js' // // import('./module.js'). Then (function (module) {// console.log(module) //) import { name, age, default as title } from './module.js' import abc, { name, Age} from './module.js' // comma left default member console.log(name, age, ABC)Copy the code

ES Modules Import and export directly export the imported members

Create index.js under the component folder to hold all the exported files, note default

ES Modules in Browser Polyfill

Browser ES Module Loader node address: unpkg.com/XXX Two

IE: Promise Polyfill 1 <script nomodule></script> nomodule, working on unsupported browsers is only suitable for development, not productionCopy the code

ES Modules in Node.js

-node –experimental-modules index. MJS -node –experimental-modules index. MJS

Native module Third-party module - YARN Add LoDash Directly extracts members from the module. The built-in module is compatible with the ESM member extraction modeCopy the code

ES Modules in Node.js interact with CommonJS Modules

  • CommonJS modules can be imported into ES Module
  • You cannot import ES Module modules in CommonJS
  • CommonJS always exports only one default member
  • Note that import does not deconstruct the exported object

ES Modules in Node.js and CommonJS Modules

​ nodemon –experimental-modules esm.mjs

// require, module, Exports are naturally imported and exported instead of // __filename and __dirname obtained from the meta attribute of the import object // const currentUrl = import.meta.url // console.log(currentUrl) // Converts to a path through the URL module's fileURLToPath methodCopy the code

ES Modules in Node.js The new version further supports ESM

// After v12, you can use package.json to add the type field module, // If you want to continue using CommonJS with type= Module, // you need to change the file extension to.cjsCopy the code

ES Modules in Node.js Babel compatible scheme

- yarn add @babel/node @babel/core @babel/preset-env --dev - yarn babel-node - yarn babel-node index.js --presets=@babel/preset-env - yarn remove @babel/preset-env - yarn add @babel/plugin-transform-modules-common.js --dev - Yarn Babel-node index.js Preset is a set of plug-insCopy the code

3, commonly used modular packaging tools

ES Modules Are compatible with the environment. There are too many module files and frequent network requests. Modular code compilation is required for all front-end resources: ES6 in the development stage compiles ES5 Modules in the production stage packaging: ES6 in the development stage packs bundle.js Modules in the production stage Development phase (.js.css.scs.hss.png. Ts) package production phase (bundle.js.css.png)Copy the code
  • New feature code compiled
  • Modular JavaScript packaging
  • Supports different types of resource modules

Module packaging tool profile

Webpack Module Loader (Code Splitting) Asset Module

When installing a package for production, you should use NPM install --save. If you are installing a package for development (e.g., Linter, test libraries, etc.), You should use NPM install --save-dev. Please [] NPM document (https://docs.npmjs.com/cli/install) to find more information.Copy the code

Webpack is quick to get started

  • yarn init –yes

  • yarn add webpack webpack-cli –dev

  • yarn webpack –version

  • yarn webpack

    “Scripts “: {“build”: “webpack”}

    Don’t need type=”module” to refer directly to the generated dist directory file

Webpack configuration file

Create webpack.config.js in ‘SRC /index.js’ -> ‘dist/main.js’ root

Module. Exports = {entry: './ SRC /main.js', // Filename: 'bundle.js', // The name of the output object path: path.join(__dirname, 'output') // The absolute path of the output object}}Copy the code

Webpack working mode

  • This property has three values: production, Development, and None.
  • Automatic optimization of packaging results in production mode;
  • In development mode, automatic optimization of packaging speed, add some assistance in the debugging process;
  • In None mode, raw packaging is run without any extra processing
  • yarn webpack

  • yarn webpack –mode development

  • yarn webpack –mode none

    Reference site: webpack.js.org/configurati… Or by using mode: ‘development’

Webpack results run principle

Fast fold Ctrl+ K Ctrl+0

Webpack resource module loaded

  • yarn add css-loader –dev

  • yarn add style-loader –dev

    Module: {rules: [{test: /.css$/, use: [// multiple loaders, execute ‘style-loader’, ‘css-loader’]}]}

    Loader is a core feature of Webpack. With Loader, you can load any type of resources

Webpack imports the resource module

Import resources dynamically based on the needs of the code. It's not the application that needs the resources, it's the code. Javascript drives the whole front-end applicationCopy the code
  • Logically, JS does need these resource files

  • It is necessary to ensure that there is no shortage of online resources

    The idea of something new is the breakthrough

Webpack file resource loader Data URLs and URL-loader

file-loader

{
    test: /.png$/,
    use: 'file-loader'
  }
Copy the code
  • Yarn add file-loader –dev publicPath: ‘dist/’ // Root directory of the website

    Data URLs Data: [<mediatype>][;base64], < Data > protocol; Media type and encoding file content Data :text/ HTML; charset=UTF-8,<h1>html content</h1> data:image/png; base64,iVBORw0KGgoAAAANSUhE... SuQmCCCopy the code

url-loader

  • yarn add url-loader –dev

  • Use Data URLs for small files to reduce the number of requests

  • Large files are individually extracted and accessed to improve loading speed

  • Files exceeding 10KB are extracted and stored separately

  • {test: /. PNG $/, use: {loader: ‘url-loader’, // suitable for small files options: {// add configuration attribute limit: 10 * 1024 // convert files below 10 KB to file-loader}}}

Webpack often uses loader classifications

CSS CSS -loader bundle.js A CSS module that works as JS

PNG file-loader bundle.js Export file access path bar.png Code check class baz.js eslint-loader checks whether baz.js passes or does not passCopy the code

Webpack and ES2015

Since module packaging is required, import and export are handled

  • yarn add babel-loader @babel/core @babel/preset-env –dev

  • Webpack is just a packaging tool

  • The loader can be used to compile the transformation code

    {test: /.js$/, use: {loader: ‘babel-loader’, options: {presets: [‘@babel/preset-env’] // This set includes all the latest ES features}}},

How the Webpack module is loaded

Follow ES Modules standard import declaration follow CommonJS standard require function follow AMD standard define function and require function style code @import and URL function HTML The SRC attribute of the image tag in the codeCopy the code
  • yarn add html-loader –dev

    { test: /.html$/, use: { loader: ‘html-loader’, options: { attrs: [‘img:src’, ‘a:href’] } } }

How the core of Webpack works

​ bundle your assets

The Loader mechanism is at the heart of WebpackCopy the code

How Webpack Loader works

markdown-loader

Module.exports ="" Source -> md-loader -> (other-loader) -> Result(javascript code)Copy the code
  • yarn add marked –dev

  • yarn add html-loader –dev

    { test: /.md$/, use: [ ‘html-loader’, ‘./markdown-loader’ ] }

    const marked = require(‘marked’)

    module.exports = source => { // console.log(source) // return ‘console.log(“hello ~”)’ const html = marked(source) // Exports = “${HTML}” // return module.exports = “${HTML}” // return export default ${json.stringify (HTML)} converts the string to a standard JSON string

    // Return the HTML string to the next loader to process return HTMLCopy the code

    }

    Loader converts resource files from input to output. You can use multiple Loaders for the same resource in sequence CSS-loader -> style-loader

Webpack plugin mechanism

Loader focuses on the realization of resource module loading Plugin to solve other automation work Copy static files to output directory e.g The compressed output code Webpack + Plugin implements most of the front-end engineering work

The clean-webpack-plugin is commonly used for Webpack

Plug-ins that automatically clean output directories, such as the dist directory

  • yarn add clean-webpack-plugin –dev

    const { CleanWebpackPlugin } = require(‘clean-webpack-plugin’)

    Plugins: [// New CleanWebpackPlugin() // Create an instance and place it in an array]

The html-webpack-plugin is commonly used for Webpack

Option multiple instances output HTML files through Webpack

  • yarn add html-webpack-plugin –dev
Const HtmlWebpackPlugin = require('html-webpack-plugin') // publicPath: 'dist/' [new CleanWebpackPlugin(), // Generate index.html new HtmlWebpackPlugin({title: 'Webpack Plugin Sample', meta: { viewport: 'width=device-width' }, template: HTML new HtmlWebpackPlugin({filename: 'about.html'})] : [new CleanWebpackPlugin(), // Generate index.html new HtmlWebpackPlugin({title: 'Webpack Plugin Sample', meta: { viewport: 'width=device-width' }, template: // SRC /index.html' //HTML template file}), // To generate about.html new HtmlWebpackPlugin({// add multiple instance objects, generate multiple HTML files filename: 'about.html' }) ]Copy the code

Copy -webpack-plugin & summary

  • yarn add copy-webpack-plugin –dev

    const CopyWebpackPlugin = require(‘copy-webpack-plugin’)

    Plugins: [new CleanWebpackPlugin(), // To generate index.html new HtmlWebpackPlugin({title: ‘Webpack Plugin Sample’, meta: { viewport: ‘width=device-width’ }, template: // SRC /index.html’ //HTML template file}), // To generate about. HTML add multiple instances of the object new HtmlWebpackPlugin({filename: ‘about.html’}), new CopyWebpackPlugin([// ‘public/**’ ‘public’])]

    The community also provides a number of plug-in requirements – keyword – searches

Developing a plug-in

Plugin has a wider range of capabilities than Loader. Plugin implements a function or an object containing apply methods through the hook mechanism

} console.log('MyPlugin starts ') compiler.hooks. Emit. Tap ('MyPlugin', Compilation => {//hooks, For (const name in compilation.assets) {// console.log(name) // console.log(compilation.assets[name].source()) if (name.endsWith('.js')) { const contents = compilation.assets[name].source() const withoutComments = contents.replace(/\/\*\*+\*\//g, '') compilation.assets[name] = { source: () => withoutComments, size: () => withoutcomments.length //webpack requires required methods}}}})}} new MyPlugin() extends multiple tasks by mounting functions in lifecycle hooksCopy the code

Webpack development experience

Writing source code for Webpack to run the application and refreshing the browser will reduce development efficiency imagine development environment: 1. Running with HTTP Server 2. Auto-compile + Auto-refresh 3. Source Map support is provided

Webpack enhances the development experience

– Yarn webpack — Watch runs in monitor mode – Serve Dist Runs the application in HTTP

Auto-refresh browsersync-browser-sync dist --files "**/*Copy the code

Webpack Dev Server

Provides HTTP Server integration for development, such as auto-compile and auto-refresh browsers

  • yarn add webpack-dev-server –dev

  • Yarn webpack-dev-server Run the yarn webpack-dev-server command to save the package result to the memory temporarily

  • Yarn webpack-dev-server –open Automatically wakes up the browser and opens the page address

    You can preview it while you’re coding

Webpack Dev Server static resource access

Dev Server will only serve output files by default. Any webpack output file can be accessed directly. Other static resource files also need to serve

ContentBase Additionally specifies the search resource directory for the development server devServer: {contentBase: './public', // specify additional static resource paths, strings or arrays} // // It is best not to use this plugin in the development phase // new CopyWebpackPlugin(['public']) to be used in the package before going liveCopy the code

Webpack Dev Server Proxy API service

Cross-domain resource Sharing (CORS) The prerequisite for using CORS is that the API must support it. Not in every case, the API should support same-origin deployment, domain name, protocol, port

DevServer: {contentBase: {GitHub API: devServer: {contentBase: './public', // specify an additional static resource path, string or array proxy: {// Add the proxy service configuration '/ API ': {/ / request path prefix target: / / http://localhost:8080/api/users - > https://api.github.com/api/users 'https://api.github.com', // http://localhost:8080/api/users -> https://api.github.com/users pathRewrite: {// proxy path overridden '^/ API ': '}, // cannot use localhost:8080 as the host name for requesting GitHub changeOrigin: True // Take the actual proxy host name as the request}}}, // ======================== fetch proxy api example main.js======================== const ul = Document.createelement ('ul') document.body.append(ul) // Cross-domain requests. GitHub supports CORS, but not every server should. // fetch('https://api.github.com/users') fetch('/api/users') // http://localhost:8080/api/users .then(res => res.json())  .then(data => { data.forEach(item => { const li = document.createElement('li') li.textContent = item.login ul.append(li) }) }) (https://www.example.com/index.html) | v (https://www.example.com/api/users) (https://localhost/index.html) | v (https://www.example.com/api/users)Copy the code

Source Map

The running code is completely different from the source code. If you need to debug the application, error messages cannot be located. Debugging and error reporting are based on the running code source Source Map(mapping relationship) Compoled

//# sourceMappingURL=jquery-3.4.1.min.map; //# sourceMappingURL=jquery-3.4.1.min.map; Debugging the Source Map solves the problem of inconsistency between the Source code and the running codeCopy the code

Webpack configures the Source Map

Devtool: ‘source-map’, // Source Map-related configuration WebPack supports 12 different packaging methods, each with different efficiency and effectiveness

Devtool: 'eval', packages the back-end module code, knows the corresponding Source code, can only locate the name of the Source code does not know the line informationCopy the code

Differences between different Devtools

Const HtmlWebpackPlugin = require(‘html-webpack-plugin’) // Generate HTML files for each package

Const allModes = ['eval', // Execute module code in eval function, annotate file path through source URL, do not generate source map, // the eval function can be used to locate the error file 'cheap-eval-source-map'. The eval function can be used to locate the error file. 'cheap-module-eval-source-map' //eval to locate error files, only lines, Module is not executed by loader in 'eval-source-map', // it can locate the wrong file, and locate the wrong row and column information. Generate the corresponding source map' cheap-source-map', // No eval to execute the module code, No module is handled by loader: 'cheap-module-source-map', 'inline-cheap-source-map', 'inline-cheap-module-source-map', 'source-map', 'inline-source-map', //data URL embedding, least available 'hidden-source-map', // source-map file is generated, This file is not included in the code; it is useful to use 'nosource-source-map' when developing third-party packages to see the error location, click the error message, enter the source code is not visible, Exports = allModes. Map (item => {//serve Dist Module.exports = allModes. Return {devtool: item, // The name of the traversal mode mode: 'none', // no processing inside webpack entry: './ SRC /main.js', // the entry output: {/ / output filename: ` js / ${item}. Js `}, the module: {rules: [{test: / \. Js $/, use: {loader: Options: {presets: ['@babel/preset-env']}}}]}, presets: ['@babel/preset-env']}}}]}, presets: [ new HtmlWebpackPlugin({ filename: `${item}.html` }) ] } }) // module.exports = [ // { // entry: './src/main.js', // output: { // filename: 'a.js' // } // }, // { // entry: './src/main.js', // output: { // filename: 'b.js' // } // } // ]Copy the code

Select the appropriate Source Map

1. Each line of my code will not exceed 80 characters. 2. Repackings are relatively fast (webPack serve monitor repackings, not every startup repackings) production mode None 1, Source Map will expose Source code 2, debugging is a matter of development phase 3, if you are not confident in the code: nosource-source-map

There is no absolute choice to understand the differences between different modes and adapt to different circumstancesCopy the code

Auto-refresh issues

Option 1: Kill the editor content in code Option 2: extra code to save before refresh, read after refresh

Core problem: Page status loss caused by automatic refresh The module can be updated in time even if the page is not refreshedCopy the code

HMR introduction

Hot Module Replacement: A Module is replaced in real time during application running, without affecting application running status. Hot Module Replacement: A device is removed or replaced at any time on a running machine

Hot replacement only replaces the modified module into the application in real time. HMR is one of the most powerful features in Webpack, which greatly improves the work efficiency of developersCopy the code

Start HMR

Integrated with webpack-dev-serve Webpack-dev-serve — HOT can also be enabled via configuration files

devServer: { hot: true // hotOnly: True // Use HMR only, Don't fallback to live reloading}, const webpack = the require (' webpack) new webpack. HotModuleReplacementPlugin ()Copy the code
  • Yarn webpack-dev-serve –open CSS file ok, js has some problems

HMR to reassure

HMR in WebPack cannot be handled manually out of the box by HMR in Webpack

1. Why the hot update of the style file out of the box has been loader 2. 3. My project does not have manual processing, JS can still hot replace you use a framework, framework development, each file is regular; Projects created through scaffolding are internally integrated with the HMR solution summary: we need to manually handle hot replacement after JS modules are updatedCopy the code

HMR API

​ devServer: { ​ hot: true ​ },

Module.hot.accept ('./editor', () => {// Register a module's updated handler; Dependent path, dependent path after the handler function; Console. log(' Editor module updated, need to handle hot replacement logic here manually ')}) - yarn webpack-dev-serveCopy the code

JS module hot replacement

Let lastEditor = editor module.hot.accept(‘./editor’, () => {// Dependent path, dependent path after the handler function; // console.log(‘ Editor module updated, need to handle hot replacement logic manually here ‘) // console.log(createEditor)

const value = lastEditor.innerHTML document.body.removeChild(lastEditor) const newEditor = createEditor() NewEditor. InnerHTML = value document. The body. The appendChild (newEditor) lastEditor = newEditor}) there is no universalCopy the code

Image module hot replacement

Module.hot.accept (‘./better.png’, () => {img.src = background console.log(background)})

HMR Precautions

{// hot: true hotOnly: true // HMR only, no fallback to live reloading}

- yarn webpack-dev-serve 2. HMR API error if (module.hot) {} Hot replace is disabled, remove the plugin, yarn webpack, find the bundle. Processing hot substitution is removedCopy the code

Production environment optimization

There is a big difference between the production environment and the development environment. The production environment is about operational efficiency. The development environment is about development efficiency

Mode creates different configurations for different working environmentsCopy the code

Configurations in different environments

1. Configuration files vary depending on the environment. 2

Configuration files in different environments

Module. exports = (env, exports) If (env === ‘production’) {config.mode = ‘production’ Config. Devtool = false // Disable source map config.plugins = […config.plugins, new CleanWebpackPlugin(), New CopyWebpackPlugin([‘public’])} new CopyWebpackPlugin([‘public’])}

Yarn webpack --env production is packaged in production mode 2. Each environment corresponds to a large project of configuration files, Js webpack.dev.js webpack.prod.js -yarn add webpack-merge --dev const merge = require('webpack-merge') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const common = require('./webpack.common') module.exports = merge(common, { mode: 'production', plugins: [new CleanWebpackPlugin(), new CopyWebpackPlugin(['public'])]}) -YARN webpack --config webpack.prod.js can package applications in production environmentCopy the code

DefinePlugin

Inject the global member process.env.node_env into the code

Plugins: [new webpack.defineplugin ({// value required is a code snippeAPI_base_URL: json.stringify ('https://api.example.com')})]Copy the code

Tree Shaking

[Shake out] unreferenced dead-code parts of code such as console.log(). No reference to the function – YARN webpack –mode production is automatically enabled in production mode

Use the Tree Shaking

Tree Shaking is not a configuration option, it is an optimization of a set of features that can be used together. Take care to mark [dry leaves] with usedExports automatically enabled in Production mode

Optimization: {// Centralize some of the functions optimized within Webpack // module only exports the members that are used: usedExports: True, // as far as possible to combine each module into a function, Scope concatenateModules: true, // compress output results // minimize: true} - yarn webpackCopy the code

Combine the module function Scope as

// As far as possible, combine each module into a function, Scope concatenateModules: true,

Tree Shaking & Babel

Tree Shaking is the precondition for ESModules, code packaged by WebPack must use ESM to select babel-loader to deal with JS ESModules -> CommonJS in order to convert the new ECMAScript features in the code

// ['@babel/ PRESET -env', {modules: presets: [// If Babel loads ESM, Tree Shaking is invalid // ['@babel/preset-env', {modules: 'commonjs'}] // Force es Babel to be converted to mommon JS // ['@babel/preset-env', {modules: False}] // Use the default configuration, that is, auto, Auto Determines whether ES Modules is enabled ['@babel/preset-env', {Modules: 'auto'}] // Preset name, preset object]}Copy the code

SideEffects side effects

SideEffects: what a module does when it executes other than exporting its members sideEffects is generally used to flag NPM packages for sideEffects

Enable optimization: {sideEffects: true, // module exports only the members used // usedExports: true, // merge each module into a function whenever possible // concatenateModules: True, // compress the output // minimize: true,} // "sideEffects":false indicates no sideEffectsCopy the code

SideEffects note

Before use: Make sure your code really has no side effects

"SideEffects" : [/ file/logo side effects ". / SRC/extend. Js ", "*. CSS"]Copy the code

The code segment

All the code is eventually packaged together and bundel is so bulky that not every module is necessarily subcontracted and loaded on demand at startup

Code Splitting/Code Splitting

1. Multi-entry packaging 2. Dynamic importCopy the code

Packaging Multi Entry

Multi-page applications: one page corresponds to one packaging entry, and the common parts are extracted separately

Entry: {// define object index: './ SRC /index.js', album: './ SRC/albu.js'}, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ title: 'Multi Entry', template: './src/index.html', filename: 'index.html', chunks: ['index'] // form separate}), new HtmlWebpackPlugin({title: 'Multi Entry', template: './ SRC/albu.html ', filename: 'albu.html ', chunks: ['album'] // form separate})]Copy the code

Extract the common module Split Chunks

Optimization: {splitChunks: {// Automatically extract all common chunks into separate bundle chunks: ‘all’}}, generating the album~index.bundle.js public file

Dynamically import Dynamic Lmports

Load on demand, when you need a module, If (hash === ‘#posts’) {// mainElement.appendChild(posts()) import(/* webpackChunkName: ‘components’ /’./posts/posts’).then(({ default: posts }) => { mainElement.appendChild(posts()) }) } else if (hash === ‘#album’) { // mainElement.appendChild(album()) import(/ webpackChunkName: ‘components’ */’./album/album’).then(({ default: album }) => { mainElement.appendChild(album()) }) }

Magic Comments

/* webpackChunkName: ‘components’ */

MiniCssExtractPlugin extracts CSS files into separate files

  • yarn add mini-css-extract-plugin –dev const MiniCssExtractPlugin = require(‘mini-css-extract-plugin’)

    new MiniCssExtractPlugin()

    rules: [ { test: /.css$/, use: [/ / ‘style – loader, / / the style by style tags into MiniCssExtractPlugin. Loader, / / considering whether more than 150 KB to use’ CSS – loader]}]

OptimizeCssAssetsWebpackPlugin compress CSS

- yarn add optimize-css-assets-webpack-plugin --dev - yarn add terser-webpack-plugin --dev const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin') const TerserWebpackPlugin = require('terser-webpack-plugin') optimization: { minimizer: [new TerserWebpackPlugin (), / / new OptimizeCssAssetsWebpackPlugin ()]}, packaging, production running mode to compress - yarn webpack - mode productionCopy the code

The output file name Hash substitutions

In production mode, if the file name is Hash 1.[name]-[Hash].bundel.js changes. 2. [name]-[contenthash].bundel.js The corresponding file is changed. 4

Rollup

Smaller, just an EXM packer Rollup does not support advanced features like HMR to provide an efficient packer that takes full advantage of ESM features

Rollup

-   yarn add rollup --dev
    -   yarn rollup
        -   yarn rollup ./src/index.js
            -   yarn rollup ./src/index.js --format iife
                -   yarn rollup ./src/index.js --format iife --filedist/bundle.js
Copy the code

Rollup configuration file

The root directory creates the rollup.config.js file

Export default {input: 'SRC /index.js', output: {file: 'dist/bundle.js', // output filename format: 'iife' // Output format}} -yarn rollup --config // Declare that the config file is enabled - yarn rollup --config rollup.config.jsCopy the code

Rollup uses plug-ins

Rollup supports Rollup extensions using plugins. Rollup-plugin-json is the only extension for Rollup

    -   yarn add rollup-plugin-json --dev

    import json from 'rollup-plugin-json'

    plugins: [
        json()
    ]

    -   yarn rollup --config
Copy the code

Rollup Loads the NPM module

​ rollup-plugin-node-resolve

-yarn add rollup-plugin-node-resolve --dev import resolve from 'rollup-plugin-node-resolve' resolve() // Import module member import _ from 'lodash-es' log(_.camelCase('hello world')) - yarn rollup --configCopy the code

Rollup Common JS module

​ rollup-plugin-commonjs

-yarn add rollup-plugin-commonjs --dev import commonjs from 'rollup-plugin-commonjs' commonjs() // Create the cjS-module.js file Module.exports = {foo: 'bar'} //index.js import CJS from './ js-module' log(CJS)Copy the code

Rollup code split

​ Dynamic Imports

//index. Js import('./logger'). Then (({log}) => {log('code splitting~')}) -YARN rollup --config --format amd Amd dir: 'dist', // can output multiple files format: 'AMD' -yarn rollup --configCopy the code

Rollup multi-entry packing

​ export default { ​ // input: [‘src/index.js’, ‘src/album.js’], ​ input: { ​ foo: ‘src/index.js’, ​ bar: ‘src/album.js’ ​ }, ​ output: { ​ dir: ‘dist’, ​ format: ‘amd’ ​ } ​ }

- yarn rollup --config <! -- AMD standard format output bundles cannot be directly referenced --> <! -- <script src="foo.js"></script> --> <! -- to the Require. Js such libraries -- > < script SRC = "https://unpkg.com/[email protected]/require.js" data - the main = "foo js" > < / script >Copy the code

Choose the principle Rollup/Webpack

Advantages:

  • The output is flatter
  • Automates a cluster of unreferenced code
  • The package results are still fully readable

Disadvantages:

  • Loading non-ESM third-party modules is complicated
  • Modules end up packaged into a function that does not implement HMR
  • In the browser environment, the code splitting function relies on the AMD library
If we're developing an application, there's a gap. If we're developing a framework or library, there's a need. The downside can be ignored. Most of the well-known frameworks/libraries are used in the Rollup community. Webpack is big, Rollup is small reference development uses webPack library/framework development uses RollupCopy the code

Parcel Zero Configures the front-end application packer

  • yarn init

  • yarn add parcel-bundler –dev

  • Yarn Parcel SRC /index.html // The browser is automatically refreshed

    // import $from 'jquery' // Automatically install dependencies import foo from './foo' import './style.css' // Load third party import logo from './zce.png' Foo bar () the import (' jquery). Then ($= > {/ / dynamic import $(document. The body). Append (' < h1 > Hello Parcel < / h1 > ') The $(document. The body). Append (` < img SRC = "${logo}" / > `)}) if (module. Hot) {/ / support hot replacement of the module. Hot. Accept (() = > {/ / can only receive a parameter console.log('hmr') }) }Copy the code
  • Yarn Parcel build SRC /index.html // Run packaging in production mode

    Summary: The experience feels comfortable, released in 2017, build faster, complete zero configuration Webpack has a better ecology, more and more useful.