vue公共文件提取,打包后修改无需重新打包

vue项目中公共路径在打包之后一旦遇到整体的路径更改就需要再次打包。如果打包后的外部文件,直接修改就能生效,则能事半功倍。下面就介绍两种方案:

方案一:在public文件夹下提取config.json文件

config.json文件

在入口 main.js中引入

import Vue from 'vue';
import ApplyLogin from './ApplyLogin.vue';
import router from '../router/applyRouter.js';
import http from '@/utils/http.js';
import { store } from '@/store/store.js';

function getServerConfig () {
  return new Promise((resolve, reject) => {
    axios.get('./serverConfig.json').then(result => {
      let config = result.data;
      for (let key in config) {
        Vue.prototype[key] = config[key];
      }
      resolve();
    });
  });
}

async function main () {
  await getServerConfig();
  new Vue({
    router,
    store,
    render: h => h(ApplyLogin)
  }).$mount('#login');
}

main();

json不会被webpack打包,这样打包后改baseUrl路径,就能直接生效了。

方案二:在public文件夹下提取config.js文件

由于法一的json文件不能写注释,所以提出js为公共文件。

  • serverConfig.js代码如下:
const serverConfig = {
  baseUrl: '//192.168.1.200:8080',
};
  • 引入
    不要使用import引入该文件,在index.html页面使用script标签引入


  
    
    
    
    mits-front
    
  
  
    
  • 然后在.eslintrc.js文件内声明serverConfig 为全局变量
globals: {
  'serverConfig': false
}
  • 调用
    在其他文件内直接调用全局变量config即可,false指定serverConfig为只读。
const baseUrl = serverConfig.baseUrl;
  • 打包后,config.js未被压缩,可进行修改
    vue公共文件提取,打包后修改无需重新打包_第1张图片
    image.png

    方法二借鉴,戳我查看

方案三:在public文件夹下提取serverConfig.yml文件

由于代码打包后给售后人员部署到现场,售后可能不懂编程语法,所以需要将可动态改写的配置写到配置文件中,这里就写在yml配置文件下。

法一:
  • 在public下新建serverConfig.yml文件,并填写需要日后动态更改配置的内容
# 系统整体配置

# 是否打开日志
log: true

# 当前环境
model: dev

#开发环境
dev:
  baseUrl: 'http://baidu.dev.com'

#测试环境
test:
  baseUrl: 'http://baidu.test.com'

#线上环境
prod:
  baseUrl: 'http://baidu.prod.com'
  • 在公共入口文件main.js引入
import yaml from 'js-yaml';
import Vue from 'vue';
import router from '../router.js';
import http from '@/utils/http.js';
Vue.prototype.$http = http;

/**
 * async
 */
async function main () {
  new Vue({
    router,
    render: h => h(App)
  }).$mount('#app');
}

http.get('./serverConfig.yml').then(res => {
  var model = yaml.safeLoad(res).model;
  Vue.prototype.$serverConfig = yaml.safeLoad(res)[model];
  // 关闭log
  if (!yaml.safeLoad(res).log) {
    console.log = function () {
      return false;
    };
  }
  main();
});

打印出来的yml文件会以json格式输出

法二:

也可将yml文件存到vuex中


vue公共文件提取,打包后修改无需重新打包_第2张图片
image.png

vue公共文件提取,打包后修改无需重新打包_第3张图片
image.png

你可能感兴趣的:(vue公共文件提取,打包后修改无需重新打包)