從一個二線城市來到北京,工做模式很不同,也有許多須要掌握的知識與工具,不過這也正是我來北京的緣由。此文中大部份內容都是webpack官方文檔上摘過來的,僅僅是對本身理解薄弱的地方加以整理和概括,加深自身印象。對其餘人的參考意義不大。html
在開發環境中,咱們須要更強大的、實際從新加載(live reloading)或者熱模塊替換(hot module replacement)能力的sourcemap和locahost server。在生產環境中,咱們的目標則轉向關於更小的bundle,更輕量的sourcemap,以及更優化的資源,建議爲每一個環境編寫彼此獨立的webpack配置。webpack
首先安裝webpack-merge
,經過它咱們能夠將開發環境與生產環境中相同的配置單獨摘離出來共同使用,而沒必要重複配置。web
npm install --save-dev webpack-merge
而後咱們能夠定義如下三個配置文件:
webpack.common.jsnpm
const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './src/index.js' }, plugins: [ new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ title: 'Production' }) ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };
webpack.dev.jsjson
const merge = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = merge(common, { devtool: 'inline-source-map', devServer: { contentBase: './dist' } });
webpack.prod.jsapp
const webpack = require('webpack'); const merge = require('webpack-merge'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { devtool: 'source-map', plugins: [ new UglifyJSPlugin({ sourceMap: true }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }) ] });
inline-**
和eval-**
,由於它們能夠增長bundle大小,並下降總體性能。process.env.NODE_ENV
能夠判斷當前是生產環境仍是開發環境,能夠再index.js裏這樣調用:if (process.env.NODE_ENV !== 'production') { console.log('Looks like we are in development mode!:)'); }else{ console.log('Looks like we are in production mode!:)'); }
而後在package.json中做以下定義並運行查看:webpack-dev-server
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --open --config webpack.dev.js", "build": "webpack --config webpack.prod.js --watch" },