V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
deathscythe
V2EX  ›  JavaScript

如何很好地写路径配置

  •  
  •   deathscythe · 2018-01-24 17:40:56 +08:00 · 3009 次点击
    这是一个创建于 2255 天前的主题,其中的信息可能已经有所发展或是发生改变。
    本人有个项目,项目里面的 config.js 文件是管理一些常量"地址头"的,
    比如
    生产环境就
    API_URL = 'http://api.prod.com'
    WEB_URL = 'http://prod.com'

    测试环境就
    API_URL = 'http://api.test.com'
    WEB_URL = 'http://test.com'

    现在我用的方法是判断 window.location.origin 来区分,
    但是如果不只有生产环境和测试环境,那么要写几个 else if,觉得不好看。
    大家有一些好的建议么?
    8 条回复    2018-01-25 16:11:12 +08:00
    SakuraKuma
        1
    SakuraKuma  
       2018-01-24 18:01:53 +08:00
    拍平 if,可以用 object,然后用变量咯。
    deathscythe
        2
    deathscythe  
    OP
       2018-01-24 20:51:30 +08:00
    @SakuraKuma object 有想过,是不是做个循环,然后写个方法来改变这些变量?
    polun
        3
    polun  
       2018-01-24 23:00:44 +08:00
    scriptB0y
        4
    scriptB0y  
       2018-01-24 23:18:22 +08:00
    SakuraKuma
        5
    SakuraKuma  
       2018-01-25 09:21:42 +08:00
    @deathscythe #2 你的楼下已经告诉了你原理了,就是根据 env 直接读,不用循环呀
    ```js
    const
    API_MAP = {
    DEV: {
    // api here
    },
    PRODUCTION: {
    // api here
    },
    // etc...
    };
    ```
    deathscythe
        6
    deathscythe  
    OP
       2018-01-25 16:07:35 +08:00
    @SakuraKuma
    @polun
    @scriptB0y

    😂 很好,看到提到 env 想到了,那么我把路径写在 webpack 配置上,根据 env 去生成。感谢各位。
    deathscythe
        7
    deathscythe  
    OP
       2018-01-25 16:08:15 +08:00
    @SakuraKuma
    @polun
    @scriptB0y

    😂 很好,看到提到 ‘ env ’ 想到了,那么我把路径写在 webpack 配置上,根据去生成。感谢各位。
    deathscythe
        8
    deathscythe  
    OP
       2018-01-25 16:11:12 +08:00
    what ?提示我重复发相同内容我以为我没发成功
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5395 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 08:58 · PVG 16:58 · LAX 01:58 · JFK 04:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.