This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

At the forefront of

Webpack is a front-end packaging tool, is an important part of the large front-end automation factory, Webpack is mainly packaging, Webpack as a part of the automation tool chain integrated with a larger tool system, rather than all the requirements are expected to webpack.

Wepack is a front-end tool that allows modules to be loaded, preprocessed, and packaged. It has all the basic features of Grunt or Gulp.

Advantage:

  1. Support commonJS and AMD modules
  2. Support calls to many module loaders, making it flexible to customize module loaders, such as the Babel-loader, which allows us to write code using ES6 syntax
  3. You can configure to package multiple files to effectively take advantage of the browser’s caching capabilities to improve performance
  4. Using the module loader, can support sASS, less and other processors for packaging and support static resource style and image packaging
NPM install -g webpack // project configuration item // CD open NPM initCopy the code

package.json

{" name ":" jeskson ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo \" Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }Copy the code

Create webPack dependencies:

npm install --save-dev webpack
Copy the code
{" name ":" jeskson ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" test ", "echo \" Error: No test specified\" && exit 1"}, "author": "", "license": "ISC", "devDependencies": {"webpack": "^1.14.0"}Copy the code

How webpack is run

Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: {// where the packed file is placed path: __dirname + '/public', // our packed filename filename: 'webpack.js'}}Copy the code
webpack.js
Copy the code
{" name ":" jeskson ", "version" : "1.0.0", "description" : ""," main ":" index. Js ", "scripts" : {" start ": "webpack", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": {"webpack": "^1.14.0"}}Copy the code
If start changes to da, NPM run daCopy the code

Loaders needs to be installed separately and configured under modules in webpack.config.js. Loaders configuration options include the following:

  • Test, a regular expression that matches the extended name of the file loaders is processing.
  • The name of the loader, loader
  • Include /exclude manually add files that must be processed or exclude files that do not need to be processed
  • Query, which provides additional setup options for loaders
npm install --save-dev json-loader
Copy the code

webpack.config.js

Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: Path: __dirname + '/public', // Filename: 'webpack.js'}, module: {loaders: [{test: /\.josn$/, loader: 'json" } ] } }Copy the code

work.js

var config = require("./config.json")
document.write(config.text);
Copy the code

Webpack’s manipulation of stylesheets

Webpack provides two tools for handling style sheets, CSS-loader and style-loader.

Css-loader enables you to use things like @import and URLS (…) The require() method implements the function.

Style-loader adds all the computed styles to the page, and together the two enable you to embed the stylesheet into webpack wrapped JS files.

Installation command: NPM install –save-dev style-loader CSS-loader

webpack.config.js

Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: Path: __dirname + '/public', // Filename: 'webpack.js'}, module: {loaders: [{test: / \. Josn $/, loader: 'json "}, {$/ test: / \. CSS, loader: "style! CSS/right/left performed}]}}Copy the code

Css3 syntax, when writing styles, to do browser compatibility, that is, to add a lot of style prefixes, which will also increase the amount of code, but now the work of adding prefixes is left to Webpack.

npm intall --save-dev postcss-loader autoprefixer
Copy the code

webpack.config.js

Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: Path: __dirname + '/public', // Filename: 'webpack.js'}, module: {loaders: [{test: / \. Josn $/, loader: 'json "}, {$/ test: / \. CSS, loader: "the CSS style! Postcss"/right/left performed}]}, postcss: [ require('autoprefixer') ] }Copy the code

Compatible with:

body {
 background: red;
 display: flex;
 display: -webkit-box;
 display: -ms-flexbox;
}
Copy the code

Webpack babel-Core (es6 converted to ES5)

Babel is actually a couple of modular packages with the core functionality in an NPM package called Babel-Core, but WebPack uses them all together, but for every feature or extension you need, You’ll need to install separate preset packages (the most used are babel-preset- ES2015 for ES6 and babel-preset- React for JSX).

npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react
Copy the code

Configuration items written:

{test: /\.js$/, exclude: /node_modules/, loader: 'Babel ', // Query: {presets: ['es2015','react']}} // react install: NPM install --save react-domCopy the code

webpack.config.js

Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: Path: __dirname + '/public', // Filename: 'webpack.js'}, module: {loaders: [{test: / \. Josn $/, loader: 'json "}, {$/ test: / \. CSS, loader: "the CSS style! Postcss"/right/left performed}, {test: / \. Js $/, loader: "babel", exclude: /node_modules/, query: { presets: ['es2015'] } } ] }, postcss: [ require('autoprefixer') ] }Copy the code

Use of plug-ins for WebPack

Plugins are used to extend Webpack functionality, and they take effect throughout the build process to perform related tasks.

Loaders and Plugins are often confused, but they are completely different things. Loaders are used to process source files (JSX, Scss, Less) during the package build process.

To use a plug-in, we install it via NPM, and all we need to do is add an instance of the plugin (plugins are an array) to the Plugins keyword section of the WebPack configuration, adding a plug-in that implements the copyright declaration.

We need to call the WebPack plugin at the very beginning of the configuration file:

var webpack = require('webpack');
Copy the code

Then add a plugins keyword to module.exports={}

Plugins: [new webpack.BannerPlugin(' copyright ') // Add a new one to the array.Copy the code

HtmlWebpackPlugin

The purpose of this plugin is to generate your final HTML5 file from a simple template, which automatically references your packed JS file, inserting a different hash value into the filename each time you compile.

npm install --save-dev html-webpack-plugin
Copy the code

This plugin automates some of the things we did manually, and requires some changes to the project structure before it can be used:

Remove the public folder. Using this plugin, HTML5 files will be automatically generated. In addition, THE CSS has been packaged into the JS public folder through the previous steps.

In the app directory, create a template Html file that contains the title and other elements you need. During compilation, the plugin will use this template to generate the final Html page, automatically adding the dependent css.js, Favicon and other files.

Configuration items:

webpack.config.js

var webpack = require('webpack'); var Html = require('html-webpack-plugin'); Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: Path: __dirname + '/public', // Filename: 'webpack.js'}, module: {loaders: [{test: / \. Josn $/, loader: 'json "}, {$/ test: / \. CSS, loader: "the CSS style! Postcss"/right/left performed}, {test: / \. Js $/, loader: "babel", exclude: /node_modules/, query: { presets: ['es2015'] } } ] }, postcss: [ require('autoprefixer') ], plugins: [new webpack.BannerPlugin(' copyright '), // Add a new one to the array. // Add a new one to the array. __dirname + '/app/index.html' }) ] }Copy the code

Webpack webpack — dev server

Automatic page refresh function

Webpack development server, is an auxiliary development tool officially provided by Webpack, it can automatically monitor the files under the project, once there is a modification to save the operation, he will take the initiative to execute the packaging command, our code to repackage, and if necessary, can also refresh the browser.

npm install --save-dev webpack-dev-server
Copy the code

ContentBase By default webpack-dev-server provides a local server for the root folder. If you want to provide a local server for files in another directory, you should set the directory here.

  • Port Specifies the default listening port. If omitted, the default listening port is 8080.
  • Inline is set to true to refresh the page automatically when the source file changes
  • Colors is set to true so that the terminal outputs files in color
  • HistoryApiFallback is very useful for developing single-page apps. It relies on the HTML5 History API, and if set to true, all jumps will point to index.html
DevServer {contentBase: "./public", // colors: true, // terminal outputs color historyApiFallback: True, // No jump to inline: true, // real-time refresh}Copy the code

webpack.config.js

var webpack = require('webpack'); var Html = require('html-webpack-plugin'); Module.exports = {// __dirname is a global variable in nodejs // it points to the root directory of our project // the location of the entry file entry: __dirname + '/app/main.js output: Path: __dirname + '/public', // Filename: 'webpack.js'}, module: {loaders: [{test: / \. Josn $/, loader: 'json "}, {$/ test: / \. CSS, loader: "the CSS style! Postcss"/right/left performed}, {test: / \. Js $/, loader: "babel", exclude: /node_modules/, query: { presets: ['es2015'] } } ] }, postcss: [ require('autoprefixer') ], plugins: [new webpack.BannerPlugin(' copyright '), // Add a new one to the array. // Add a new one to the array. __dirName + '/app/index.html'})], devServer: {contentBase: './public', colors: true, inline: // Refresh hot: true}}Copy the code

Webpack-dev-server has two startup modes:

IFrame: Code changes in this mode are automatically packaged, but the browser is not refreshed

Inline: Code changes in this mode are automatically packaged and the browser is refreshed

Run: webpack-dev-server –line

Module hot loading technology, which means that when we modify the code and save it, the code can be packaged and will automatically refresh the part of the code that we modify without refreshing the browser.

DevServer: {contentBase: "./public", // colors: true, // terminal outputs color historyApiFallback: True, // Don't skip inline: true, // Refresh hot: true // allow hot loading}Copy the code
webpack-dev-server --inline --hot
Copy the code

Fuse.js

Fuse.js is a powerful, lightweight fuzzy search library with zero dependencies.

// 1. List of items to search in
const books = [
  {
    title: "Old Man's War",
    author: {
      firstName: 'John',
      lastName: 'Scalzi'
    }
  },
  {
    title: 'The Lock Artist',
    author: {
      firstName: 'Steve',
      lastName: 'Hamilton'
    }
  }
]

// 2. Set up the Fuse instance
const fuse = new Fuse(books, {
  keys: ['title', 'author.firstName']
})

// 3. Now search!
fuse.search('jon')

// Output:
// [
//   {
//     item: {
//       title: "Old Man's War",
//       author: {
//         firstName: 'John',
//         lastName: 'Scalzi'
//       }
//     },
//     refIndex: 0
//   }
// 
Copy the code

Module packaging tool

The module packaging tool is designed to resolve dependencies between modules so that the packaged results can run in a browser.

  • Combine dependent modules into a single JS file according to specific rules and load them all into the page at one time.
  • One entry module is loaded at page initialization, and the others are loaded asynchronously.

webpack

  1. Webpack supports a variety of module standards by default
  2. Webpack has a complete code splitting solution
  3. Webpack can handle all types of resources
  4. Webpack has a huge community of support

Install using local installation mode:

  1. With a global installation, when working on projects with others, the results can be inconsistent due to the different versions of Webpack on each person’s system.
  2. Plug-ins that partially rely on WebPack will call modules within webPack in your project, and in this case you still need to install WebPack locally in your project, which can be confusing if you have both globally and locally.
npm init
// yarn init
Copy the code

Generate a package.json file, which is the specification of the NPM project, with the project name, version, warehouse address, and so on.

npm install webpack webpack-cli --save-dev
Copy the code

Webpack is the core module, Webpack – CLI command line tool

  • Entry is the entry for resource packaging
  • Output-filename is the name of the output resource
  • Webpack provides developers with development, production, none three modes

The default configuration file for webpack is webpack.config.js:

module.exports = {
 entry: './src/index.js',
 output: {
  filename: 'bundle.js',
 },
 mode: 'development',
}
Copy the code

webpack-dev-server

npm install webpack-dev-server --save-dev
Copy the code

NPM install –production Filters out extra modules in devDependencies

module.exports = {
 entry: './src/index.js',
 output: {
  filename: 'bundle.js',
 },
 mode: 'development',
 devServer: {
  publicPath: '/dist',
 },
}
Copy the code

Webpack-dev-server is used to receive browser requests and return resources. When Webpack-dev-server receives a resource request from the browser, it first verifies the URL address. If the address is a resource service address, the resource is looked for in the webpack result and returned to the browser. Conversely, if the requested address does not belong to the resource service address, the source file is read directly from the hard disk and returned.

Webpack dev – server:

  • Have WebPack do module packaging and handle resource requests for the resulting packaging
  • As a normal Web server, it handles static resource file requests

Webpack can handle dependencies between modules, concatenating them into a single JS file, using a local installation, allowing teams to share a version while developing, and allowing other plug-ins to access webPack’s internal modules directly.

Module packaging

export

module.exports = { name: 'calculater', add: function(a, b) { return a + b; }};Copy the code

The CommonJS module has a module object that holds information about the current module. It can be understood as an object defined at the beginning of each module:

var module = {... }; Exports = {// module exports = {exports. };Copy the code

In the application, 🗡 puts module.exports and the exports statement at the end of the module.

Use require in CommonJS for module import

module.exports = {
 add: func()
}

const addFun = require('./addjs.js');
const num = addFun.add()
Copy the code
  • The require module is loaded for the first time, and the module is executed first, then the content is exported.
  • Require’s module has been loaded before, and the module’s code does not execute again, instead exporting the results of the last execution.

The module object is used to store information, and the object has an attribute loaded to record whether the module has been loaded. Default false, true after loading.

dynamic

The require function can accept expressions.

const moduleNames = ['foo.js', 'bar.js'];
moduleNames.forEach(name => {
 require('./' + name);
});
Copy the code

Es6 module

export default {
 name: 'dada'
};

import add form './xx.js';
const num = add.name
Copy the code

The ES6 Module automatically adopts strict mode

export

  • One: Declare and export variables on one line
  • The second way is to declare variables first and then export them using the same export statement

When using named exports, variables can be renamed using the AS keyword.

Export default is understood as the output of a variable named default. Therefore, you do not need to declare the variable as named export, but directly export the value.

// Export default 'DDD'Copy the code

The import

When importing multiple variables, you can import them as a whole

import * as addFunc from 'xxx.js';

Mix the two import methods:

import React, { Component } from 'react'; // React corresponds to the module's default export // Component is a variable in its named exportCopy the code

Composite writing

import calculator from './calculator.js';
export default calculator;
Copy the code

CommonJS and ES6 Module

The fundamental difference between CommonJS and ES6 modules is that the former resolves Module dependencies “dynamically” while the latter is “static”.

Dynamic: Module dependencies are established during code runtime; Static: The establishment of module dependencies occurs during code compilation.

Module dependencies can be analyzed during compilation of ES6 code:

  • Dead code detection and exclusion, using static analysis tools to detect which modules have not been called. The module code that has not been called will not be executed and become dead code. Through static analysis, these unused modules can be removed during packaging to reduce the volume of packaging resources.
  • Module variable type checking. JavaScript is a dynamically typed language and does not check for type errors before code execution. The static Module structure of ES6 Modules helps ensure that the values or interface types passed between modules are correct.
  • Compiler optimization. CommonJS and other dynamic Module systems, no matter which way is adopted, essentially import is an object, while ES6 Module supports direct import variables, reducing the reference level, program efficiency is higher.

When importing a Module, for CommonJS it is a copy of the exported value, whereas ES6 Module is a dynamic map of the value, and the map is read-only.

AMD

AMD is an asynchronous Module definition, which differs from CommonJS and ES6 Modules in that it loads modules asynchronously.

The advantage of defining modules in AMD form is that module loading is non-obstructive. When executing the require function, it does not stop to execute the loaded module. Instead, it continues to execute the code after require.

UMD

Its goal is to enable a module to run in a variety of environments, whether CommonJS,AMD, or modular.

npm

Initialize the NPM project to obtain modules through NPM:

NPM install lodash NPM install lodashCopy the code
// use // index.js import _ from 'lodash';Copy the code

CommonJS and ES6 modules are widely used today, the main difference being that the former establishes Module dependencies at runtime and the latter at compile time. In terms of Module import, CommonJS import is value copy, ES6 Module imports read-only variable mapping, ES6 Module can optimize the compilation process through its static feature, and has the ability to deal with cyclic dependency.

Webpack is a modular tool that is packaged at development time, meaning it cannot be used online without being packaged. Webpack is compatible with AMD, common.js, and modular writing.

Use globally installed WebPack or gulp

npm install -g webpack gulp
Copy the code

Consider using taobao’s mirror image

npm install -g webpack gulp --registry=http://registry.npm.taobao.org
Copy the code

Entry files are javascript files that are referenced directly in HTML and triggered by the browser. Other non-entry files are directly or indirectly dependent on entry files and executed by JS calls to each other.

Parse the file

(function(Modules){// Runtime})(// module array])Copy the code

The purpose of the Common Chunks plug-in is to extract Common Chunks from your code and package them into a separate file that can be used in other Chunks and Chunks.

Use it to extract common modules

var webpack = require('webpack');

module.exports = {
    entry:{
        main1:'./main',
        main2:'./main.2'
    },
    output:{
        filename:'bundle.[name].js'
    },
    plugins: [
        new  webpack.optimize.CommonsChunkPlugin('common.js', ['main1', 'main2'])
    ]
};
Copy the code

The split point indicates the point at which the code is split into two separate files. There are two ways to do this.

Using the require. Ensure:

require.ensure(["module-a", "module-b"], function(require) {
    var a = require("module-a");
    // ...
});
Copy the code

Use AMD’s dynamic require:

require(["module-a", "module-b"], function(a, b) {
    // ...
});
Copy the code

output.publicPath

In general, the above configuration should do the trick. If your site is a bit larger, you may need to introduce a CDN, and it probably has some weird prefixes. This can be done with output.publicPath.

For example, in the example above, the output of the script path is dist/example4.1 js, and in a production environment to access when it is likely to be http://cdn.toobug.net/scripts/webpack_guide/dist/example4.1.js. In this case, we need to use output.publicPath to complete the previous path:

output:{
    publicPath:'http://cdn.toobug.net/scripts/webpack_guide/'
}
Copy the code

After publishing to the production environment, the script will be loaded in the corresponding path on the CDN.

TypeScript (ts – loader)

module:{
    rules:[{
        test: /.ts$/,
        loader:'ts-loader',
    }]
}
Copy the code

Bundle-loader is a loader that loads modules asynchronously at run time.

Var waitForChunk = require("bundle! ./file.js"); Function (file) {// var file = require("./file.js"); }); // Todo: What does this comment say? // wraps the require in a require.ensure blockCopy the code
var load = require("bundle? lazy! ./file.js"); Load (function(file) {});Copy the code

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create better articles

Likes, favorites and comments

I’m Jeskson, and thanks for your talent: likes, favorites and comments. See you next time! ☞ Thank you for learning with me.

See you next time!

Github: 1024bibi.com

“Welcome to the discussion in the comments section. The excavation authorities will draw 100 nuggets in the comments section after project Diggnation. See the event article for details.”