不写不知道,一写发现自己真是罗里吧嗦,尽量改进
之前写了webpack的主要概念和一些使用,今天再记一下webpack的plugins和loaders的使用
7.webpack plugins使用
例:html-webpack-plugin ,这个插件的作用主要有两点
? 1.自动在内存中根据指定页面生成一个内存的页面
? 2.自动把打包好的 bundle.js 追加到页面中去
安装插件,终端输入npm i html-webpack-plugin -D
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry:path.join(__dirname,'./src/main.js'),
output:{
path:path.join(__dirname,'./dist'),
filename:"bundle.js"
},
plugins:[
new htmlWebpackPlugin({
template:path.join(__dirname,'./src/index.html'), //以src目录下的index.html为模板
filename:"index.html" //生成一个自动注入bundle.js的index.html文件
})
]
}
webpack
重新打包,dist目录下生成一个新的index.html,输入npm run dev
运行当前页面//使用webpack所携带的插件,只需引入webpack,再用webpack.***获取即可
const webpack = require('webpack')
module.exports = {
entry:path.join(__dirname,'./src/main.js'),
output:{
path:path.join(__dirname,'./dist'),
filename:"bundle.js"
},
plugins:[
new webpack.HotModuleReplacementPlugin(),
new htmlWebpackPlugin({
template:path.join(__dirname,'./src/index.html'), //以src目录下的index.html为模板
filename:"index.html" //生成一个自动注入bundle.js的index.html文件
})
]
}
8.webpack loader使用
? 前面提到webpack自身只能解析JavaScript和JSON文件,所有当我们需要打包其他类型文件如css文件、image文件等,需要使用loader配置。
ul>li{
background-color: cadetblue;
}
npm i style-loader css-loader -D
import './css/index.css'
const path = require('path')
const webpack = require('webpack')
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry:path.join(__dirname,'./src/main.js'),
output:{
path:path.join(__dirname,'./dist'),
filename:"bundle.js"
},
plugins:[
new webpack.HotModuleReplacementPlugin(),
new htmlWebpackPlugin({
template:path.join(__dirname,'./src/index.html'), //以src目录下的index.html为模板
filename:"index.html" //生成一个自动注入bundle.js的index.html文件
})
],
module:{
rules:[
//loader的顺序不能颠倒,webpack使用loader的顺序是从右到左(从下到上)
{test:/\.css$/,use:['style-loader','css-loader']}
]
}
}
原文:https://www.cnblogs.com/dairyDeng/p/11941841.html