繁体   English   中英

在typescript导入一个JSON文件

[英]Import a JSON file in typescript

我有 JSON 文件,我想通过导入语句访问它。 我不想直接在代码中公开名称,而是从 .env 文件中读取名称并将其导入。

这是我的代码片段,可以直接导入文件。 如何更改它以便我可以从 .env 读取文件名并导入实际文件

import keys from 'home/path/account.json';
class SecurityServices {
   getToken(){
     return keys.certs;
   }
}

基本上我有带路径的 env 文件,我将它导入我的 typescript 代码中。

.env { "keyFile":"home/path/account.json'" }

谢谢

我会使用类似https://www.npmjs.com/package/properties-reader

使用它从文件加载属性。 将其放入 object,导入该 object 文件并使用该属性。 例如

let PropertiesReader = require('properties-reader');
let properties = null;
try {
    debugLog('Looking for ' + os.homedir() + '/app.properties')
    properties = PropertiesReader(os.homedir() + '/app.properties');
    debugLog('Found ' + os.homedir() + '/app.properties')
} catch(e) {
    debugLog(os.homedir() + '/app.properties' + ' not found.  Using default properties')
}

然后

const prop = properties.get(name);

如果你只想在构建时替换一些文本,像 rollup 这样的打包器是适合你的工具。 例如:

// file.ts
import keys from 'home/path/account.json';

// rollup.config.js
import replace from '@rollup/plugin-replace';

export default {
  client: {
    plugins: [
      replace({ 'home/path/account.json': process.env.keyFile })

您应该能够使用 webpack、gulp 和大多数其他现代捆绑器完成类似的事情。

或者(和我的偏好),考虑做一个动态导入 请注意,这需要使用Promises向您的代码添加异步因素:

let _loadedJson: any = null;

export async function getJsonFromFile() {
  if (_loadedJson === null) {
    // This dynamic import will happen one time, when this is first called.
    _loadedJson = await import(process.env.keyFile);
  }
  // Optionally assert a type at return since dynamic imports resolve to `any`.
  return _loadedJson as Record<string, any>
}

使用这种方法,您可以以需要异步处理 JSON 为代价来减小初始构建大小。

暂无
暂无

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

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