I need to use mock json to test my front-end render.
import MOCK_FAQ from '../../mocks/FAQ.json';
When I try to import the file i got this exception:
Cannot find module '../../mocks/FAQ.json'. Consider using '--resolveJsonModule' to import module with '.json' extensionts(2732)
But I'm ready using this property on my tsconfig file:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": [
"dom",
"es6"
],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext"
},
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
Someone can helps? o/
It should work if you set "resolveJsonModule": true. and save tsconfig.json like:
import * as MOCK_FAQ from '../../mocks/FAQ.json';
Or you can try another way to import json file as below:
const MOCK_FAQ = require('../../mocks/FAQ.json');
Related
I want to import a JSON file which doesn't have a .json file extension. For example foo.myext:
{"something": "some data"}
I tried to declare the file type:
// declarations.d.ts
declare module "*.myext" {
const json: {something: string};
export default json;
}
In my tsconfig.json I have the following:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"typeRoots": ["./src/declarations.d.ts"]
},
"include": ["src"]
}
And inside code I import it as:
import foo from "./foo.myext";
console.log(foo.something);
This works at compile time, but at runtime it turns out that the imported value (foo) is actually a string that just contains the filename.
If I rename the file to use .json extension, importing works fine. But I'd really like to keep the original file extension.
Update
I tried overriding the WebPack config using react-app-rewired. Created the following config-overrides.js:
module.exports = function override(config, env) {
return {
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.myext$/,
use: [{ loader: "json-loader" }],
},
],
},
};
};
Also installed json-loader dependency.
But the problem stays the same - the file is still imported as just a filename string :(
When I run yarn build I see the JSON file being converted to JavaScript file in /build/static/media/foo.81ac3f28.myext:
module.exports = {"something": "some data"}
So the Webpack config sort of works... but not quite.
I have problem importing json files into typescript. I have configured tsconfig.json according to the convention, but it still does not work in the environment.ts file, however in the environment.prod.ts file, the import works perfectly
environment.ts
import { domain, clientId, audience, serverUrl } from '../../auth_config.json';
export const environment = {
production: false,
auth: {
domain,
clientId,
redirectUri: window.location.origin,
audience,
},
dev: {
serverUrl,
},
};
ERROR -->
Cannot find module '../../auth_config.json'. Consider using '--resolveJsonModule' to import module with '.json' extensionts(2732)
environment.prod.ts
import { domain, clientId, audience, serverUrl } from '../../auth_config.json';
export const environment = {
production: true,
auth: {
domain,
clientId,
redirectUri: window.location.origin,
audience,
},
dev: {
serverUrl,
},
};
Its work ok.
My tsconfig.json
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"strict": true,
"resolveJsonModule": true,
"esModuleInterop": true
},
}
I am several days, without finding why. Thank you.
Here you can see the error.
Now mark it in console, but not in the file.
Just faced a similar problem and found the solution on typescriptlang.org. You need to enable following option:
resolveJsonModule -
Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. This includes generating a type for the import based on the static JSON shape.
TypeScript does not support resolving JSON files by default.
So enabling this option in you tsconfig.json under compilerOptions should do the job:
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
],
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"strict": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"resolveJsonModule": true
},
}
Maybe you also need to enable allowSyntheticDefaultImports to avoid eslint errors.
I need to import this json file that it is in the assets filder.
{
"HOME": "home"
}
So I do in my component:
import config from "../../../assets/file/config.json";
But I obtain this error:
Cannot find module '../../..//config.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
So I modified my tsconfig.json in this way:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": ["es2018", "dom"],
"resolveJsonModule": true,
"esModuleInterop": true
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
But the error it doesn't disappear, it is throwed the same. Anyone can help me?
folder structure is
assets/ file/ and in the /file there is the config.jo;
Try the import statement below :-
import * as config from "../../../assets/file/config.json";
Try importing it directly from the asset as :
import config from "assets/file/config.json";
And further, if it doesn't work, you may need to set "resolveJsonModule": true in ts.config
I have a json file which looks like this
{
"type": "service_account",
"project_id": "blele",
"private_key_id": "9c0a8fe58c6a35a1640677b7dbf5b",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCQAsmXWkbeNsLn\nktPmTGONatPlZevmvSDO0IIMymUuRHPOuTQRm6k6WkYB1BB5gulGOsOc10hGrscK\nJtxj/G+eZguTvybosKdwVbm5sZ1jCUlS/TdmAVtJVWGf1YT/nxS1RuT+d7obFGN3\nNhMzQ2sm6JwmPIfF7kcfcU9Cjgjj5mDMa7OO2PQ4/gkKi+8/HhMge/4Wde\nd+/htb6ZA6BdHFSoevHHgTkkygJF47oDeirSN5VDDc1FYqSSZnCZ45uRik3RsAcw\ndInRhknSKdcbqyug9FQgM6l9T8a0sMpwgVcAjq3WaJaUgO1Wd9nfMhoItZvc6cIc\nbbBl3FxRAgMBAAECggEACK2gNQBGsRBfR0hdE/Y0oWnlJg8tSdM\nWDx6WgZIkhrfBZyvGndsUb5YS9MASLwfA+pYFRFg84lgMLjP4i1FBcSwsrM0kgN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u/Oj+gE33+V5C9qdk84v2Hn6\n1dUqBNjWjtlbRXjxFv4UAQ4=\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-0fcdc#be.iam.gserviceaccount.com",
"client_id": "10713329946488",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-0fc.gserviceaccount.com"
}
in ./.keys/admin.keys.json
I want to import that file in index.ts.
When I did something like this
import firebaseKeys from './.keys/admin.keys.json'
it is giving me an error (red underline on the vscode saying
Module
'"/Users/aia/Desktop/ble-typescript/functions/src/.keys/admin.keys"'
can only be default-imported using the 'esModuleInterop' flagts(1259)
admin.keys.json(1, 1): This module is declared with using 'export =',
and can only be used with a default import when using the
'esModuleInterop' flag.
this how my tsconfig looks like
{
"compilerOptions": {
"moduleResolution": "node",
"experimentalDecorators": true,
"module": "commonjs",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "lib",
"sourceMap": true,
"strict": true,
"target": "es2017",
"resolveJsonModule": true
},
"compileOnSave": true,
"include": [
"src"
],
"exclude": ["node_modules"]
}
This is my first project so can someone help me in comprehending how i can use .json file in typescript?
You can do this by adding "esModuleInterop": true under "compilerOptions" in your tsconfig.json:
{
"compilerOptions": {
..
"resolveJsonModule": true,
"esModuleInterop": true
},
..
}
Form more information on compiler options, see the compiler options documentation.
I want to display data in an html file coming from a local json file.
My JSON looks like:
{
"ACCESSIBILITY_EXPANDED": "Expanded",
"ACCESSIBILITY_BACK": "Back",
"ACCESSIBILITY_COLLAPSED": "Collapsed",
"ACCESSIBILITY_PHONE_NUMBER": "Call us at",
"ACCESSIBILITY_EMAIL": "Email us at",
"ACCESSIBILITY_ADDRESS": "Visit us at",
"ACCESSIBILITY_FAX": "Send us a FAX at",
}
What i did so far is change my tsconfig.json to look like this:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/#types",
"src/typings.d.ts"
],
"lib": [
"es2018",
"dom"
],
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"esModuleInterop": true,
}
}
Added a file called in src folder called typings.d.ts which looks like this:
declare module "*.json" {
const value: any;
export default value;
}
And then in my component's .ts file i did.
import en from '../../assets/i18n/en.json';
However in my html file when i did something like
<span class="bolded"> {{ en.ACCESSIBILITY_BACK }}</span>
i got an error saying Cannot read property ACCESSIBILITY_BACK of undefined. When I console.log(en) in ngOnInit() it's logs my object fine.
Any ideas? Thanks
{{ en }} is a template property, so you need to assign it to a component property:
#Component({
template: '...<span class="bolded"> {{ en.ACCESSIBILITY_BACK }}</span>...'
})
export class A11yComponent {
// assigns `en` from json to a component property `en`
en = en;
}
You could also use interpolation in the template string / concatenation, but this will not be allowed with AoT compilation.