saber 酱的抱枕

Fly me to the moon

05/26
2020
软件

VUE-CLI 的 process.env.BASE_URL

在 VUE_CLI 项目中配置路由时,例如有如下代码:

export default new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      name: 'index',
      path: '/',
      component: Index
    }
  ]
})

base: process.env.BASE_URL 这个参数令我疑惑,花了点时间才搞清楚。

默认情况下,这个 BASE_URL 并不需要特意配置。它默认会是空字符串 '',等于没有实际作用。

如果要配置 BASE_URL,需要在项目根目录创建 vue.config.js 文件,在里面设置 publicPath

module.exports = {
  publicPath: 'test/'
}

其实 BASE_URL 就是这里的 publicPath 的值。

注意:
如果设置了 BASE_URL,那么本地开发时,打开的默认地址 http://localhost:8080/ 后面要加上设置的路径,如 http://localhost:8080/test/,否则会出现错误。这个地方官方文档没提,我本以为本地开发时不用改的,栽了个头。

参考文档:
https://cli.vuejs.org/zh/guide/mode-and-env.html
https://cli.vuejs.org/zh/config/#%E5%85%A8%E5%B1%80-cli-%E9%85%8D%E7%BD%AE

VUE-CLI 的 process.env.BASE_URL