Note:
This blog mainly refers to this blogger's: http://www.jianshu.com/p/9423a7f04d31
But the version of webpack used by this blogger is 1.15.0. According to his instructions, there were errors in configuring webpack dev-server. There were many incompatible versions of plug-ins, so I changed to the latest version of webpack 3.10.0. It is no problem to install it according to the version number I gave below. (The "extract-text-webpack-plugin" plug-in is installed by default, i.e. without version number. The installation is the latest, but it is incompatible with webpack dev-server, so I changed it to a version number, see below).
Project preparation tools:
(1) The version of NodeJs is V4.4.7, which serves as a running environment for using webpack.
(2)Git I use Git under windows, and the next project is to operate on the Git Brash Here interface.
Establishment of Git Remote Warehouse
If you start a new project from scratch
Establishing a remote warehouse in Github
Structure of new projects built locally
-
git initialization
git init
Establishing association with remote Libraries
//Add your host public key to Github
git remote add origin ssh address
- Configuration. gitignore
.DS_Store
/node_modules/
/dist
The role of the. gitignore configuration: Ignore these items when pushing to a remote server.
- Push to remote
git add .
git commit -m "something"
git push -u origin master
-
Of course, we should finish the project in the branch.
git checkout -b dev
Git is too specific configuration I will not elaborate here, not clear can be found online, there are many.
Scaffolding Construction of Project
- npm initialization
npm init
2 webpack
Global installation of webpack: NPM install webpack-g
Webpack Local Installation: npm install webpack save-dev, my default installation has no version number (webpack version 3.10.0)
3. webpack.config.js
Of course, you can't do a project with command line packaging.
Entry files for entry JS
externals External Dependency Statement
output target file
resolve configuration alias
module files, loader s
plugins plug-in
Some Problems with Script Processing
What loader does js load with?
Using the js loading mode of webpack
- There is only one JS in the example entry on the official document. What if we have more than one js?
var config = {
entry: {
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '[name].js' //Note that multiple entry files do not use this approach,Entry files will be overwritten in turn
}
};
module.exports = config
- How to set up the target file in output folder?
var config = {
entry: {
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '/js/[name].js' //filename It supports paths.,We can specify the path here.
}
};
module.exports = config
- jquery introduction method
There are actually two ways, one of which is through require.
'use strict';
var $ = require('jquery');
console.log('hello index');
$('body').html('HELLO INDEX');
But the bad thing about this method is that I need to introduce jquery into almost every file, which is very troublesome. We don't like to do troublesome things.
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
Well, that's the solution. jquery 1.11.3 is used here, but what about introducing jquery in a modular way?
//index.js
'use strict';
console.log('hello index');
var $$ = require('jquery'); //jquery is not installed in npm
$$('body').html('index hello ~~~~~~');
var config = {
entry: {
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '/js/[name].js'
},
externals:{
'jquery':'window.jQuery' //Introduce external variables or modules to load in
}
};
module.exports = config
- I want to extract the public module, how to deal with it?
CommonsChunkPlugin
Well, let's talk about it in detail.
First, if you introduce the same module into each file, it should be a common component.
var webpack = require('webpack');
var config = {
entry: {
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '/js/[name].js'
},
externals:{
'jquery':'window.jQuery'
},
plugins:[
new webpack.optimize.CommonsChunkPlugin({ //Copy it if you want, who will remember it?
name:'commons', //The name of the saved file, commons, is the default
filename:'js/base.js' //The final output file name, filename, is output-based path
//Both index and login introduce the same module, so it will introduce this generic module into base.js
})
]
};
module.exports = config
But I introduce the same module into every file, and I want to write a request (), I don't want to write ().
var webpack = require('webpack');
var config = {
entry: {
'common':['./src/page/common/index.js'],
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '/js/[name].js'
},
externals:{
'jquery':'window.jQuery'
},
plugins:[
new webpack.optimize.CommonsChunkPlugin({
name:'common', //this common and entry Of common Corresponding,otherwise common Will generate common.js Instead of base.js
filename:'js/base.js'
})
]
};
module.exports = config
Some Problems with Style Processing
- What CSS loader does the style use?
css-loader style-loader
Install css-loader style-loader
npm install css-loader style-loader --save-dev
css-loader version: 0.28.7
style-loader version: 0.19.1
js introduces css file
//index.js
'use strict';
console.log('hello index');
require('./index.css');
require('../module.js');
//webpack.config.js
var webpack = require('webpack');
var config = {
entry: {
'common':['./src/page/common/index.js'],
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '/js/[name].js'
},
externals:{
'jquery':'window.jQuery'
},
module:{
loaders:[
{test:/\.css$/,loader:"style-loader!css-loader"}
//From right to left, execute css-loader before style-loader
]
},
plugins:[
new webpack.optimize.CommonsChunkPlugin({
name:'common', base.js
filename:'js/base.js'
})
]
};
module.exports = config
- How can CSS packaged in webpack be separated into separate files?
extract-text-webpack-plugin
npm install extract-text-webpack-plugin --save-dev
The extract-text-webpack-plugin version is: 2.1.2
If I follow the 3.XX version that I installed above, I made an error installing webpack dev-server after installation, so I installed version 2.1.2, which is no problem, as follows:
npm install extract-text-webpack-plugin@2.1.2 --save-dev
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin'); //1. introduction
var config = {
entry: {
'common':['./src/page/common/index.js'],
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: '/js/[name].js'
},
externals:{
'jquery':'window.jQuery'
},
module:{
loaders:[
{test:/\.css$/,loader:ExtractTextPlugin.extract("style-loader","css-loader")} //2. Make a transformation
]
},
plugins:[
new webpack.optimize.CommonsChunkPlugin({
name:'common',
filename:'js/base.js'
}),
new ExtractTextPlugin("css/[name].css") //3. Adding dist paths
]
};
module.exports = config
The problem of html template processing
html-webpack-plugin
Why do we need to do HTML template processing? If we go online now and change it later, some of your imported files need to be version-numbered, but there are dozens of pages, each page needs version-numbered, that's not a rush to death. And the HTML file is in the src directory, not in the dist directory. When we pack it, src doesn't care. So, we need to configure our html.
Plug-in Links: https://webpack.js.org/plugins/html-webpack-plugin/
Parameters:
title: title Value is used to generate HTML documents.
filename: Write the generated HTML into the file. Write to index.html by default. You can also specify a subdirectory here (eg: assets/admin.html).
template: Webpack require path to template. See docs for details
inject:true |'head'|'body' | false adds all static resources to a template file or template Content. When true or body is passed in, all javascript resources are placed at the bottom of the body element. When the head is passed in, all scripts are placed in the head element.
Favicon: Add the specified favicon path to the output html file.
minify:{... }| false passes in an html-minifier object option to compress the output HTML file.
hash:true | false If the value is true, add a unique webpack compilation hash to all included scripts and CSS files. This is very useful for cache busting.
cache:true | false If true (default), emit (publish) files as long as the file is changed.
showErrors:true | false If true (default), detailed error information will be written to the HTML page.
Chunks: Allows you to add only some chunks (e.g. only the unit-test chunk)
chunksSortMode: Allows you to control how chunks should be sorted before they are include d in the html file. Permissible value:'none'|'auto' |'dependency'| {function} Default value:'auto'.
Exclude Chunks: Allow you to skip some chunks (e.g. don't't add the unit-test chunk)
xhtml:true | false If true, render link tag as self-closing tag, XHTML compliant. The default is false.
Reference to parameters from: front-end xiyoki link: http://www.jianshu.com/p/2c849a445a91
Technological process
npm install html-webpack-plugin --save-dev
html-webpack-plugin version: 2.30.1
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var htmlWebpackPlugin = require('html-webpack-plugin'); //1. introduction
//A Method of Obtaining Parameters from html-webpack-plugin
var getHtmlConfig = function(name){
return {
template:'./src/view/' + name +'.html',
filename:'view/' + name + '.html',
inject:true,
hash:true,
chunks:['common',name]
}
}
var config = {
entry: {
'common':['./src/page/common/index.js'],
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
output: {
path: './dist',
filename: 'js/[name].js'
},
externals:{
'jquery':'window.jQuery'
},
module:{
loaders:[
{test:/\.css$/,loader:ExtractTextPlugin.extract("style-loader","css-loader")}
]
},
plugins:[
//Independent Universal Module js/base.js
new webpack.optimize.CommonsChunkPlugin({
name:'common',
filename:'js/base.js'
}),
//Pack css in a separate file
new ExtractTextPlugin("css/[name].css"),
//html template processing
new htmlWebpackPlugin(getHtmlConfig('index')),
new htmlWebpackPlugin(getHtmlConfig('login'))
]
};
module.exports = config
ok, our automatic packaging of HTML templates is successful. But every time we pack, we need to have an initial HTML file. We need to add a jquery reference to each file. It's troublesome, because we need this html-loader as a mediator later.
npm install html-loader --save-dev
html-loader version: 0.5.1
Well, let's take the head out.
//html-head.html
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
//index.html
<!doctype html>
<html lang="en">
<%= require('html-loader!./layout/html-head.html') %>
<body>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
</body>
</html>
Picture Processing Problems
npm install url-loader --save-dev
html-loader version: 0.6.2
In this case, your picture will be converted to base64 format and stored in the css file
...
module:{
loaders:[
{test:/\.css$/,loader:ExtractTextPlugin.extract("style-loader","css-loader")},
{test:/\.(gif|png|jpg)\??.*$/,loader:'url-loader'},
]
},
...
Of course, the advantage is that you have fewer requests, but we still need to put a place for large files to be taken out of css files.
npm install file-loader --save-dev
file-loader version: 1.1.6
module:{
loaders:[
{test:/\.css$/,loader:ExtractTextPlugin.extract("style-loader","css-loader")},
{test:/\.(gif|png|jpg|jpeg)\??.*$/,loader:'file-loader?limit=1000&name=resource/[name].[ext]'}
]
},
Problems of icon-font processing
module:{
loaders:[
{test:/\.css$/,loader:ExtractTextPlugin.extract("style-loader","css-loader")},
{test:/\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/,loader:'file-loader?limit=1000&name=resource/[name].[ext]'}
//Just add an extension here.
]
},
Installation of webpack-dev-server
npm install webpack-dev-server --save-dev
webpack-dev-server version: 2.9.7
To be able to use commands, install webpack-dev-server globally
npm install webpack-dev-server -g
Executing webpack-dev-server, we found that we used its iframe mode, which is not conducive to our debugging, so we took another way.
First, we need to place the proxy of webpack-dev-server on the page, and the common module is available on all pages, so:
//webpack.config.js
...
entry: {
'common':['./src/page/common/index.js','webpack-dev-server/client?http://localhost:8088/'], //Setting agent
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
...
Execute orders:
webpack-dev-server --inline --port 8088
But since the path of webpack-dev-server is'/', and our path is'. /', we need to specify the path of page access.
//webapck.config.js
...
output: {
path: './dist',
publicPath:'/dist', //Access Path of Page
filename: '/js/[name].js'
},
...
But this module of webpack-dev-server is not needed when we are online, so we configure it as follows
//webapck.config.js
...
//Environment variable configuration dev / Online
var WEBPACK_ENV = process.env.WEBPACK_ENV || 'dev'
console.log(WEBPACK_ENV)
//Make judgement
if(WEBPACK_ENV === 'dev'){
config.entry.common.push('webpack-dev-server/client?http://localhost:8088/')
}
entry: {
'common':['./src/page/common/index.js'],
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
...
Finally, don't forget to delete the webpack-dev-server configuration in common, which is what the following common looks like:
'common':['./src/page/common/index.js'],
...
entry: {
'common':['./src/page/common/index.js','webpack-dev-server/client?http://localhost:8088/'], //Setting agent
'index':['./src/page/index/index.js'],
'login':['./src/page/login/index.js']
},
...
At this point, execute the command
WEBPACK_ENV=dev webpack-dev-server --inline --port 8088
OK, our webpack-dev-server is basically configured. Now let's optimize our npm command
//package.json
...
"scripts": {
"dev" : "WEBPACK_ENV=dev webpack-dev-server --inline --port 8088",
"dev_win" : "set WEBPACK_ENV=dev && webpack-dev-server --inline --port 8088",
"dist": "WEBPACK_ENV=online webpack -p",
"dist_win": "set WEBPACK_ENV=online && webpack -p"
},
...
Implementation:
Under Linux and Mac, execute the following commands:
npm run dev
Under windows, execute the following commands:
npm run dev_win