【问题标题】:Is it possible to judge npm script in a JavaScript file in vue.js?是否可以在 vue.js 的 JavaScript 文件中判断 npm 脚本?
【发布时间】:2020-09-18 12:24:09
【问题描述】:

我的 vue.js + webpack + npm 项目中有一个配置文件

/plugins/http/GLOBAL_CONST.js

const GLOBAL_CONST = {}


GLOBAL_CONST.BASE_URL = "http://www.example.com/"  // "http://localhost:3000/"  

GLOBAL_CONST.BASE_API = "http://www.example:8000/"  //  "http://localhost:8000/"  

export default GLOBAL_CONST

我有一个要求,如果我运行npm run dev,则

GLOBAL_CONST.BASE_URL = "http://localhost:3000/"
GLOBAL_CONST.BASE_API = "http://localhost:8000/"

如果我运行 npm run build 它使用:

GLOBAL_CONST.BASE_URL = "http://www.example.com/"  
GLOBAL_CONST.BASE_API = "http://www.example:8000/"  

有可能实现吗?

【问题讨论】:

    标签: vue.js npm webpack


    【解决方案1】:

    这通常使用if (process.env.NODE_ENV === 'production') 完成(等于true 用于npm run build),因此您可以在设置BASE_URL 时使用该条件:

    GLOBAL_CONST.BASE_URL = (process.env.NODE_ENV === 'production')
                          ? "http://www.example.com/"
                          : "http://localhost:3000/"
    

    如果使用 Vue CLI,在构建过程中,NODE_ENV 环境变量是 automatically set。否则,您可以在构建脚本中set it自己:

    // package.json
    {
      "scripts": {
        "build": "NODE_ENV=production node build.js",
        "dev": "NODE_ENV=development webpack-dev-server [...]"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多