插件

webpack有很多内置插件,也有第三方插件,用来拓展webpack相关功能
如果是第三方插件,需要先安装

HtmlWebpackPlugin

自动生成html插件,自动在dist目录下自动生成一个index.html

  1. //webpack.config.js
  2. var HtmlWebpackPlugin = require('html-webpack-plugin');
  3. module.exports={
  4. entry:'./index.js',
  5. output:{
  6. path:__dirname+'/dist',
  7. filename:'bundle.js'
  8. }
  9. plugins:[
  10. new HtmlWebpackPlugin()
  11. ]
  12. }

更多的配置

  1. plugins: [
  2. new HtmlWebpackPlugin({
  3. title: 'My App',
  4. filename: 'admin.html',
  5. template:'header.html',
  6. inject: 'body',
  7. favicon:'./images/favico.ico',
  8. minify:true,
  9. hash:true,
  10. cache:false,
  11. showErrors:false,
  12. "chunks": {
  13. "head": {
  14. "entry": "assets/head_bundle.js",
  15. "css": [ "main.css" ]
  16. },
  17. xhtml:false
  18. })
  19. ]

extract-text-webpack-plugin

提取样式插件

  1. var ExtractTextPlugin = require("extract-text-webpack-plugin");
  2. new ExtractTextPlugin("[name].[hash].css")

优化插件

需要在生产打包时进行额外的处理,比如压缩js代码.
就要用到内置插件UgilifyJsPugin

  1. plugins:[
  2. new webpack.optimize.UglifJsPlugin()
  3. ]

在生产打包会有更多处理,在vue-cli中有以下配置

  1. new webpack.optimize.CommonsChunkPlugin({
  2. name: 'vendor',
  3. minChunks: function (module, count) {
  4. // any required modules inside node_modules are extracted to vendor
  5. return (
  6. module.resource &&
  7. /\.js$/.test(module.resource) &&
  8. module.resource.indexOf(
  9. path.join(__dirname, '../node_modules')
  10. ) === 0
  11. )
  12. }
  13. }),
  14. // extract webpack runtime and module manifest to its own file in order to
  15. // prevent vendor hash from being updated whenever app bundle is updated
  16. new webpack.optimize.CommonsChunkPlugin({
  17. name: 'manifest',
  18. chunks: ['vendor']
  19. }),

总之,webpack配置还挺复杂,值得弄明白,听说以前还有专门的webpack岗位,下面还会就vue-cli这种专业的配置总结一下.