Webpack
Webpack is a front-end resource loading/packaging tool. It performs static analysis according to the dependencies of modules, and then generates corresponding static resources according to the specified rules of these modules.
The configuration file
- The entry entry tells Webpack which file to use as the entry to the project
- Where does the output exit let WebPack put the processed packaged files
- What different modules are used to handle various types of files
1. Build projects
- Create the project and init it
Mkdir webpack CD webpack NPM initCopy the code
- The new file
index.js
,run.js
// run.js function text() { var element = document.createElement('p') element.innerHTML = 'hello world' return element } module.exports = textCopy the code
// index.js
var text = require('./run)
var app = document.createElement('div')
app.innerHTML = '<h1>HELLO WORLD</h1>'
app.appendChild(text())
document.body.appendChild(app)
Copy the code
- Configuration Webpack
Install a plugin to automatically generate HTML
npm install html-webpack-plugin --save-dev
// webpack.config.js var path = require('path') var HtmlwebpackPlugin = require('html-webpack-plugin' var ROOT_PATH = path.resolve(__dirname) var APP_PATH = path.resolve(ROOT_PATH, 'app') var BUILD_PATH = path.resolve(ROOT_PATH, 'build') module.exports = {// the name of the project folder can be used directly. Output: {path: BUILD_PATH, filename: [new HtmlwebpackPlugin({title: 'Hello World app'})]}Copy the code
- run
webpack
2. Configure hot update
npm install webpack-dev-server --save-dev
- in
config
Add configuration to
module.exports = {
.....
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
progress: true
},
.....
}
Copy the code
- in
package.json
To add the script command
. "scripts": { "dev": "webpack-dev-server --hot --inline" }, .....Copy the code
- run
npm run dev
Implement hot update
3. Add the loader
Webpack itself can only recognize JS files. For non-JS files, loader is required to convert them to JS files. Loader is a resource converter.
- Install the loader
npm install css-loader style-loader sass-loader --save-dev
- in
config.js
Configure loader in the file
module.exports = {
.....
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'scss'],
include: APP_PATH
}
]
}
.....
}
Copy the code
4. Add the Babel
- The installation
npm install babel-loader babel-preset-es2015 --save-dev
- configuration
config.js
file
module: {
loaders: [
.....
{
test: /\.js?$/,
loader: 'babel',
include: APP_PATH,
query: {
presets: ['es2015']
}
}
.....
]
}
Copy the code
Continuously updated…