简体   繁体   English

如何为JavaScript参数使用外部值?

[英]How do I use an external value for JavaScript parameters?

Suppose I've got a bunch of JavaScript files that build funcs something like: 假设我有一堆JavaScript文件,这些文件可以构建如下功能:

me.add ([
panel1: [{
   url: 'https://localhost:8888/MyProj-0.0.1/resources/html/dir1/page1.html'
   }, {
   url: 'https://localhost:8888/MyProj-0.0.1/resources/html/dir2/page5.html'
   }]);

How can I use a property file to manage the front parts of all of these refs? 如何使用属性文件来管理所有这些引用的前部? ie, I'd like to change all 60+ of my JavaScript files that have functions like the above to be something like: 即,我想将具有上述功能的所有60多个JavaScript文件更改为:

me.add ([
panel1: [{
   url: '($MagicGoesHere)/resources/html/dir1/page1.html'
   }, {
   url: '($MagicGoesHere)/resources/html/dir2/page5.html'
   }]);

so that I can read in a single property from a file in my project that defines the MagicGoesHere root for all of these references. 这样我就可以从项目的文件中读取单个属性,该文件为所有这些引用定义了MagicGoesHere根目录。

Note, I only want to do this as part of building my project; 注意,我只想在构建项目的过程中这样做; I do not need to read in a property and expose is on the webserver. 我不需要读取属性并在Web服务器上公开。 (ie, when I deploy the WAR that gets built, all of the refs will have been expanded during the build) (即,当我部署要构建的WAR时,所有引用都将在构建期间进行扩展)

My goal is to make it easy to update the refs when releasing MyProj-0.0.2 我的目标是在发布MyProj-0.0.2时使其易于更新引用

TIA, TIA,

You can easily just use a constants file. 您可以轻松地使用常量文件。

my-constants.js my-constants.js

const myConstants = {
    baseUrl: 'http://localhost:8888/MyProj-0.0.1/'
};
module.exports = myConstants;

my-app.js my-app.js

const myConstants = require('./my-constants');

me.add([
    {
        panel1: [
            { url : myConstants.baseUrl + 'resources/html/dir1/page1.html' }
        ]
    }
])

The above does not satisfy this constraint you placed upon the problem: 上面的方法不能满足您对问题施加的约束:

Note, I only want to do this as part of building my project; 注意,我只想在构建项目的过程中这样做; I do not need to read in a property and expose is on the webserver. 我不需要读取属性并在Web服务器上公开。 (ie, when I deploy the WAR that gets built, all of the refs will have been expanded during the build) (即,当我部署要构建的WAR时,所有引用都将在构建期间进行扩展)

However, I think it is worth asking if that is really necessary. 但是,我认为值得一问,是否真的有必要。 There is no cost to the constants file. 常量文件没有任何花费。 The amount of complexity you bring in with replacing source code during a build is non-trivial and it introduces new kinds of security concerns. 在构建期间替换源代码带来的复杂性是不平凡的,并且引入了新的安全性问题。

If you really want to do this as a build step, my favorite tool for the job is rollup-plugin-replace . 如果您真的想在构建步骤中执行此操作,那么我最喜欢的工作工具是rollup-plugin-replace It includes a few features you will probably want, like delimiters , without any cruft. 它包括一些您可能想要的功能,例如delimiters ,没有任何多余的内容。

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

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