上一章講的是分離樣式,這一章講的是剩下的一些我經常使用的插件,和上一章是沒有任何關係。webpack
$ mkdir 0x0016-other-plugin $ cd 0x0016-other-plugin $ npm init -y $ vim webpack.config.js // ./webpack.config.js const path = require('path'); module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].bundle.js' } ;
EnvironmentPlugin
定義環境插件介紹
這個插件用來定義環境變量的,直接定義在了process.env
下。git
修改配置github
plugins: [ new webpack.EnvironmentPlugin({ NODE_ENV:'development', DEBUG:false }) ]
編寫代碼web
if (process.env.NODE_ENV==='production') { console.log('Welcome to production'); } if (process.env.DEBUG) { console.log('Debugging output'); }
編譯並查看結果npm
/* 1 */ /***/ (function(module, exports, __webpack_require__) { if (false) { console.log('Welcome to production'); } if (false) { console.log('Debugging output'); } /***/ })
更多配置請查閱webpack關於EnvironmentPlugin相關章節vim
CleanWebpackPlugin
清除文件夾插件介紹
這個插件用來清除某個路徑下的文件的,通常用來清理上次打包以後的殘留文件。segmentfault
不使用插件打包文件
這裏咱們修改一下output.filename:
爲[name].[chunkhash].js'
,這樣每次輸出的文件就都不同了ui
打包代碼this
$ webpack // ./dist index.dfa7ddd294976d60a25f.js
修改代碼插件
// ./src/index.js if (process.env.NODE_ENV==='production') { console.log('Welcome to production'); } if (process.env.DEBUG) { console.log('Debugging output'); } console.log('clearwebpackplugin')
再次打包
$ webpack // ./dist index.69ed567b40b7234d1ea4.js index.dfa7ddd294976d60a25f.js
能夠看到,上次打包的文件依舊在,這不方面咱們直接部署到線上,手動刪除可不符合webpack
的初衷,因此須要用到這個插件
安裝依賴
$ cnpm install --save-dev clean-webpack-plugin
修改依賴
const path = require('path'); var webpack = require('webpack') const CleanWebpackPlugin = require('clean-webpack-plugin') module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].[chunkhash].js' }, plugins: [ new webpack.EnvironmentPlugin({ NODE_ENV: 'development', DEBUG : false }), new CleanWebpackPlugin(path.resolve(__dirname, 'dist')) ] };
打包編譯
$ webpack // ./dist index.69ed567b40b7234d1ea4.js
啊世界清靜了,之前的文件都沒了!
更多配置請查看clean-webpack-plugin官方文檔
copyWebpackPlugin
複製文件插件介紹
用來直接複製文件的,好比資源文件,有一些文件咱們但願他不打包到js
中,可是又須要部署到生成環境下,爲了方便部署,將它們和要部署的文件放在同一個文件夾下,方便部署。
安裝依賴
$ cnpm install --save-dev copy-webpack-plugin
添加資源
$ mkdir ./asset $ cd ./asset $ vim resource.txt this is resource!
修改配置
const path = require('path'); const webpack = require('webpack') const CleanWebpackPlugin = require('clean-webpack-plugin') const CopyWebpackPlugin=require('copy-webpack-plugin') module.exports = { entry : { 'index': ['./src/index.js'], }, output: { path : path.join(__dirname, 'dist'), filename: '[name].[chunkhash].js' }, plugins: [ new webpack.EnvironmentPlugin({ NODE_ENV: 'development', DEBUG : false }), new CleanWebpackPlugin(path.resolve(__dirname, 'dist')), new CopyWebpackPlugin([ { from:path.resolve(__dirname,'asset'), to:path.resolve(__dirname,'dist/asset') } ]) ] };
打包
$ webpack // ./dist asset -resource.txt index.69ed567b40b7234d1ea4.js
其餘更多配置請查閱webpack關於CopyWebpackPlugin