I am having issues importing a JSON file depending on a process.env.WORLD value in my React Typescript app. This is done in a .tsx file defining a React Context, and no React components are used here.
The JSON file can be loaded without problems when we ignore the process.env variable.
import data from '../main.json';
- TS file loading the JSON file:
src/contexts/world.tsx - JSON file:
src/main.json
In my first attempt, I tried
let file;
if (process.env.WORLD == 'main') {
file = '../main.json';
} else {
file = '../test.json';
}
import data from file;
but got the error
Import in body of module; reorder to top import/first
Tried using dynamic import
const data = await import(
process.env.WORLD == 'main'
? '../main.json'
: '../test.json'
);
but my setup does not allow a top-level await
Module parse failed: Cannot use keyword 'await' outside an async function
Tried using require instead of import
let file;
if (process.env.WORLD === 'main') {
file = '../main.json';
} else {
file = '../test.json';
}
const data = require(file);
but it almost works except that the file cannot be found
contexts sync:2 Uncaught Error: Cannot find module '../main.json'
Strangely, there is no problem using the same file path with import as shown in the first example in this question.
Typescript target is ES2018, and React 18 is used.
Why is the file not found when using require, and how can we solve this problem?
Could importing both files then choose the right file be a fit for you ?
or use
react.lazy: