I have a JSON file that looks like following:
{
"primaryBright": "#2DC6FB",
"primaryMain": "#05B4F0",
"primaryDarker": "#04A1D7",
"primaryDarkest": "#048FBE",
"secondaryBright": "#4CD2C0",
"secondaryMain": "#00BFA5",
"secondaryDarker": "#009884",
"secondaryDarkest": "#007F6E",
"tertiaryMain": "#FA555A",
"tertiaryDarker": "#F93C42",
"tertiaryDarkest": "#F9232A",
"darkGrey": "#333333",
"lightGrey": "#777777"
}
I'm trying to import it into a .tsx file. For this I added this to the type definition:
declare module "*.json" {
const value: any;
export default value;
}
And I'm importing it like this.
import colors = require('../colors.json')
And in the file, I use the color primaryMain as colors.primaryMain. However I get an error:
Property 'primaryMain' does not exist on type 'typeof "*.json"
With TypeScript 2.9.+ you can simply import JSON files with benefits like typesafety and intellisense by doing this:
import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);
Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):
"resolveJsonModule": true,
"esModuleInterop": true,
Side notes:
Typescript 2.9.0 has a bug with this JSON feature, it was fixed with 2.9.2
The esModuleInterop is only necessary for the default import of the colorsJson. If you leave it set to false then you have to import it with import * as colorsJson from '../colors.json'
The import form and the module declaration need to agree about the shape of the module, about what it exports.
When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)
declare module "*.json" {
const value: any;
export default value;
}
You are stating that all modules that have a specifier ending in .json have a single export named default.
There are several ways you can correctly consume such a module including
import a from "a.json";
a.primaryMain
and
import * as a from "a.json";
a.default.primaryMain
and
import {default as a} from "a.json";
a.primaryMain
and
import a = require("a.json");
a.default.primaryMain
The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default exports.
However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require gives you an object representing the module itself and not its exported bindings.
So why the error? Because you wrote
import a = require("a.json");
a.primaryMain
And yet there is no export named primaryMain declared by your "*.json".
All of this assumes that your module loader is providing the JSON as the default export as suggested by your original declaration.
Note: Since TypeScript 2.9, you can use the --resolveJsonModule compiler flag to have TypeScript analyze imported .json files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.
Here's how to import a json file at runtime
import fs from 'fs'
var dataArray = JSON.parse(fs.readFileSync('data.json', 'utf-8'))
This way you avoid issues with tsc slowing down or running out of memory when importing large files, which can happen when using resolveJsonModule.
It's easy to use typescript version 2.9+. So you can easily import JSON files as #kentor decribed.
But if you need to use older versions:
You can access JSON files in more TypeScript way. First, make sure your new typings.d.ts location is the same as with the include property in your tsconfig.json file.
If you don't have an include property in your tsconfig.json file. Then your folder structure should be like that:
- app.ts
+ node_modules/
- package.json
- tsconfig.json
- typings.d.ts
But if you have an include property in your tsconfig.json:
{
"compilerOptions": {
},
"exclude" : [
"node_modules",
"**/*spec.ts"
], "include" : [
"src/**/*"
]
}
Then your typings.d.ts should be in the src directory as described in include property
+ node_modules/
- package.json
- tsconfig.json
- src/
- app.ts
- typings.d.ts
As In many of the response, You can define a global declaration for all your JSON files.
declare module '*.json' {
const value: any;
export default value;
}
but I prefer a more typed version of this. For instance, let's say you have configuration file config.json like that:
{
"address": "127.0.0.1",
"port" : 8080
}
Then we can declare a specific type for it:
declare module 'config.json' {
export const address: string;
export const port: number;
}
It's easy to import in your typescript files:
import * as Config from 'config.json';
export class SomeClass {
public someMethod: void {
console.log(Config.address);
console.log(Config.port);
}
}
But in compilation phase, you should copy JSON files to your dist folder manually. I just add a script property to my package.json configuration:
{
"name" : "some project",
"scripts": {
"build": "rm -rf dist && tsc && cp src/config.json dist/"
}
}
In my case I needed to change tsconfig.node.json:
{
"compilerOptions": {
...
"resolveJsonModule": true
},
"include": [..., "colors.json"]
}
And to import like that:
import * as colors from './colors.json'
Or like that:
import colors from './colors.json'
with "esModuleInterop": true
You should add
"resolveJsonModule": true
as part of compilerOptions to tsconfig.json.
Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.
Example #
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
// .ts
import settings from "./settings.json";
settings.debug === true; // OK
settings.dry === 2; // Error: Operator '===' cannot be applied boolean and number
// settings.json
{
"repo": "TypeScript",
"dry": false,
"debug": false
}
by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
Another way to go
const data: {[key: string]: any} = require('./data.json');
This was you still can define json type is you want and don't have to use wildcard.
For example, custom type json.
interface User {
firstName: string;
lastName: string;
birthday: Date;
}
const user: User = require('./user.json');
In an Angular (typescript) app, I needed to include a .json file in my environment.ts. To do so, I had to set two options in tsconfig:
{
"compilerOptions": {
"moduleResolution": "node",
"resolveJsonModule": true
}
}
Then, I could import my json file into the environment.ts:
import { default as someObjectName } from "../some-json-file.json";
You can import a JSON file without modifying tsconfig you tell explicitly that you are importing JSON
import mydata from './mydataonfile.json' assert { type: "json" };
I know this does not fully answer the question but many people come here to know how to load JSON directly from a file.
Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:
const config = require('./config.json');
Note that if you using #kentor ways
Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):
You need to add --resolveJsonModule and--esModuleInterop behind tsc command to compile your TypeScript file.
Example:
tsc --resolveJsonModule --esModuleInterop main.ts
require is a common way to load a JSON file in Node.js
in my case I had to change: "include": ["src"] to "include": ["."] in addition to "resolveJsonModule":true because I tried to import manifest.json from the root of the project and not from ./src
I am trying to load the version number of my Angular application from package.json because that is where the version number is located. When looking up how to do this, most people suggest using require to load the json file like:
var pckg = require('../../package.json');
console.log(pckg.version);
When I put this code in the constructor of a component, I get undefined.
Next I try putting the require statement above the component by the imports like:
const { version: appVersion } = require('../../package.json')
export class StackOverflowComponent {
public appVersion
constructor() {
this.appVersion = appVersion
}
}
and I get Error: (SystemJS) Unexpected token : when the require is trying to parse the json file. When I hover over require I see that it is of type "NodeRequire(id: string)". Is this different than requirejs?
I am using systemjs and I noticed a lot of people with answers are referring to Webpack. Here are relevant files that may help you answer my problem.
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"allowSyntheticDefaultImports": true,
"typeRoots": [
"./node_modules/#types/"
]
},
"compileOnSave": true,
"exclude": [
"node_modules/*",
"**/*-aot.ts"
]
}
devDependencies in package.json:
"devDependencies": {
"#types/node": "^6.0.46",
"concurrently": "^3.0.0",
"lite-server": "^2.3.0",
"rollup": "^0.50.0",
"rollup-plugin-commonjs": "^8.2.1",
"rollup-plugin-node-resolve": "^3.0.0",
"rollup-plugin-uglify": "^2.0.1",
"source-map-explorer": "^1.5.0",
"typescript": "~2.3.2"
},
The problem you've encountered is that SystemJS is trying to interpret a JSON file as if it were executable. In order to get SystemJS to load JSON files sensibly, you need to use a JSON loader like systemjs-plugin-json.
You need to make it available in your SystemJS configuration. For instance, I use:
SystemJS.config({
paths: {
// Set an abbreviation to avoid having to type /node_modules/ all the time.
"npm:": "/node_modules/",
// ....
},
map: {
// The loader is known to SystemJS under the name "json".
json: "npm:systemjs-plugin-json",
// ...
},
packageConfigPaths: [
// Tell SystemJS that it should check the package.json files
// when figuring out the entry point of packages. If you omit this, then
// the map above would have to be "npm:systemjs-plugin-json/json.js".
"npm:*/package.json",
// ...
],
});
Then you need to use it. You could replace your require call with require('../../package.json!json'); but I suspect that TypeScript would not be happy with this due to the funky module name. The !json part tells SystemJS to use the json loader. I never do this. Instead, I set a meta in my configuration that tells SystemJS, "use the json loader when you load this file":
SystemJS.config({
meta: {
"path/to/package.json": {
loader: "json",
},
},
});
You need to figure out path/to/package.json on the basis of the rest of your SystemJS configuration, baseUrl in particular.
If you add the following to your typings.d.ts :
declare module '*.json' {
const value: any;
export default value;
}
you can then do this:
import * as pkg from '../path-to-root/package.json';
and later refer to it like this, e.g. in you component's constructor:
console.log(`version: ${pkg['version']}`);
or, equivalently,
console.log(`version: ${(<any>pkg).version}`);
I have an ASP.NET core project and I'm getting this error when I try to build it:
error TS18003: Build:No inputs were found in config file 'Z:/Projects/client/ZV/src/ZV/Scripts/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["../wwwroot/app","node_modules/*"]'.
1> The command exited with code 1.
1> Done executing task "VsTsc" -- FAILED.
This is my tsconfig.json file:
{
"compileOnSave": true,
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es5", "dom" ],
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
"outDir": "../wwwroot/app/",
"removeComments": false,
"sourceMap": true,
"target": "es6"
},
"exclude": [
"../wwwroot/app",
"node_modules/*"
]
}
Is this a bug or am I doing something wrong? I did recently upgrade Visual Studio 2015 to update 3. Has anyone encountered this before?
Add an empty typescript file to the typescript scripts folder (the location of your tsconfig file) to satisfy the typescript compiler.
You can also try to restart your code editor. That works well too.
This can occur because typescript server can't find any files described by the include array:
// tsconfig.json
{
//...
"include": [
"./src/"
],
}
If you're using VSCode, you can restart your TS server within your editor super easily to prompt it to re-evaluate the file like this:
Navigate to any .ts or .tsx file
Open the command palette (CMD + SHIFT + P on mac)
Run the TypeScript: Restart TS server command:
I'm not using TypeScript in this project at all so it's quite frustrating having to deal with this. I fixed this by adding a tsconfig.json and an empty file.ts file to the project root. The tsconfig.json contains this:
{
"compilerOptions": {
"allowJs": false,
"noEmit": true // Do not compile the JS (or TS) files in this project on build
},
"compileOnSave": false,
"exclude": [ "src", "wwwroot" ],
"include": [ "file.ts" ]
}
If you are using the vs code for editing then try restarting the editor.This scenario fixed my issue.I think it's the issue with editor cache.
I have all of my .ts files inside a src folder that is a sibling of my tsconfig.json. I was getting this error when my include looked like this (it was working before, some dependency upgrade caused the error showing up):
"include": [
"src/**/*"
],
changing it to this fixed the problem for me:
"include": [
"**/*"
],
In modern typescript config just set "allowJs" and no need to add any empty .ts file in include directories such as "src" (specified in include array)
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
...
},
"include": [
"src"
]
}
When you create the tsconfig.json file by tsc --init, then it comments the input and output file directory. So this is the root cause of the error.
To get around the problem, uncomment these two lines:
"outDir": "./",
"rootDir": "./",
Initially it would look like above after un-commenting.
But all my .ts scripts were inside src folder. So I have specified /src.
"outDir": "./scripts",
"rootDir": "./src",
Please note that you need to specify the location of your .ts scripts in rootDir.
I was getting this error:
No inputs were found in config file 'tsconfig.json'.
Specified include paths were '["**/*"]' and exclude paths '["**/*.spec.ts","app_/**/*.ts","**/*.d.ts","node_modules"]'.
I had a .tsconfig file, which read TS files from the ./src folder.
The issue here was that with the source folder not containing any .ts files and I was running tslint. I resolved issue by removing tslint task from my gulp file, as I don't have any .ts files to be compiled and linted.
Changing index.js to index.ts fixed this error for me. (I did not have any .ts files before this).
Note: remember to change anywhere you reference index.js to index.ts except of course, where you reference your main file. By convention this is probably in your lib or dist folders.
My tsconfig.json:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"inlineSourceMap": true,
"noImplicitAny": false
}
}
My outDir is ./dist so I reference my main in my package.json as "main": "dist/index.js"
"outDir"
Should be different from
"rootDir"
example
"outDir": "./dist",
"rootDir": "./src",
You need to have the root index.tsx or index.ts file for the tsc command to work.
I added the following in the root ( visual studio )
{
"compilerOptions": {
"allowJs": true,
"noEmit": true,
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"include": [
"**/*"
],
"exclude": [
"assets",
"node_modules",
"bower_components",
"jspm_packages"
],
"typeAcquisition": {
"enable": true
}
}
The solution that worked for me was to add a ./ before each include path in the config file:
"include": ["./src/**/*.d.ts", "./src/**/*.js", "./src/**/*.svelte"]
Ok, in 2021, with a <project>/src/index.ts file, the following worked for me:
If VS Code complains with No inputs were found in config file... then change the include to…
"include": ["./src/**/*.ts"]
Found the above as a comment of How to Write Node.js Applications in Typescript
When using Visual Studio Code, building the project (i.e. pressing Ctrl + Shift + B), moves your .ts file into the .vscode folder (I don't know why it does this), then generates the TS18003 error.
What I did was move my .ts file out of the .vscode folder, back into the root folder and build the project again.
The project built successfully!
add .ts file location in 'include' tag then compile work fine. ex.
"include": [
"wwwroot/**/*" ]
My VSCode was giving me the squiggly line at the beginning of my tsconfig.json file, and had the same error, so
I made sure I had at least one .ts file in the folder specified in the "include" paths (one of the folders in the include path was empty and it was fine)
I simply closed the VSCode and opened it back up, and that fixed it. (sigh..)
My folder structure
tsconfig.json
package.json
bar/
myfile.ts
lib/
(no file)
My tsconfig.json
"compilerOptions": { ... },
"include": [
"bar/**/*",
"lib/**/*"
],
"exclude": [
".webpack/**/*",
".vscode/**/*"
]
If you don't want TypeScript compilation, disable it in your .csproj file, according to this post.
Just add the following line to your .csproj file:
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
I had to add the files item to the tsconfig.json file, like so:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
},
"files": [
"../MyFile.ts"
]
}
More details here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
Btw, just had the same problem.
If you had my case, then you probably have the tsconfig.json not in the same directory as the .ts file.
(In my case I stupidly had next to launch.json and tasks.json inside the .vscode folder :P)
I had existing tsconfig files for 4 existing projects in my solution. After upgrading to vs2017 I experienced this problem. It was fixed by adding the (supposedly default) include and exclude sections to the files, as described by NicoJuicy.
For anyone experiencing the same error should try adding "node modules" to the exclude options
{
"compilerOptions": {
...
},
"include": [
"./src/**/*.ts"
],
"exclude": [
"./out.d.ts",
"node_modules",
]
}
If you are using VSCode, and you have several folders opened then you need to open the one folder you are working on for it to go away.
Wrong Opening of Folder
Right Opening of Folder
I have a tsconfig.json file that doesn't apply to any .ts files. It's in a separate folder. Instead I only use it as a base for other tsconfig files via "extends": "../Configs/tsconfig.json". As soon as I renamed the base config file to something else e.g. base-tsconfig.json (and updated the extends statements) the error went away and the extending still worked.
I got the same error and in my case it was because vscode couldn't recognize .ts file.
It was seeing it as text file and I had to rename it to remove one letter and add it back to make it work.
I ran into this issue constantly while packing my projects into nugets via Visual Studio 2019. After looking for a solution for ages I seem to have solved this by following advice in this article
MSBuild & Typescript
especially part about <TypeScriptCompile /> where I included all my .ts resources with the Include operator and excluded others such as node_modules with the Remove operator. I then deleted the tsconfig.json file in each offending project and the nuget packages were generated and no more errors
I received this same error when I made a backup copy of the node_modules folder in the same directory. I was in the process of trying to solve a different build error when this occurred. I hope this scenario helps someone. Remove the backup folder and the build will complete.
I had the same error because I had this:
"include": [
"wwwroot/ts/*.ts"
],
"exclude": [
"node_modules",
"wwwroot"
]
The error appear because the folder wwwroot appear in include and exclude, you should quit one of them.
Make sure all your files has a correct name.