详解webpack进阶之插件篇(2)

new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" })) new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.CommonsChunkPlugin('common.js')

作用: 和上面5个一一对应

  当模块使用这些变量的时候,wepback会自动加载。(区别于window挂载,感谢@lihuanghe121指正)

  不显示错误插件

  查找相等或近似的模块,避免在最终生成的文件中出现重复的模块

  丑化js 混淆代码而用

  提取公共代码的插件

二、一个完整的栗子

'use strict'; // Modules var webpack = require('webpack'); var autoprefixer = require('autoprefixer'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); /** * Env * Get npm lifecycle event to identify the environment */ var ENV = process.env.npm_lifecycle_event; var isTest = ENV === 'test' || ENV === 'test-watch'; var isProd = ENV === 'build'; module.exports = function makeWebpackConfig() { var config = {}; config.entry = isTest ? {} : { app: './src/app/app.js' }; config.output = isTest ? {} : { // Absolute output directory path: __dirname + '/dist', publicPath: isProd ? 'https://www.jb51.net/' : 'http://localhost:8080/', filename: isProd ? '[name].[hash].js' : '[name].bundle.js', chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js' }; if (isTest) { config.devtool = 'inline-source-map'; } else if (isProd) { config.devtool = 'source-map'; } else { config.devtool = 'eval-source-map'; } config.module = { preLoaders: [], loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.css/, loader: isTest ? 'null' : ExtractTextPlugin.extract('style', 'css?sourceMap!postcss') }, { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, loader: 'file' }, { test: /\.json$/, loader: 'json' }, { test: /\.scss/, loader: 'style!css!sass' }, { test: /\.html$/, loader: 'raw' }] }; if (isTest) { config.module.preLoaders.push({ test: /\.js$/, exclude: [ /node_modules/, /\.spec\.js$/ ], loader: 'isparta-instrumenter' }) } config.postcss = [ autoprefixer({ browsers: ['last 2 version'] }) ]; config.plugins = []; if (!isTest) { config.plugins.push( new HtmlWebpackPlugin({ template: './src/public/index.html', inject: 'body' }), new ExtractTextPlugin('[name].[hash].css', {disable: !isProd}) ) } if (isProd) { config.plugins.push( new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), new CopyWebpackPlugin([{ from: __dirname + '/src/public' }]), new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" })) } config.devServer = { contentBase: './src/public', stats: 'minimal' }; return config; }();

三、调试技巧

if (isTest) { config.devtool = 'inline-source-map'; }

作用: 使用source-map可以在debug的时候看到源代码,方便 查错

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfzjd.html