详解Webpack多环境代码打包的方法

在实际开发中常遇到,代码在

在package.json文件的scripts中,会提供开发环境与生产环境两个命令。但是实际使用中会遇见 测试版与正式版代码相继发布的情况,这样反复更改服务器地址,偶尔忘记更改url会给工作带来很多不必要的麻烦(当然也会对你的工作能力产生质疑)。这样就需要在生产环境中配置测试版本打包命令与正式版本打包命令。

1、Package.json 文件中 增加命令行命令,并指定路径。

"scripts": { "dev": "node build/dev-server.js", "build": "node build/build.js",      //正式环境打包命令 "fev": "node build/test.js" //测试环境打包命令 },

2、在build文件中添加相应文件

详解Webpack多环境代码打包的方法

test.js

// https://github.com/shelljs/shelljs require('./check-versions')() process.env.NODE_ENV = 'fev' var ora = require('ora') var path = require('path') var chalk = require('chalk') var shell = require('shelljs') var webpack = require('webpack') var config = require('../config') var webpackConfig = require('./webpack.test.conf') var spinner = ora('building for fev...') spinner.start() var assetsPath = path.join(config.fev.assetsRoot, config.fev.assetsSubDirectory) shell.rm('-rf', assetsPath) shell.mkdir('-p', assetsPath) shell.config.silent = true shell.cp('-R', 'static/*', assetsPath) shell.config.silent = false webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n') console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' )) })

webpack.test.conf.js

var path = require('path') var utils = require('./utils') var webpack = require('webpack') var config = require('../config') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') var HtmlWebpackPlugin = require('html-webpack-plugin') var ExtractTextPlugin = require('extract-text-webpack-plugin') var env = config.fev.env var webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.fev.productionSourceMap, extract: true }) }, devtool: config.fev.productionSourceMap ? '#source-map' : false, output: { path: config.fev.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, plugins: [ // new webpack.DefinePlugin({ 'process.env': env }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, drop_console: true }, sourceMap: true }), // extract css into its own file new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css') }), // 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.fev.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' }), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { // 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', chunks: ['vendor'] }) ] }) if (config.fev.productionGzip) { var CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.fev.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) ) } if (config.fev.bundleAnalyzerReport) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig

3、在config文件中增加环境变量配置

详解Webpack多环境代码打包的方法

test.env.js 增加环境变量

module.exports = { NODE_ENV: '"fev"' }

index.js

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

转载注明出处:http://www.heiqu.com/ca4c77e82f637606c0a24a443db1c948.html