Vue实现通过npm启动和打包时自动切换assetsPublicPath的路径
文章已阅读次
通常情况下我们是修改config》index.js》assetsPublicPath的值:
开发环境:’/‘
生产环境:’./‘
来解决这个问题,但是我们每次在开发和生产环境(测试与打包)切换的时候,就要手动去修改这个值,这是比较麻烦的,万一忘记修改了,打包到线上就会出现异常,相当烦人!
有没有一个让npm进行测试运行和打包的时候自动切换这个路径的一劳永逸的办法呢?
答案是有的!
1)修改package.json配置脚本指令(dev,start,build):
"scripts": {
"dev": "set NODE_ENV=development&&webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "set NODE_ENV=development&&npm run dev",
"build": "set NODE_ENV=production&&node build/build.js"
}
看看我们的指令dev,start,build都添加了什么内容。
增加一个名为NODE_ENV的变量,同时:
(1)在执行指令npm run dev 或 npm run start指令时给变量赋值为:development
(2)在执行指令 npm run build指令时给变量赋值为:production
2)增加修改config》index.js中的内容:
‘use strict’
const path = require(‘path’)
const runPath = process.env.NODE_ENV === ‘development’ ? ‘/‘ : ‘./‘ //#新增项/module.exports = {
dev: {// Paths assetsSubDirectory: 'static', assetsPublicPath: runPath,//#修改项/ proxyTable: { }, // Various Dev Server settings host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- /** * Source Maps */ // https://webpack.js.org/configuration/devtool/#development devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools, // set this to false - it *may* help // https://vue-loader.vuejs.org/en/options.html#cachebusting cacheBusting: true, cssSourceMap: true }, build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: runPath,//#修改项/ /** * Source Maps */ productionSourceMap: true, // https://webpack.js.org/configuration/devtool/#production devtool: '#source-map', // 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 }
}
调整的地方是备注为“新增项”和“修改项”的内容
这样,我们便实现了Vue项目在运行和打包自动切换路径的功能。