学习webpack基础笔记
1.webpack搭建环境最重要的就是如何使用loader和plugins,使用yarn/npm安装插件、预处理器,正确的配置好去使用
2.从0配置webpack
- 1.创建文件夹
- yarn init -y (生成package.json)
-在package.json里面写好
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js",
"build": "webpack --config webpack.product.config.js"
},
- 2.创建webpack.config.js文件配置
- module.exports={} 导出配置文件
- mode: "development | production | none" 指定运行环境,none可不写
- entry: "./src/index.js" 入口环境
- module: {rules:[{}]} 配置正则,loader预处理文件
- plugins:[] 插件
- 3.创建src文件夹
-index.html 写一个项目挂下点
-index.js 引入项目挂载点,编写内容
-index.css 编写css样式引入
- 4.不同的环境可以配置一个webpack.base.config.js
-引入插件,将公共的配置提取出来,不同的环境配置,创建多个文件,在package.json里面声明引用
- 5.输出文件夹,可不写,默认dist,写的话要引入安装path
output:{
path: path.resolve(__dirname,dist_dir)
},
3.常见plugin和loader
HtmlWebpackPlugin
ClearWebpackPlugin
VueLoaderPlugin
style-loader
css-loader
less / less-loader
scss / scss-loader
file-loader
...
module: {
rules: [
{
test:/\.css$/,
loader: ['style-loader', 'css-loader']
},{
test:/\.less$/,
loader: ['style-loader', 'css-loader', 'less-loader']
},{
test:/\.(jpg|png|svg)$/,
loader: ['file-loader']
}
]
},
plugins: [
new CleanWebpackPlugin(dist_dir), ------清理html文件
new HtmlWebpackPlugin({
template:'./src/index.html',
title: 'Dev mode'
})
]
{
"name": "online",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"dev": "webpack --config webpack.dev.config.js",
"build": "webpack --config webpack.prod.config.js"
},
"license": "MIT",
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"file-loader": "^6.0.0",
"html-webpack-plugin": "^3.2.0",
"less": "^3.11.1",
"less-loader": "^5.0.0",
"style-loader": "^1.1.3",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
}
}
vue基础配置
const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
mode: 'development',//指定开发环境
entry: './src/index.js', //入口
module: {
// 处理器
rules: [
{
test:/\.vue$/,
loader:'vue-loader',
},
{
test: /\.js?$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.less$/,
use: [
'vue-style-loader',
'css-loader',
'less-loader'
]
}
]
},
plugins: [ //引入html的插件
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template:"./src/index.html"
}),
]
}
{
"name": "webpack01",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js",
"build": "webpack --config webpack.config.js"
},
"devDependencies": {
"@babel/core": "^7.8.7",
"babel-loader": "^8.0.6",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"less": "^3.11.1",
"less-loader": "^5.0.0",
"vue-loader": "^15.9.0",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
},
"dependencies": {
"http-server": "^0.12.1",
"vue": "^2.6.11"
}
}