angular-cli: Cannot import json files when running ng test
Bug Report or Feature Request (mark with an x
)
- [x] bug report -> please search issues before submitting
- [ ] feature request
Versions.
@angular/cli: 1.1.3
node: 8.1.0
os: win32 x64
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/flex-layout: 2.0.0-beta.8
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/material: 2.0.0-beta.7
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.1.3
@angular/compiler-cli: 4.2.4
Repro steps.
import sampleData from './data.json';
// check if sampleData is undefined or not - in ng serve it has the correct value, in ng test it's undefined
You can see more details in this repo - https://github.com/pgrm/angular-bug-import-json
npm start
- you should see the content of sample.jsonnpm test
- the exception will be thrown that it’s undefined (the exception is just there to demonstrate that it’s undefined)
Desired functionality.
since I import the json file as a module, it should be imported the same way in tests, like it is done for the application to be served or compiled
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 6
- Comments: 16 (1 by maintainers)
You need to have typings for jso file. Put this to your typing.d.ts
declare module '*.json' { const value: any; export default value; }
Then use
import * as sampleData from './data.json';
@Juansasa works for me until the latest version of
angular/cli
(1.6.2).It seems that somehow this issue is related to this merge https://github.com/angular/angular-cli/commit/09177d1
This merge force to use
module: 'commonjs'
incompilerOptions
of tsconfig.And by default,
ng test
usecommonjs
either (seesrc/app/tsconfig.spec.ts
in your project).I don’t know what is the difference between
commonjs
andes2015
. Any idea why?UPDATE
UPDATE
I think this is because typescript compile in different way. See example below.
To clarify i’ve been using this trick for quite some time since Angular first released until now at version 6 everything just work.
typings.d.ts
declare module '*.json' { const value: any; export default value; }
Component import
import * as JSON from './file.json';
I’ll create a sample project and post it here to clear this issue once for all and will post it here.
Update Angular 6 JSON import
The same problem here using angular 6. I created a library with the new command
ng generate library
. In the new library component created I’m importing a json file in the same path of the library component. When I try to build I getCannot find module './palettes.json'
. How to solve it?I’ll have a look but generally we don’t really support loading anything but js/ts files as ES6 imports. It is inconsistent that it works in one case and not the other though.