Webpack Introduction
Webpack is now the most popular modular management and packaging tool for front-end resources. It can package many loose modules according to dependencies and rules into front-end resources that meet the deployment of the production environment. You can also code-separate modules that are loaded on demand until the actual
Load asynchronously when needed. Through loader
the conversion, any form of resources can be regarded as modules, such as CommonJs module, AMD module, ES6 module, CSS, image, JSON, coffeescript, less and so on.
Evolution <script> labeling of modular systems
<script src= "Module1.js" ></script><script src= "module2.js" ></script><script src= " Librarya.js "></script><script src=" Module3.js "></script>
This is the most primitive way to load JavaScript files, if each file as a module, then their interface is usually exposed to the global scope, that is, defined in the window
object,
Interface calls from different modules are a scope, and some complex frameworks use the concept of namespaces to organize the interfaces of these modules, typical examples such as the YUI Library.
This primitive loading method exposes some obvious drawbacks:
- Variable collisions can be caused by global scope
- Files can only be
<script>
loaded in the order in which they are written
- Developers must subjectively resolve dependencies between modules and code base
- Resources are difficult to manage in large-scale projects, and long-term accumulation of problems leads to a confusing code base
COMMONJS specification
CommonJS is a project designed to build a JavaScript ecosystem outside of a browser environment, such as in a server and desktop environment.
The CommonJS specification is a modular form that is defined to address the scope of a JavaScript problem and allows each module to execute in its own namespace. The main content of this specification is that the module must import the output of module.exports
require()
Other modules into the current module scope by exporting the external variables or interfaces.
An intuitive example
ModuleA.jsmodule.exports = function (value) { return value * 2;}
// Moduleb.js var multiplyBy2 = require ('./modulea'); var result = MultiplyBy2 (4);
AMD Specifications
AMD (Asynchronous module definition) is designed for the browser environment because the CommonJS module system is loaded synchronously and the current browser environment is not ready to load the module synchronously.
The module define
is defined in the closure by function, in the following format:
Define (ID: String, dependencies?: string[], factory:function| Object);
id
is the name of the module, which is an optional parameter.
factory
Is the last parameter, which wraps the concrete implementation of the module, which is a function or object. If it is a function, then its return value is the output interface or value of the module.
Some use cases
Define a module named myModule
, which depends on the jQuery
module:
define(‘myModule‘, [‘jquery‘], function($) { // $ 是 jquery 模块的输出 $(‘body‘).text(‘hello world‘);
}); // 使用 require([‘myModule‘], function(myModule) {});
Note : In Webpack, the module name has only a local scope, and in Require.js the module name is global scope and can be referenced globally.
Defines an anonymous module that does not have a id
value, usually as the application's startup function:
define ([' jquery '], function ($) { $ (' body '). Text (' Hello World ');});
AMD The module is also loaded with the Require () statement, but unlike COMMONJS, he requires two parameters
The first parameter, [module], is an array in which the member is the module to be loaded, and the second parameter, callback, is the callback function after the load succeeds. If you rewrite the previous code in AMD form, this is the following:
Math.add () is not synchronized with the math module, and the browser does not take place in animation. So it's clear that AMD is better suited to the browser environment
Currently, there are two main JavaScript libraries that implement the AMD specification:require.js and curl.js
Require ([' math '], function (math) {Math.add (2, 3); });
What is Webpack
Webpack is a module wrapper. It will perform static analysis based on the dependencies of the modules, and then generate the corresponding static resources according to the specified rules.
Features of WebpackCode splitting LoaderIntelligent ParsingPlug-in system runs quicklyWebpack Basic Use
Create the project root directory
Initialization
NPM init or NPM init-y
Global Installation
NPM Install Webpack-g
Local installation, installation in project directory
NPM Install Webpack--save-dev
--save: Storing information about installed packages in the package
--dev: Development version, only used when the project is built, the files that are not dependent upon the completion of the project
If you use Web development tools, install them separately
NPM Install Webpack-dev-server--save-dev
Basic Use
First create a static page index.html and a JS entry file Entry.js:
<!-- index.html -->
Create Entry.js
// entry.js : 在页面中打印出一句话document.write(‘It works.‘)
Then compile the entry.js and package into the Bundle.js file
// 使用npm命令 webpack entry.js bundle.js
using Modules1. Create the module module.js and export the content internally
module.exports = ‘It works from module.js‘
2. Using a custom module in Entry.js
//entry.jsdocument.write(‘It works.‘)document.write(require(‘./module.js‘)) // 添加模块
Loading CSS Modules1. Installing Css-loader
npm install css-loader style-loader --save-dev
2. Create a CSS file
//style.cssbody { background: yellow; }
3. Modify Entry.js:
require("!style-loader!css-loader!./style.css") // 载入 style.cssdocument.write(‘It works.‘)document.write(require(‘./module.js‘))
Creating a configuration file Webpack.config.js1. Create a file
var webpack = require(‘webpack‘)module.exports = { entry: ‘./entry.js‘, output: { path: __dirname, filename: ‘bundle.js‘ }, module: { loaders: [ //同时简化 entry.js 中的 style.css 加载方式:require(‘./style.css‘) {test: /\.css$/, loader: ‘style-loader!css-loader‘} ] }}
2. Modify the Style.css load mode in Entry.js: Require ('./style.css ')
3. Running Webpack
Enter Webpack directly on the command line page
plug-in use1. Plug-in installation
//添加注释的插件npm install --save-devbannerplugin
2. Writing the configuration file
var webpack = require(‘webpack‘)module.exports = { entry: ‘./entry.js‘, output: { path: __dirname, filename: ‘bundle.js‘ }, module: { loaders: [ //同时简化 entry.js 中的 style.css 加载方式:require(‘./style.css‘) { test: /\.css$/, loader: ‘style-loader!css-loader‘ } ], plugins: [ //添加注释的插件 new webpack.BannerPlugin(‘This file is created by zhaoda‘) ] }}
3. Running Webpack
// 可以在bundle.js的头部看到注释信息/*! This file is created by zhaoda */
Development Environmentwebpack --progress : 显示编译的进度--colors : 带颜色显示,美化输出--watch : 开启监视器,不用每次变化后都手动编译
12.4.7.1. Webpack-dev-server
Turn on the service to run automatically in listening mode
1. Installation package
npm install webpack-dev-server -g --save-dev
2. Start the service
Real-time monitoring of pages and automatic refresh
webpack-dev-server --progress --colors
Automatic compilation1. Installing plugins
npm install --save-dev html-webpack-plugin
2. Importing packages in a configuration file
var htmlWebpackPlugin = require(‘html-webpack-plugin‘)
3. Using plugins in configuration files
plugins: [ //添加注释的插件 new webpack.BannerPlugin(‘This file is created by zhaoda‘), //自动编译 new htmlWebpackPlugin({ title: "index", filename: ‘index.html‘, //在内存中生成的网页的名称 template: ‘./index.html‘ //生成网页名称的依据 }) ]
4. Run the project
webpack--save-dev
Webpack Modular management and packaging tools