webpack简单配置
1、初始化(获得package.json文件)
npm init -y
2、安装webpack 开发依赖 ,还需要webpack-cli
@为选择特定版本
npm i webpack --save--dev
或者使用
npm i webpack -D
3、安装babel 以及ES2015和stage-0预设(-0的范围最大,-4最精确),将ES6~ES8转换为ES5,以便被大多数浏览器所兼容、识别。
npm i babel babel-core babel-loader -D
npm i babel-preset-es2015 babel-preset-stage-0 -D
4、设置 .babelrc文件(用来设置预设)
{"presets": ["es2015","stage-0"]}
5、安装识别和转义CSS的loader
// 对于css,先用css-loader转换成css,再用style-loader将css放到页面中(安装时是不需要考虑顺序问题,使用时需要考虑,从右到左开始使用),假如使用less预处理语言
npm i style-loader css-loader less less-loader -D
6、识别文件路径的(例如:导入图片 import pic from ‘./assets/pic.jpg’)
npm i file-loader url-loader -D
7、安装识别的html插件
npm i html-webpack-plugin -D
8、webpack.config.js文件
let HtmlWebpackPlugin = require('html-webpack-plugin');
let path = require('path');
module.exports = {
entry: "./src/main.js",
output: {
filename: "build.js",
path: path.resolve('./dist')
},
module: {
rules: [
{ test: /\.js$/, use: ["babel-loader"], exclude: /node-modules/ },
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.less$/, use: ["style-loader", "css-loader", "less-loader"] },
{ test: /\.(jpg|gif|jpeg|png)$/i, use: ["url-loader?limit=5120"] }
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html"
})
]
}
9、package.json文件
{
"name": "webpackcli",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^5.0.1",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^4.5.0",
"less": "^3.12.2",
"less-loader": "^7.1.0",
"style-loader": "^2.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.6.0",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^3.11.0"
}
}