webpack is a static resource packaging tool (required for the front end)
-
Features of webpack
js relies on packaging and integration
Some pre-processed sass, less can be compiled and converted in the environment,
js, html, image resources can be compressed and optimized -
The core of webpack
- entry entry file
// the core js file of the file - output export file
// packaged dist folder - pligin plugin
// Various plugins - loader converter
// convert the file to the file type we want - dev-serve server
// Let our webpack run locally to build a server - modo mode
// can switch development environment and production environment
Webpack manual construction steps
- Confirm whether there is webpack -v in the current environment. If there is no npm i webpack -g download to the local
- In the folder that you want to be a package file, but the folder name cannot be Chinese, use npm init -y to initialize a package.json
- Create a src, create an index.html under src
- Create a main.js in src as the main development file, perform dom operations in it, and manipulate the root div in html
- Bale
Create a webpack.config.js
const path = require("path")
module.exports = {
entry:"./src/main.js",
output:{
filename:"bundle.js",
path:path.resolve(__dirname,"dist")
}
}
Run the webpack command to pack
- You can use packaged hot start so you do not need to pack every time you modify the
establishment of a local server cnpm webpack-dev-server -D i
download dependentcnpm i node-sass sass-loader style-loader css-loader -D
configuration commands in package.json
added
"dev": "webpack-dev-server --open --port 8888 --contentBase src --hot"
npm run dev run
- Parse scss file
Configure in webpack.config.js
module: {
rules: [
//解析.scss文件,对于用 import 或 require 引入的sass文件进行加载,以及...声明的内部样式进行加载
{
test: /\.scss$/,
use:['style-loader', 'css-loader', 'sass-loader']
}
]
}
- Introduce jquery
download npm i jquery --save
import $ from 'jquery'
// 对#root的样式进行改变
$("#root").css({color:"red",backgroundColor:"green"})
- Automatically generate html page
Download dependent on cnpm i html-webpack-plugin -D
the configuration webpack.config.js
// 插件
plugins:[
new htmlWebpackPlugin({
filename:"index.html",
template:path.join(__dirname,'index.html')
})
],
Get the index.html template to the same level as src
After configuration, you can package and run again