0

Can require be used in a typescript file in the web app to import a json file locally?

export function getData(id: string): string {
    const ids: string = id + 'something'; 
    const data = require(`./config/${ids}.json`);

    return JSON.stringify(data);
}
7
  • That depends entirely upon how you're building your web app from typescript source. I think we'll need some more information. Commented Jan 15, 2022 at 0:01
  • can you elaborate a bit on it? I am not sure on what parameters it depends or what are the more info you need me to include? Commented Jan 15, 2022 at 0:04
  • 1
    Most (all?) browsers don't run typescript. In order to use typescript in a web app, you must transpile it somehow. The process that you use to transpile influences whether this is possible. For example, if using webpack or esbuild or parcel this is probably pretty easy. If just using tsc then maybe less-so and you might need to look into a bundler. Commented Jan 15, 2022 at 0:05
  • Thank you, this is helpful. We use webpeck as a bundler. Is it possible with Webpack? will this work or I need to change or add something to webpack config? Commented Jan 15, 2022 at 0:06
  • Does this answer your question? Importing JSON file in TypeScript Also webpack docs say this just works out of the box. v4.webpack.js.org/loaders/json-loader Should just work I suppose? Commented Jan 15, 2022 at 0:07

1 Answer 1

3

If you want a JSON string from a file at a relative address in the same origin as your web app, you can use this function:

TS Playground

export async function getJsonById(id: string):Promise<string> {
  const url = `./output/config/${id}something.json`;
  const json = (await fetch(url)).text(); // this is a string (JSON is a string)
  return json;
  // alternatively: to parse the JSON into a native JS data type
  // return JSON.parse(json);
}

// use:
const json = await getJsonById('id');
Sign up to request clarification or add additional context in comments.

9 Comments

awesome, didn't know that. Thank you. yes it is in the same origin
it seems it has this issue? stackoverflow.com/questions/50007055/…
@AlreadyLost Is this a React project?
yes, it is a monorepo written mostly in react, the packages are used in a react app
Then the problem is not with your React app, but with the server. If the files aren't at the address, then it means that the server isn't serving them at that address. You'll have to determine the address at which the JSON files are being served.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.