什麼是webpack
WebPack可以看做是子產品打包機:它做的事情是,分析你的項目結構,找到JavaScript子產品以及其它的一些浏覽器不能直接運作的拓展語言(Sass,TypeScript等),并将其轉換和打包為合适的格式供浏覽器使用。在3.0出現後,Webpack還肩負起了優化項目的責任。
其最主要的就是三點:打包,轉換,優化
webpack 配置
module.exports = {
<!--入口-->
entry:'',
<!--出口-->
output:'',
<!--子產品-->
module: {},
<!--插件-->
plugins: [],
<!--服務-->
devServer: {}
}
這些配置都是老生常淡,直接進入正題吧
webpack 在vue 中
webopack.base.conf.js
'use strict'
//node 子產品
const path = require('path')
// 從vue-loder.conf中引入
const utils = require('./utils')
// 對dev和prod環境配置
const config = require('../config')
//配置css-loader
const vueLoaderConfig = require('./vue-loader.conf')
// 封裝resolve
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
// 配置eslint
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
// context 是webpack entry的上下文,是入口檔案所處的目錄的絕對路徑, ../ 對應上層路徑
context: path.resolve(__dirname, '../'),
// entry 代表spa入口,從何main.js 引入所有元件
entry: {
app: './src/main.js'
},
// 輸出路徑
output: {
// assetsRoot: path.resolve(__dirname, '../dist'),
path: config.build.assetsRoot,
// 代表輸出打包後的名字
filename: '[name].js',
// 對應環境 assetsPublicPath: '/', assetsPublicPath: '/', 是dev還是prod
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
// resolve字段告訴webpack怎麼去搜尋檔案
resolve: {
// 預設值:extensions:['.js', '.json'],當導入語句沒帶檔案字尾時,Webpack會根據extensions定義的字尾清單進行檔案查找
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
// 子產品打包器
module: {
rules: [
// 配置是否開啟 eslint
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
//對css 配置封裝 exports.cssLoaders
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
// babel 引入查找,從src,test,node_modules中
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
//限制轉化圖檔記憶體大小
limit: 10000,
//輸出位址已經在後面加上哈希值
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
webpack.dev.conf.dev
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
//一個可以合并數組和對象的插件
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
// 用于将static中的靜态檔案複制到産品檔案夾dist
const CopyWebpackPlugin = require('copy-webpack-plugin')
//用于将webpack編譯打包後的産品檔案注入到html模闆中,即自動在index.html中裡面機上和标簽引用webpack打包後的檔案
const HtmlWebpackPlugin = require('html-webpack-plugin')
//用于更友好的輸出webpack的警告,錯誤資訊等
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// 端口累加
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
// 合并base内容到裡面
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
// exports.styleLoaders
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
// Webpack中使用DefinePlugin插件來定義配置檔案适用的環境
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
// 開啟子產品熱替換HMR
new webpack.HotModuleReplacementPlugin(),
// 使用 NamedModulesPlugin 可以使控制台列印出被替換的子產品的名稱而非數字ID,另外同webpack監聽,忽略node_modules目錄的檔案可以提升性能。
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
// 使用 NoEmitOnErrorsPlugin 來跳過輸出階段,這樣可以確定輸出資源不會包含錯誤
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
// 啟動伺服器疊加
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
webapck.prod.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
// 靜态檔案
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 打包html
const HtmlWebpackPlugin = require('html-webpack-plugin')
// extract-text-webpack-plugin該插件的主要是為了抽離css樣式,防止将樣式打包在js中引起頁面樣式加載錯亂的現象
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// 用于優化或者壓縮CSS資源
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
// 壓縮js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
// 該插件會根據子產品的相對路徑生成一個四位數的hash作為子產品id, 建議用于生産環境
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
//作用域提升,是在Webpack3中推出的功能,它分析子產品間的依賴關系,盡可能将被打散的子產品合并到一個函數中,但不能造成代碼備援,是以隻有被引用一次的子產品才能被合并。由于需要分析子產品間的依賴關系,是以源碼必須是采用了ES6子產品化的,否則Webpack會降級處理不采用Scope Hoisting。
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
// 提取頁面間公共代碼,以利用緩存
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
//是否開啟Gzip加速
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
// 可視化分析工具,比Webapck Analyse更直覺。使用也很簡單
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig