webpack.common.js const path = require('path') const htmlWebpackPligin = require('html-webpack-plugin') const cleanWebpackPligin = require('clean-webpack-plugin') const webpack = require('webpack') const merge = require('webpack-merge') const devConfig = require('./webpack.dev') const prodConfig = require('./webpack.prod')
const commonConfig = { entry:{ main:'./src/index.js' }, output:{ path:path.resolve(__dirname,'../dist') }, optimization:{ usedExports: true }, module:{ rules:[ { test: /\.m?js$/, exclude: /node_modules/, use: [ { loader: "babel-loader", },{ loader: "imports-loader?this=>window", } ] } , { test:/\.(jpg|png|gif)$/, use:{ loader: 'url-loader', options:{ name:'[name]_[hash].[ext]', outputPath:'images/', // 文件大于200kb 会生成文件 否则生成 base64图片格式 limit:204800 //200kb } } }, { test:/\.(woff2|woff|ttf)$/, use:{ loader:'file-loader' } } , ] }, // 配置 代码分割 optimization:{ runtimeChunk:{ name: 'runtime' }, usedExports:true, splitChunks:{ chunks:"all" , cacheGroups:{ vendors: { test: /[\\/]node_modules[\\/]/, priority:-10, name:'vendors' } } } }, performance:false, plugins:[ new htmlWebpackPligin({ template:`./src/index.html` }), new cleanWebpackPligin(['dist'],{ root: path.resolve(__dirname,'../') }), new webpack.ProvidePlugin({ $:'jquery', _:'lodash' }) ], } module.exports = (env) => { if(env && env.production){ return merge(commonConfig,prodConfig) }else{ return merge(commonConfig,devConfig) } } webpack.dev.js const webpack = require('webpack') const devConfig = { // 开发配置 mode:'development', devtool:"cheap-module-eval-source-map", output:{ filename: '[name].js', chunkFilename:'[name].js' }, plugins:[ new webpack.HotModuleReplacementPlugin() ], devServer:{ contentBase:'./dist', open: true, hot:true, port:8080 }, module:{ rules:[ { test:/\.css$/, use:['style-loader','css-loader', 'postcss-loader' ] } , { test:/\.scss$/, use:[ 'style-loader', // 'css-loader', { loader:'css-loader', options:{ importLoaders:2, // modules:true // 开启modules 模块化css } }, 'sass-loader', 'postcss-loader' ] } ] }, } module.exports = devConfig webpack.prod.js const miniCssExtractPlugin = require('mini-css-extract-plugin') const optimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
const prodConfig = { // 线上配置 mode:'production', // devtool:"cheap-module-source-map", module:{ rules:[ { test:/\.css$/, use:[ miniCssExtractPlugin.loader,'css-loader', 'postcss-loader' ] } , { test:/\.scss$/, use:[ miniCssExtractPlugin.loader, // 'css-loader', { loader:'css-loader', options:{ importLoaders:2, // modules:true // 开启modules 模块化css } }, 'sass-loader', 'postcss-loader' ] } ] }, optimization:{ minimizer:[new optimizeCssAssetsWebpackPlugin({})] }, plugins:[ new miniCssExtractPlugin({ filename:'[name].css', chunkFilename:'[name].chunk.css', }) ], output:{ filename: '[name].[contenthash].js', chunkFilename:'[name].[contenthash].js' }, }
module.exports = prodConfig