简体   繁体   English

在Javascript中切换开发/测试/生产变量

[英]Switching Development/Test/Production variables in Javascript

I am trying to search the best approach to manage different values for same variables in Devlopment, Test and Production environment. 我正在尝试搜索最佳方法来管理Devlopment,Test和Production环境中相同变量的不同值。
For example, I have variable jsonFile which can be: 例如,我有变量jsonFile ,它可以是:

var jsonFile = http://localhost:63342/json/appsconfig.json

for development env 发展环境

var jsonFile = http://192.168.35.59/applications/json/appsconfig.json

for test env 用于测试环境

var jsonFile = http://example.com/applications/json/appsconfig.json

for production env 用于生产环境

I am trying to read a lot about Frontend Development Stack, but I am confused about what tool to use. 我试图阅读很多关于前端开发堆栈的内容,但我对使用什么工具感到困惑。 I will use Google Closure Tools for minification, can it be also useful to switch variable values? 我将使用Google Closure工具进行缩小,是否也可以切换变量值? Or can it be considered a Grunt task (even if I am not able to understand how to properly configure Grunt tasks...)? 或者它可以被认为是一个Grunt任务(即使我无法理解如何正确配置Grunt任务......)?

What might be better is to write the JSON into a JS file that is part of your build artifacts. 可能更好的是将JSON写入JS文件,该文件是构建工件的一部分。 Something like file-creator that can write a file like so (using a simplistic setup that can obviously be made more dynamic). 类似于文件创建者的东西,可以像这样写一个文件(使用简单的设置,显然可以使其更具动态性)。

In the top of your module.exports for grunt tasks, load in the config file into a var like: 在您的module.exports顶部用于grunt任务,将配置文件加载到var中:

var configData = grunt.file.readJSON('../config/appsconfig.json'),

Then write to a new JS file using the grunt file-creator module 然后使用grunt file-creator模块写入新的JS文件

"file-creator": {
    'dev': {
        'build/config.js': function (fs, fd, done) {
                fs.writeSync(fd, 
                    'var yourSiteHere = yourSiteHere || {}; yourSiteHere.config = '
                    + JSON.stringify(configData) + ";"
                );
                done();
        }
    }
}

Then load this JS file into the page (perhaps even minify it using a separate grunt task). 然后将此JS文件加载到页面中(甚至可能使用单独的grunt任务将其缩小)。 You will be then able to refer to the config data like so: 然后,您将能够像这样引用配置数据:

var apiEndPoint = yourSiteHere.config.api.apiEndPoint,
    apiKey = yourSiteHere.config.api.apiKey;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM