Vue-cli3 通过配置 public 目录下的 config.js 和config.json 实现一次编译,修改生效

1.背景

最近实施部门,有个需求就是研发人员通过vue 写完代码,yarn build 编译完成代码后,移交实施,通过修改public 文件夹下的 config 文件来实现修改,请求后台的 requestUrl 和 titile 的功能。由于在代码里配置后,yarn build 后会压缩js 导致,修改配置不方便。故经过我长期的研究总结出了一套可以完美从开发环境迁移到nginx 部署的方案。在此分享给有需要的小伙伴,一起共勉!!!

2.配置步骤

  1. public 文件夹下新增两个配置文件:config.js 和config.json
    在这里插入图片描述

config.js

export const globalConfig = {
  // 请求后台路径
  requestUrl: '/api'
}

config.json

{
  "logoTitle": "标题",
  "energyWarningShowFlag": false
}

index.html 页面里引入 这两个配置文件

<script  src="<%= BASE_URL %>config.js"></script>
<script  src="<%= BASE_URL %>config.json"></script>

完整的 html 页面:

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!--常见的头缺失或不安全问题:
    1、“Content-Security-Policy”头缺失或不安全
    2、“X-Content-Type-Options”头缺失或不安全
    3、“X-XSS-Protection”头缺失或不安全
    4、设置HTTP请求头(X-Frame-Options)-->
   <!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self'"/>
    <meta http-equiv="X-Content-Type-Options" content="nosniff" />
    <meta http-equiv="X-XSS-Protection" content="1; mode=block" />
    <meta http-equiv="X-Frame-Options" content="SAMEORIGIN">-->

    <link rel="icon" href="<%= BASE_URL %>img/logo.png">
    <title></title>
<!--    <title><%=htmlWebpackPlugin.options.title %></title>-->
    <!--<style>#preloadingAnimation{position:fixed;left:0;top:0;height:100%;width:100%;background:#ffffff;user-select:none;z-index: 9999;overflow: hidden}.lds-roller{display:inline-block;position:relative;left:50%;top:50%;transform:translate(-50%,-50%);width:64px;height:64px;}.lds-roller div{animation:lds-roller 1.2s cubic-bezier(0.5,0,0.5,1) infinite;transform-origin:32px 32px;}.lds-roller div:after{content:" ";display:block;position:absolute;width:6px;height:6px;border-radius:50%;background:#13c2c2;margin:-3px 0 0 -3px;}.lds-roller div:nth-child(1){animation-delay:-0.036s;}.lds-roller div:nth-child(1):after{top:50px;left:50px;}.lds-roller div:nth-child(2){animation-delay:-0.072s;}.lds-roller div:nth-child(2):after{top:54px;left:45px;}.lds-roller div:nth-child(3){animation-delay:-0.108s;}.lds-roller div:nth-child(3):after{top:57px;left:39px;}.lds-roller div:nth-child(4){animation-delay:-0.144s;}.lds-roller div:nth-child(4):after{top:58px;left:32px;}.lds-roller div:nth-child(5){animation-delay:-0.18s;}.lds-roller div:nth-child(5):after{top:57px;left:25px;}.lds-roller div:nth-child(6){animation-delay:-0.216s;}.lds-roller div:nth-child(6):after{top:54px;left:19px;}.lds-roller div:nth-child(7){animation-delay:-0.252s;}.lds-roller div:nth-child(7):after{top:50px;left:14px;}.lds-roller div:nth-child(8){animation-delay:-0.288s;}.lds-roller div:nth-child(8):after{top:45px;left:10px;}#preloadingAnimation .load-tips{color: #13c2c2;font-size:2rem;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);margin-top:80px;text-align:center;width:400px;height:64px;}  @keyframes lds-roller{0%{transform:rotate(0deg);} 100%{transform:rotate(360deg);}}</style>-->
    <script src="<%= BASE_URL %>js/moment.min.js"></script>
    <script src="<%= BASE_URL %>js/vue.js"></script>

    <script src="<%= BASE_URL %>js/antd.min.js"></script>

    <link rel="stylesheet" href="<%= BASE_URL %>css/antd.min.css">
    <!--<style>-->
      <!--.ant-menu-dark .ant-menu-inline.ant-menu-sub{background:#123092;-webkit-box-shadow:0 2px 8px rgba(0,0,0,.45) inset;box-shadow:inset 0 2px 8px rgba(0,0,0,.45)}-->
      <!--.ant-menu-submenu-popup.ant-menu-dark .ant-menu-item-selected,.ant-menu.ant-menu-dark .ant-menu-item-selected{background-color:#081a59}-->
      <!--.ant-menu-dark,.ant-menu-dark .ant-menu-sub{color:hsla(0,0%,100%,.65);background:#123092}-->
    <!--</style>-->
  </head>
  <body>
    <noscript>
      <strong>因为未启用 JavaScript,所以本项目无法正常工作。请启用 JavaScript!</strong>
    </noscript>
    <div id="app">
      <div id="preloadingAnimation"><div class=lds-roller><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div><div class=load-tips>Loading</div></div>
    </div>
    <!-- built files will be auto injected -->
    <script  src="<%= BASE_URL %>config.js"></script>
    <script  src="<%= BASE_URL %>config.json"></script>

  </body>
</html>

  1. main.js 里新增 getServerConfig 方法
import axios from 'axios'

function getServerConfig () {
  return new Promise ((resolve, reject) => {
    axios.get('../config.json').then(response => {
      console.log("读取外部化配置文件>>>>>>>>")
      let data = response.data
      console.log(data)  // 是否成功读取需要的配置项
      for (let key in data) {
        Vue.prototype["$"+key] = data[key];
        console.log("设置 $"+key +"  "+data[key])
      }
      console.log(Vue.prototype.$logoTitle)  // 验证是否已经把属性挂载在了Vue的原型上
      resolve();
    }).catch(error => {
      console.log(error);
      reject()
    })
  })
}
async function init(){
  await getServerConfig();
}

new Vue({
  router,
  store,
  created () {
    bootstrap();
    init();
  },
  render: h => h(App)
}).$mount('#app')

PS: Vue.prototype 表示将变量挂载到Vue 实例上,可以从页面调用。 config.js 里面的 变量可以从js 代码里调用;config.json 里可以从Vue 页面通过this.$var 的方式调用。

  1. 在Vue 页面里调用
<div class="header">
  <a href="/">
      <span class="title">{{ this.$logoTitle }}</span>
 </a>
</div>
  1. js 里面调用
import { globalConfig } from '../../public/config'
const baseUrl = process.env.NODE_ENV === 'production' ? globalConfig.requestUrl : process.env.VUE_APP_BASE_API
  1. 修改html 页面里的title
    router.beforeEache 里面 添加 document.title = Vue.prototype.$logoTitle 更改title 标题
router.beforeEach((to, from, next) => {
  document.title = Vue.prototype.$logoTitle
  NProgress.start() // start progress bar
  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (to.path === '/user/login') {
      next({ path: '/sys/menu' })
      NProgress.done()
    } else {
      if (!store.getters.nickname) {
        store
          .dispatch('GetInfo')
          .then(res => {
            // 新增服务器返回的菜单路由
            addRoutes(res.menus)
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if (to.path === redirect) {
              // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: redirect })
            }
       
          })
          .catch((e) => {
            // Vue.prototype.$notification.error({
            //   message: '错误',
            //   description: '请求用户信息失败,请重试'
            // })
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单,直接进入
      next()
    } else {
      next({ path: '/user/login', query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

3.小结

  1. Vue.prototype 表示将变量挂载到Vue 实例上,可以从页面调用。
  2. config.js 里面的 变量可以从js 代码里调用;config.json 里可以从Vue 页面通过this.$var 的方式调用。
  3. 在router 里面 新增document.title = Vue.prototype.$logoTitle 更改title 标题
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: vue-cli3 中的 vue.config.js 文件用于配置项目的 webpack 构建环境。可以在该文件中进行如下配置: - 修改 webpack 的配置项 - 配置 devServer - 配置代理 - 使用插件 示例: ``` module.exports = { devServer: { port: 8080, proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true } } }, configureWebpack: { plugins: [ new MyAwesomeWebpackPlugin() ] } } ``` 其中,configureWebpack 配置项可以修改 webpack 的配置项,devServer 配置项可以配置开发服务器的相关选项,proxy 配置项可以配置代理。 注意:vue.config.js 文件不是必须的,如果项目中没有该文件,则使用默认配置。 ### 回答2: Vue CLI 3是Vue.js的一个脚手架工具,用于快速构建Vue项目。vue.config.js是一个配置文件,它在项目构建过程中被调用,用于配置Webpack和Vue CLI的一些选项。 vue.config.js配置文件中可以设置很多选项,包括开发时代理、打包时的压缩和代码分割等等。下面是一些常用的选项: 1. publicPath publicPath是一个字符串,用于指定打包后的静态资源的路径。可以是相对路径或绝对路径,它的值会被Webpack在生成代码时加入到各个静态资源引用的URL中。 2. outputDir outputDir是一个字符串,用于指定打包后的输出目录。默认值是"dist"。 3. devServer devServer是一个对象,用于配置开发服务器。其中包括代理、端口号和自动打开浏览器等选项。可以用它来配置前后端联调、Mock服务等。 4. chainWebpack chainWebpack是一个函数,用于修改Webpack的配置。可以在其中添加、删除、修改各种Webpack配置项。举个例子,我们可以通过chainWebpack来关闭ESLint验证: ``` chainWebpack: config => { config.module .rule('eslint') .use('eslint-loader') .tap(options => { options.emitWarning = false return options }) } ``` 5. configureWebpack configureWebpack是一个对象或函数,用于向Webpack配置中添加内容。其中包括Entry和Output等选项。 6. optimization optimization是一个对象,用于配置打包时的优化选项,比如代码压缩等。 7. css css是一个对象,用于配置CSS的选项。其中包括分离CSS、压缩CSS、CSS的sourceMap等。 8. pluginOptions pluginOptions是一个对象,用于配置Vue CLI插件的选项。其中包括ESLint、Stylelint、PWA等。我们可以通过它来关闭ESLint验证: ``` pluginOptions: { eslint: { enable: false } } ``` 除了上面提到的常用选项,vue.config.js中还有很多其他配置项可供选择,具体可参考Vue CLI的官方文档。总的来说,vue.config.js是一个非常强大的工具,可以大大提高开发效率和优化打包结果。 ### 回答3: Vue.js是目前非常流行的前端框架之一,它的灵活性和易用性受到了广大开发者的欢迎。其最新的版本Vue-cli3,提供了更加方便快捷的开发模式,同时其强大的配置功能也是特别值得注意的。Vue-cli3中的vue.config.js文件包含着许多重要的配置选项,下面我们来逐一介绍一下。 1. publicPath publicPath选项可以指定发布路径,通过配置publicPath选项,可以将Vue应用的资源文件发布到指定的位置,这样就方便我们在多个环境中部署Vue应用。例如,如果希望将Vue应用文件发布到“/my-app/”目录下,配置publicPath选项为“/my-app/”即可。 2. outputDir outputDir选项用于指定Vue应用的输出目录,通过配置outputDir选项,可以将Vue应用打包生成的文件输出到指定的目录下面。例如,如果希望将生成的文件输出到“/dist/”目录下,那么可以在vue.config.js文件中配置outputDir选项为“dist”。 3. devServer devServer选项用于配置开发服务器,对于Vue应用的开发来说,它非常重要。通过配置devServer选项,可以定制开发服务器的端口、代理等信息,使我们在开发Vue应用时能够更加方便地进行调试和测试。 4. lintOnSave lintOnSave选项用于在保存代码时自动检查语法错误和格式错误,让我们在开发过程中能够更加精细地把控代码质量。通过配置该选项,可以将Vue应用的代码自动规范,并保持统一的风格。 5. chainWebpack chainWebpack选项用于定制Webpack的配置,它可以让我们更加灵活地定制Vue应用的构建过程。通过配置该选项,可以添加自定义的Webpack插件,优化打包生成的文件等。 总之,Vue-cli3中的vue.config.js文件不仅提供了强大的配置功能,而且能够让我们更加方便地开发和部署Vue应用。掌握这些配置选项,能够让我们更加高效地进行Vue应用的开发和维护工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值