I have JSON file that I want to access via the import statement. I don't want to expose the name directly in the code but read the name from the .env file and import it.
Here is a snippet of my code that works from directly importing the file. How can I change it so that I can read the file name from .env and import the actual file
import keys from 'home/path/account.json';
class SecurityServices {
getToken(){
return keys.certs;
}
}
basically I have the env file with the path and I was import it in my typescript code.
.env { "keyFile":"home/path/account.json'" }
Thanks
CodePudding user response:
I'd use something like https://www.npmjs.com/package/properties-reader
Load the properties from a file using that. Put it in an object, import that object file and use the property. For example
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')
}
then
const prop = properties.get(name);
CodePudding user response:
If you just want to replace a bit of text at build time, bundlers like rollup are the tool for you. For example:
// 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 })
You should be able to accomplish something similar with webpack, gulp, and most other modern bundlers.
Alternatively (and my preference), consider doing a dynamic import. Note that this requires using Promises
adding an async factor to your code:
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>
}
With this approach, you reduce the initial build size at the cost of needing to work with the JSON asynchronously.