Plugin
Plugins,即插件。通过plugins可以在webpack运行到某个时刻的时候,帮我们做一些事情。
HtmlWebpackPlugin
HtmlWebpackPlugin可以为我们生成一个HTML文件,并将打包好的JS文件自动引入到这个html文件中。
安装
npm install --save-dev html-webpack-plugin
配置
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: 'index.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'index_bundle.js'
},
plugins: [new HtmlWebpackPlugin({
template: 'src/index.html' // 以src/目录下的index.html为模板打包
}
)],
};
运行
npm run dev
这样我们就可以在dist目录下生成HTML模块,且自动引入bundle.js
CleanWebpackPlugin
这个插件并非官方插件,但非常好用。CleanWebpackPlugin可以帮助我们删除上一次打包好的文件。
安装
npm i clean-webpack-plugin -D
配置
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
// 低版本CleanWebpackPlugin需要配置项 详情移步官网
plugins: [ new CleanWebpackPlugin()]
copy-webpack-plugin
可以为网站添加小图标ico
安装
npm i copy-webpack-plugin -D/ yarn add copy-webpack-plugin -D
配置
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
plugins: [
new CopyWebpackPlugin([{
from: path.resolve(__dirname, '../public/favicon.ico'),
to: path.resolve(__dirname, '../dist/')
}])
]
}
vue-loader
vue开发,src/components/Home.vue
<template>
<div>webpack 开发vue</div>
</template>
<script>
export default {}
</script>
<style lang="stylus" scoped>
</style>
src/app.js入口引入
import Vue from 'vue'
import Home from './components/Home.vue'
new Vue({
el: '#root',
render(h) {
return h(Home)
}
})
安装
npm i vue / yarn add vue
npm i vue-loader -D / yarn add vue-loader -D
npm i vue-template-compiler -D / yarn add vue-template-compiler -D
配置
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: {}
}]
},
plugins: [
new VueLoaderPlugin()
]
}