Welcome to the little friends for the 前端导航仓库
Point star https://github.com/pfan123/fr ...
Front-end navigation platform access
CommonJS and AMD are two major specifications for JavaScript module management, which defines synchronous loading of modules, primarily for NodeJS, while the latter is asynchronous loading, and is suitable for the front end through tools such as Requirejs. As NPM becomes the mainstream JavaScript component publishing platform, a growing number of front-end projects are also dependent on the project on NPM, or they will be published to the NPM platform themselves. Therefore, making it easier for front-end projects to use the resources on NPM becomes a big requirement.
The static resources commonly used in web development include JavaScript, CSS, pictures and other files, and the static resource file is called module in Webpack. Webpack is a module bundler (Modular Packaging tool), which can be compatible with a variety of JS writing specifications, and can handle the dependencies between the modules, with more powerful JS modular function. Webpack to manage them in a unified and packaged release, here's a diagram to illustrate Webpack's role:
The core principle of webpack
The two core principles of Webpack are:
1. All Modules
Just as a JS file can be a module, other files (such as CSS, image, or HTML) are also visible as modules. Therefore, you can also require (' myjsfile.js ') and require (' mycssfile.css '). This means that we can divide things (business) into smaller, manageable pieces to achieve the purpose of recycling.
2. Load on Demand
The Traditional modular packaging tool (module bundlers) eventually compiles all the modules to generate a large bundle.js file. But in the real app, the "bundle.js" file may have a size of 10M to 15M that could cause the app to be in the loaded state. So Webpack uses many features to split the code and generate multiple "bundle" files, and asynchronously loads part of the code to implement on-demand loading.
Webpack Official Website documents
Website address: https://webpack.js.org/
Chinese Civil Service Network: https://doc.webpack-china.org/
Advantages of Webpack
Compatible with CommonJS, AMD, ES6 syntax
For JS, CSS, pictures and other resource files are supported packaging
Inline module loaders and plug-in mechanisms for greater flexibility and scalability, such as support for Coffeescript, ES6
Has a separate configuration file Webpack.config.js
Code can be cut into different chunk for on-demand loading, reducing initialization time
Supports Sourceurls and sourcemaps for easy commissioning
With a powerful Plugin interface, mostly internal plug-ins, use more flexible
Webpack uses asynchronous IO and has a multilevel cache. This makes the webpack fast and faster on incremental compilation
Webpack Installation and Configuration installation
npm install -g webpack //全局安装npm install --save-dev webpack //局部安装
Perform
webpack —config webpack.config.js
Configuration
Each project must be configured with a webpack.config.js typically placed in the root of the project, which is itself a standard COMMONJS specification module. There are several key parameters in the exported configuration object:
Entry
The entry parameter defines the packaged portal file, which can be a string or an array or an object, and if it is an array, all the files in the array are packaged to generate a filename file, and if it is an object, you can build different files into different files:
entry: { index: "./page1/index.js", //支持数组形式,将加载数组中的所有模块,但以最后一个模块作为输出 login: ["./entry1/login.js", "./entry2/register.js"] }
Output
The output parameter is an object that defines the location and name of the exported file:
Output: { Path:path.resolve (__dirname, "build"), //packaged output path, recommended absolute path //configuration file in HTML reference to the root path, change the relative path of static resource introduction "/assets/", //publicpath: "Http://cdn.com/assets /",//Can be combined with the full URL, the effect is consistent with the above filename: " Js/bundle.js ", //single page app with only one portal file to use, reference Ingress module filename: " Js/[name ". JS ", //traditional multi-page application with multiple portal files, [name] substituting the name of any of the modules in the entry configuration, such as: Index "Js/[hash]/[chunkhash].js", // Used for incremental update of front-end static resources for the production environment, [hash] is based on the hash value of the overall file of the project after each compilation, [Chunkhash] is the hash value calculated based on the contents of each module}
Module
In Webpack Javascript,css,less,typescript,jsx,coffeescript, pictures and other static files are modules, the loading of different modules is through the module loader (Webpack-loader) to unified management:
module: { rules: [ { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: ‘file-loader‘, query: { limit: 8192, name: ‘./images/[name].[ext]?[hash]‘ }, }, // 使用多个插件,使用use,sass文件使用style-loader, css-loader, less-loader来处理 { test: /\.(sass|scss)$/, use: [ ‘style-loader‘, ‘css-loader‘, ‘sass-loader‘, extractTextPlugin.extract([‘style‘,‘css‘, ‘less‘]) ], } ]}
Note: Webpack 2.x after the module.loaders changed to Module.rules
Resolve
Webpack when building a package, the file is searched by directory, and the extensions array in the Resolve property is used to configure which file suffixes the program can self-complement:
resolve: { modules: [path.resolve(__dirname, "node_modules")] extensions: [‘‘, ‘.js‘, ‘.json‘, ‘.scss‘], //模块别名定义,方便后续直接引用别名,无须多写长长的地址 alias: { AppStore : ‘js/stores/AppStores.js‘,//后续直接 require(‘AppStore‘) 即可 ActionType : ‘js/actions/ActionType.js‘, AppAction : ‘js/actions/AppAction.js‘ } }
Plugin
Webpack provides [rich components] to meet different needs, and of course we can implement one of our own components to meet our own needs:
plugins: [ //your plugins list ]
Common plugins:
Hotmodulereplacementplugin--Turn on global module Hot Swap (HMR)
Namedmodulesplugin-When module hot Swap (HMR) is output to user-friendly module name information in the browser console
Commonschunkplugin--extracting chunk public part
Extracttextplugin--Independently generated CSS file, outside the chain form load
Uglifyjsplugin--Compression JS
Htmlwebpackplugin--using templates to generate HTML
Externals
Prevent some import packages (package) from being packaged into bundles, but rather at runtime (runtime) to get these extended dependencies externally (external dependencies).
For example, to introduce jQuery from a CDN instead of packaging it:
<script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>
externals: { "jquery": "jQuery"}
This strips away the dependent modules that do not need to be changed, in other words, the code shown below will work:
import $ from ‘jquery‘;$(‘.my-element‘).animate(...);
Webpack-dev-server
Webpack-dev-server is a small node. JS Express server that uses Webpack-dev-middleware middleware to provide Web services for resource files generated through Webpack packaging. It also has a small run-time program that connects to the Webpack-dev-server server via Socket.io. Webpack-dev-server sends messages about the state of the compilation to the client, and the client responds based on the message.
There are two modes of webpack-dev-server that support automatic refresh:
iframe mode
The page is nested under an IFRAME, and the IFRAME reloads when the code changes.
Using the IFRAME mode requires no additional configuration, just the browser input http://localhost:8080/webpack-dev-server/index.html
, obviously webpack-dev-server default mode is the IFRAME
Inline mode
The Webpack-dev-server client will be packaged as a portal file and will refresh the page when the backend code changes. There are two ways to configure it: CLI configuration and manual configuration via the node. JS API
CLI mode
This method is relatively simple, just add--inline to the command that Webpack.dev.server starts
"scripts":{"start":"webpack-dev-server --inline --config webpack.config.dev.js"}
Re npm start
-run, browser access http://localhost:8080
, modify the code after saving, the browser automatically refresh
node. JS API mode
var config = require("./webpack.config.js");config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/");var compiler = webpack(config);var server = new WebpackDevServer(compiler, {...});server.listen(8080);
<script src="http://localhost:8080/webpack-dev-server.js"></script>
Hot Module Replacement
Use webpack-dev-server的自动刷新功能时,浏览器会整页刷新。而热替换的区别就在于,前端代码变动时,无需刷新整个页面,只把变化的部分替换掉。配置的关键在于将
the Webpack/hot/dev-server ' file to add to the Webpack all portal file.
PS: to inject HMR plug-in before use
// 开启全局的模块热替换(HMR)new webpack.HotModuleReplacementPlugin(),// 当模块热替换(HMR)时在浏览器控制台输出对用户更友好的模块名字信息new webpack.NamedModulesPlugin()
There are two different ways to use HMR: The CLI and the node. JS Api
CLI mode
Command line configuration is simple, just on the basis of automatic refresh, plus --hot
configuration.
This configuration is automatically webpack/hot/dev-server
added to all Webpack entry points.
"scripts":{"start":"webpack-dev-server --inline --hot --config webpack.config.dev.js"}
node. JS API mode
config = require("./webpack.config.js");config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/", "webpack/hot/dev-server");var compiler = webpack(config);var server = new webpackDevServer(compiler, { hot: true ...});server.listen(8080);
PS: To make the HMR function effective, it is to include the code that allows hot substitution in the module or root module where the hot replacement is applied. Otherwise, the hot swap will not take effect, or the entire page will be re-brushed. Here is an excerpt from Webpack's quote on GitHub:
PS: note Webpack-dev-server output log
Webpack-dev-server.js output information, you can findContentbase exists, it will print the log Content not from Webpack are served fromWebpack output is served from information taken from Output.publicpath pathfunctionReportreadiness (URI, Options) {Const USECOLOR = Argv.color;Let startsentence =' Project is running at${colorinfo (Usecolor, URI)} 'if (options.socket) {startsentence =' Listening to sockets at${colorinfo (Usecolor, Options.socket)} '; }Console.log ((argv["Progress"]?"\ n":"") + startsentence);Console.log (' Webpack output is served from${colorinfo (Usecolor, Options.publicpath)} ');Const CONTENTBASE =Array.isarray (options.contentbase)? Options.contentBase.join (if (contentbase) console.log ( Content not from Webpack are served from ${colorinfo (Usecolor, Contentbase)} '); if (options.historyapifallback) console.log ( 404s would fallback to ${colorinfo (Usecolor, Options.historyApiFallback.index || "/index.html")} `); if (options.open) {open (URI). catch ( function (console.log ( "unable to open browser. If you is running in a headless environment, please don't use the open flag. "});}}
WEBPACK DEV SERVER
Hot Module Replacement
Hot Module Replacement Introduction
Hot Module Replacement
How to write well. BABELRC? Presets and plugins configuration analysis of Babel
Webpack2 Asynchronous loading routines
Exploration of front-end engineering solution based on Webpack construction
"Translation" webpack--confusing place
Webpack Introduction and use