1. 程式人生 > 其它 >vue-cli2分環境打包測試包與正式包

vue-cli2分環境打包測試包與正式包

技術標籤:vuevue.js

首先確定安裝cross-env

npm i cross-env --save-dev

看下目錄結構:

在這裡插入圖片描述

1、build資料夾中新建test.js檔案,內容複製build.js。修改個地方。process.env.NODE_ENV = ‘test’ 以及const webpackConfig = require(’./webpack.test.conf’)

'use strict'
require('./check-versions')()

process.env.NODE_ENV = 'test'     //修改這裡

const ora = require
('ora') const rm = require('rimraf') const path = require('path') const chalk = require('chalk') const webpack = require('webpack') const config = require('../config') const webpackConfig = require('./webpack.test.conf') //還有這裡 const spinner = ora('building for production...') spinner.start() rm(path.
join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, (err, stats) => { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children:
false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. chunks: false, chunkModules: false }) + '\n\n') if (stats.hasErrors()) { console.log(chalk.red(' Build failed with errors.\n')) process.exit(1) } 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' )) }) })

2、build資料夾中新建webpack.test.conf.js,同樣複製webpack.prod.conf.js。修改一處內容const env = require(’…/config/test.env’)

'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')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = require('../config/test.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'),
            allChunks: true,
        })new OptimizeCSSPlugin({
            cssProcessorOptions: config.build.productionSourceMap ? { safe: true, map: { inline: false } } : { safe: true }
        }),
        new HtmlWebpackPlugin({
            filename: config.build.index,
            template: 'index.html',
            inject: true,
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true
            },
            chunksSortMode: 'dependency'
        }),
        new webpack.HashedModuleIdsPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks(module) {
                return (
                    module.resource &&
                    /\.js$/.test(module.resource) &&
                    module.resource.indexOf(
                        path.join(__dirname, '../node_modules')
                    ) === 0
                )
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'manifest',
            minChunks: Infinity
        }),
        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) {
    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) {
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
    webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

3、修改build資料夾中utils.js檔案,使打包測試包也正式包時配置相同

exports.assetsPath = function(_path) {
    const assetsSubDirectory = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test' ?
        config.build.assetsSubDirectory :
        config.dev.assetsSubDirectory

    return path.posix.join(assetsSubDirectory, _path)
}

4、修改build資料夾中webpack.base.conf.js ,使打包測試包也正式包時配置相同

output: {
        path: config.build.assetsRoot,
        filename: '[name].js',
        publicPath: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === "test" ?
            config.build.assetsPublicPath : config.dev.assetsPublicPath
    },

5、修改config下的index.js裡的打包配置。根據process.env.NODE_ENV 區分打包測試包和正式包,並分別打包到不同的檔案裡.

 build: {
        // Template for index.html
        index: process.env.NODE_ENV === 'test' ? path.resolve(__dirname, '../test/index.html') : path.resolve(__dirname, '../dist/index.html'), //測試包與正式包入口檔案路徑區分

        // Paths
        assetsRoot: process.env.NODE_ENV === 'test' ? path.resolve(__dirname, '../test') : path.resolve(__dirname, '../dist'),  //測試包也正式包打包後文件區分
        assetsSubDirectory: 'static',
        assetsPublicPath: './', //history模式下要寫成 /

        productionSourceMap: false,
        devtool: '#source-map',

        productionGzip: false,
        productionGzipExtensions: ['js', 'css'],
        bundleAnalyzerReport: process.env.npm_config_report
    }

6、config資料夾下prod.env.js配置:

'use strict'
const BUILD_ENV = process.env.BUILD_ENV
module.exports = {
    NODE_ENV: '"production"',
    BUILD_ENV: '"' + BUILD_ENV + '"',
    baseUrl: '"正式服請求地址"'
}

7、config資料夾下test.env.js配置:

'use strict'

const BUILD_ENV = process.env.BUILD_ENV

module.exports = {
    NODE_ENV: '"test"',
    BUILD_ENV: '"' + BUILD_ENV + '"',
    // baseUrl: '"' + baseUrl + '"',
    baseUrl: '"測試服請求地址"'
}

8、package.json中,新增build:test命令,也可將新增同時打包正式包與測試包的publish命令

"scripts": {
        "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
        "start": "npm run dev",
        "build:prod": " node build/build.js",
        "build:test": " node build/test.js",
        "publish": "npm run build:prod  && npm run build:test"
    },

9、封裝的axios請求檔案中:根據環境不同修改請求地址

axios.defaults.baseURL = process.env.baseUrl 

10、執行相應命令,就好了