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

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

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

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

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

test.js

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 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: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
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文件中增加环境变量配置

test.env.js 增加环境变量

index.js

module.exports = {
build: {
env: require('./prod.env'),index: path.resolve(dirname,'../dist/index.html'),assetsRoot: path.resolve(dirname,'../dist'),assetsSubDirectory: 'static',// assetsPublicPath: './',assetsPublicPath: '',//公共资源路径
productionSourceMap: false,// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to true,make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,productionGzipExtensions: ['js','css'],// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// npm run build --report
// Set to true or false to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},fev: {
env: require('./test.env'),assetsPublicPath: './',test: {
env: require('./test.env'),productionSourceMap: false,dev: {
env: require('./dev.env'),port: 8081,autoOpenBrowser: true,assetsPublicPath: '/',proxyTable: {
// '/api':{
// target:'http://jsonplaceholder.typicode.com',// changeOrigin:true,// pathRewrite:{
// '/api':''
// }
// }
},// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option,according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience,they generally work as expected,// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}

4、在main.js文件中在增加环境变量判断

5、如果公共资源路径,在不同环境中需要更改。在webpack.base.conf.js 中配置打包文件输出的公共路径。

//测试使用
entry: {
app: ["promise-polyfill","./src/main.js"]
},// entry: {
// app: './src/main.js'
// },output: {
path: config.build.assetsRoot,filename: '[name].js',publicPath: webpack_public_path
// publicPath: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'fev' ? config.build.assetsPublicPath
// : config.dev.assetsPublicPath
},resolve: {
extensions: ['.js','.vue','.json'],modules: [
resolve('src'),resolve('node_modules'),],alias: {
'vue$': 'vue/dist/vue.common.js','src': resolve('src'),'assets': resolve('src/assets'),'components': resolve('src/components'),'vendor': path.resolve(dirname,'../src/api'),// 'vendor': path.resolve(dirname,'../src/vendor'),}
},module: {
rules: [
{
test: /.vue$/,loader: 'vue-loader'
},{
test: /.js$/,loader: 'babel-loader',include: [resolve('src'),resolve('test')]
},{
test: /.(png|jpe?g|gif|svg)(\?.)?$/,loader: 'url-loader',query: {
limit: 10000,name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},{
test: /.(woff2?|eot|ttf|otf)(\?.
)?$/,name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: 首先在编辑器里面插入javascript代码: 确定后会在编辑器插入这样的代码: <pre
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换为SyntaxHighlighter代码高亮插件 上一篇“让kindeditor显示高亮代码”中已经
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)
原生JS实现别踩白块小游戏(一)