Vue-cli2 separate environment packaging test package and official package

First make sure to install cross-env

npm i cross-env --save-dev

Look at the directory structure:

Insert picture description here

1. Create a new test.js file in the build folder and copy the content of build.js. Modify a place. process.env.NODE_ENV ='test' and 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. Create a new webpack.test.conf.js in the build folder, and copy webpack.prod.conf.js as well. Modify a content 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. Modify the utils.js file in the build folder so that the configuration of the packaged test package is the same as the official package

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. Modify webpack.base.conf.js in the build folder so that the configuration of the packaged test package is the same as the official package

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. Modify the packaging configuration in index.js under config. According to process.env.NODE_ENV, the packaged test package and the official package are distinguished and packaged into different files.

 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. Prod.env.js configuration under the config folder:

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

7. Test.env.js configuration under the config folder:

'use strict'

const BUILD_ENV = process.env.BUILD_ENV

module.exports = {
    
    
    NODE_ENV: '"test"',
    BUILD_ENV: '"' + BUILD_ENV + '"',
    // baseUrl: '"' + baseUrl + '"',
    baseUrl: '"测试服请求地址"'
}

8. In package.json, add the build:test command, or add the publish command to package the official package and the test package at the same time

"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. In the packaged axios request file: modify the request address according to the environment

axios.defaults.baseURL = process.env.baseUrl 

10. Run the corresponding command and it will be fine

Guess you like

Origin blog.csdn.net/YL971129/article/details/113816783