我正在构建一个 Chrome 打包的应用程序。我想把配置文件放在资源目录中,然后在启动时通过 JavaScript 读取。
例如:
- 项目
- WebContent
- index.html
- manifest.json
- main.js
- resource
- config.properties
- WebContent
在这里,我希望 main.js 在开始时加载 config.properties 文件并获取键值对。
有人做过类似的事情吗?
我正在构建一个 Chrome 打包的应用程序。我想把配置文件放在资源目录中,然后在启动时通过 JavaScript 读取。
例如:
在这里,我希望 main.js 在开始时加载 config.properties 文件并获取键值对。
有人做过类似的事情吗?
有一种超级简单的方法可以做到这一点,与sowbug的答案类似,但不需要任何XHR或文件阅读。
第1步。创建resource/config.js如下:
gOptions = {
// This can have nested stuff, arrays, etc.
color: 'red',
size: 'big',
enabled: true,
count: 5
}
步骤2. 将此文件包含在您的index.html中:
<!doctype html>
<head>
<script src="resource/config.js"></script>
...
步骤3. 从您的main.js(或任何地方)直接访问您的选项:
...
if (gOptions.enabled) {
for (var i = 0; i < gOptions.count; i++) {
console.log(gOptions.color);
}
}
...
<script src="messageResource.min.js"></script>
2) 您可以使用以下代码从main.js获取config.properties的键值对。
// initialize messageResource.js
messageResource.init({
// path to directory containing config.properties
filePath : 'resource'
});
// load config.properties file
messageResource.load('config', function(){
// load file callback
// get value corresponding to a key from config.properties
var value = messageResource.get('key', 'config');
});
key
的值写成另一个值,但获取到的却是key
的值而非我所写的值? - sarwar026messageResource.load('config', function(){
// 加载文件回调
});
- Khanimport URL from 'URL';
对于包含点的键(如widgetAPI.dev),语法可能有些棘手。您不能像URL.widgetAPI.dev那样简单地调用它。由于属性文件(内容)一旦到达JavaScript就变成了一个对象,因此您可以像引用任何对象键一样引用它:
console.log(URL['widgetAPI.dev'])
如果你不使用ES6,jQuery有一些库可以使用,另外还有一个普遍存在的messageResource。
使用npm安装dotenv模块
let port = "8080";
//region read from local.properties
const result = require("dotenv").config({path: "local.properties"});
if (!result.error && !!result.parsed) port = result.parsed.port;
//endregion
local.properties
port=9000
const properties = dotenv.parse(fileContent)
,其中fileContent
是文件内容的字符串表示形式。就那么简单。 - Andreas Dolk将文件结构化为JSON格式。使用File API或XHR将其读入字符串中,然后使用JSON.parse(string)。
使用JSF非常简单,但每次需要从JavaScript读取新参数时,您都必须修改HTML文件。 我的属性文件(config.properties)在项目目录中具有以下参数作为键值对。
parameter.key=parameter.value
属性文件名在faces-config.xml中配置。
<application>
<resource-bundle>
<base-name>com.example.project.properties.config</base-name>
<var>configuration</var>
</resource-bundle>
</application>
<h:inputHidden id="parameter_key" value="#{configuration['parameter.key']}" />
而从 JavaScript 函数中,使用以下代码行来读取参数值。
var parameter_value = document.getElementById("parameter_key").value;
祝你有美好的一天..!!!