I have a file called men.json. I want to do the equivalent of var men = require('./men.json');
Whatever I have tried, it is looking for a ./men.json.js file. I read that I can not use import since it is not a .ts file
What is the equivalent of the require line?
Thanks to TypeScript 2.x Wildcard Module Declarations you can do the following:
Somewhere in a *.d.ts file add this (or check if its already there):
declare module "*.json"
{ const value: any;
export default value;
}
declare module "json!*"
{ const value: any;
export default value;
}
Then you can do things like this in your TypeScript code:
import * as data1 from './data/some.json';
import data2 from "json!foo.com/data_returns_json";
Note: I think this is already part of the ES6/ES2015 standard if you're writing plain JS targeting ES6/ES2015.
You can import only .ts or .tsx file using typescript imports
This can be done in two ways: a)if you want to import JSON you may have to use "require"
b) Copy the json and assign the JSON to a varaible and store it in a .ts file . In this case the variable will hold the json object . You can now import this .ts file using typescript type of imports and start using the object
Sai Kishore Komanduri
Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art
Sai Kishore Komanduri
Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art
requireis meant for loading your modules; the recommended way to load files (including the JSON ones) is through Node's filesystem module.You could do something like this:
// Declare your variables var fs = require('fs'); var menObject; // Read the file, and pass it to your callback fs.readFile('./men.json, handleJSONFile); // Handle the data var handleJSONFile = function (err, data) { if (err) { throw err; } menObject = JSON.parse(data); }