Import Json file in Angular 6? - json

Tried several different ways to import a json file but get
countries.json has unknown extension.
Is there a solution to this I'm missing?
Current tsconfig:
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"types": [ "node"],
"target": "es5",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2017",
"dom"
]
},
"include": ["./src/**/*", "./src/**/*.json"],
}
Here the import is as follows import * as countries from './countries.json';
And the setup of countries.json is this..
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
]

import something from "somewhere" means that import the default exported value from path.
Clearly, json files does not have any export as default. You can import everything or you can import some property from it.
To import everything from json file:
import * as something from "somewhere"
To import some property from json file: when the content of file is like
file.json
{
"name": "Stackoverflow",
"otherProperty": "otherValue"
}
To import only name :
import { name } from "file.json"
But Typescript added --resolvejsonmodule option in the version 2.9. As I know Angular started to use Typescript 2.9 at the version 7, so for your case:
json.service.ts
#Injectable()
export class JsonService {
constructor(private http: HttpClient) {}
getJson(path: string) {
return this.http.get(path);
}
}
and do not forget to add your JsonService to providersarray of your module and finally, you need to import HttpClientModule at your module.

I believe Angular 6 json support is a bit wonky, so I would update the proyect to a newer version (which, with angular, is not a huge workload). From Angular 7 onwards you can configure your tsconfig.json file like this:
{
"compileOnSave": false,
"compilerOptions": {
...
"resolveJsonModule": true,
...
}
This way you can import your .json files normally like this:
import * as data from './data.json';
Hope this helps!
Ill leave an article with an example an step by step: https://www.techiediaries.com/import-local-json-files-in-typescript/

Related

Is there any way for typescript test files to import typescript source files when they have separate tsconfigs?

Sorry about the vague title here, it's one of those problems where I don't know what I don't know. Let me describe my directory structure:
root
src
tsconfig.json
test
tsconfig.json
tsconfig.json
This is some legacy code. Normally I like to set up my project so that test files and source files are in the same directories, but that would be a massive change, so I'm trying to figure out how to get it to work the way it's already structured.
Basically, I want to be able to do this in a test file:
// current file: test/downloader_test.ts
// downloader file: src/downloader.ts
import { Downloader } from "./downloader";
...
I can do this when source and test files are in the same directory, but in this case, they are in separate directories so I get an error on the import line about how "./downloader" doesn't exist.
There is a workaround that's already being used: instead, I could import from ../lib/downloader, and it works, but I'd like to be able to refer to the typescript files. Is there any way for test files to import typescript source files when they are under separate tsconfig.json files?
I figure if a solution exists it's probably a tsconfig setting. These are what mine currently look like:
root/tsconfig.json:
{
"compilerOptions": {
"rootDir": ".",
},
"files": [],
"references": [
{
"path": "./src"
},
{
"path": "./test"
},
]
}
root/src/tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "../lib",
"noImplicitReturns": true,
"noUnusedLocals": true,
"sourceMap": true,
"strict": true,
"lib": ["es2020", "dom"],
"target": "es2019",
"composite": true,
"allowSyntheticDefaultImports": true
},
"compileOnSave": true,
"types": ["node"],
"include": ["**/*.ts"]
}
root/test/tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "../libtest",
"strict": false,
"composite": true,
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"include": [
"**/*.ts"
]
}
I've also tried modifying that last file to add a
"references": [
{
"path": "../src"
}
]
but that didn't change anything for me.
You can use one config file in root folder only, and in include, you can add
"include": [
"src/**/*" // According to your structure
]
other things in config file set according to your requirement and change the path.
import { Downloader } from "../src/downloader”;

TS2307: Cannot find module or its corresponding type declarations

I have a private GitHub repo my-parser-generator which uses pegjs. All underlying logic is written in TypeScript, which is then compiled and fed to pegjs, which generates the final parser.
Then this repo a
is used a package dependency in another private repo parser-consumer, which is written in TypeScript (compiled with --declaration option). So my-parser-generator basically offers JavaScript files to a TypeScript consumer.
But when I try to import the newly generated parser I get the following error:
TS2307: Cannot find module 'my-parser-generator' or its corresponding type declarations
I've tried most of the solutions on the internet, but nothing has worked for me
my-parser-generator
package.json (most of the lines are omitted)
{
"private": true,
"version": "0.4.9",
"name": "my-parser-generator",
"files": [
"dist/lib/**/*.js",
"dist/excel.browser.js",
"dist/**/*.d.ts",
"dist/**/*.js.map"
],
"main": "dist/excel.browser.js",
"typings": "dist/index.d.ts",
"type": "module",
"dependencies": {
"pegjs": "^0.11.0-master.b7b87ea"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2019",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"outDir": "dist/lib/",
"sourceMap": true
},
"exclude": ["node_modules", "dist", "tests", "excel.browser.js"],
"include": ["src/**/*"]
}
dist/excel.browser.js (generated by pegjs so all code is omitted in favor of what is exported)
export {
peg$SyntaxError as SyntaxError,
peg$parse as parse
};
export default {
SyntaxError: peg$SyntaxError,
parse: peg$parse
};
dist/index.d.ts - my attempt to add some typings for the generated file above
declare namespace MyParserGenerator {
type PegLocation = {
offset: number,
line: number,
column: number
}
type Options = {
startRule: string,
filename: string
}
function SyntaxError (message: string, expected: string, found: string, location: PegLocation): void;
function parse <T extends Options>(input: string, options: T): any;
}
declare module "my-parser-generator" {
export default MyParserGenerator
}
parser-consumer
package.json
{
...,
dependencies: {
"my-parser-generator": "git+ssh://git#github.com/my-repo/my-parser-generator.git#master",
...,
},
...,
}
node_modules/my-parser-generator - package structure
dist/
lib/
grammar.js
grammar.d.ts
grammar.js.map
excel.browser.js
index.d.ts
package.json
README.md
index.ts - the code that uses the parser and throws the error
import parser from 'my-parser-generator';
Interestingly enough, WebStorm can easily locate and auto-complete the package
About the declaration for your parser you could use the pegjs/typings/generated-parser.d.ts from your node modules as a starting point.
For the message Cannot find my-parser-generator or its corresponding declarations. I suspect it could be because (1) you are saving the index.d.ts in the dist folder instead of the package root, (2) the js file is dist/excel.browser.js, this is easily associated with dist/excel.browser.d.ts.
I would add your my-parser-generator/package.json, accordingly to the typescript publication guidelines
{
"types": "dist/index.d.ts"
}

Resource file missing in TypeScript package

I have a Lerna project containing two Typescript packages A and B. The tsconfig.json for both packages is:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"esModuleInterop": true,
"noImplicitAny": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
"allowJs": false,
"resolveJsonModule": true,
"declaration": true,
"moduleResolution": "node",
"lib": ["es2015", "dom"]
},
"include": [
"src",
"test"
],
"exclude": [
"node_modules/**",
"packages/*/node_modules/**",
"examples/*/node_modules/**",
"**/*.d.ts"
]
}
Package A contains the following code:
const data = require('./myData.json');
Package B depends on package A. Inside package B a call is made to a function exported by package A, and so the above code is loaded. However, I get Error: Cannot find module './myData.json' in this context. Now, looking inside compiler output directory for package A I do not see the JSON file. Indeed, looking inside package B's node_modules directory at package A I do not see the file there either.
Why might the JSON file missing from the published package? Is there anything special that needs to be done to include resource files (JSON, plaintext) in the Typescript package?

Importing JSON file in Node Typescript

I have tried every solution found online but it seems I cannot get my specifics resolved.
I am trying to import a static .json file into a node controller, all in TypeScript.
The error I'm getting is
Cannot find module './data.map.json'
I've checked the path 100 times it's definitely correct. I have tried every combination of require vs import, and every option I could find in tsconfig.json, which is where I believe the problem lies.
Below is a clean minimal example showing my setup. How can I import a static json file in my Typescript application?
controller
import * as data from "./data.map.json";
typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
tsconfig.json
{
"compilerOptions": {
"outDir": "build",
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"typeRoots": ["node_modules/#types"],
"paths": {
"*": ["typings.d.ts"]
}
},
"files": [
"typings.d.ts"
],
"include": [
"src/**/**.ts",
"test/**/**.ts"
],
"exclude": [
"node_modules"
],
"compileOnSave": false
}
The workaround may no longer be required since TS 2.9 added support for well typed json imports. Just add:
{
"compilerOptions": {
"resolveJsonModule": true
}
}
in your tsconfig.json or jsconfig.json. With this approach, you currently must use the full path with a .json file extension:
import * as data from "./data.map.json";
instead of:
import * as data from "./data.map";
Fixed this a while ago forgot to post the answer on here. Instead of trying to import a json file I just export a json object from a typescript file and it works great
Changed the import line to
import {default as map} from "./data.map";
and the file data.map.ts is
export default {
"key": "value"
}
and you can access it just as you'd expect with
map["key"] // gives you "value"

Use Maps with typerscirpt and requirejs

I starting using requirejs with typescript and the amd module of typescript.
Right now I am using HereMaps with typescript, the functions are only referenced with a d.ts file.
How could I reference/import Here Maps, google maps or openstreetmaps to typescript 2, that it will be loaded by requirejs?
I think it is not a perfect combination and it will be better to use webpack or something simular
I solved it by switch the typescript module to AMD in tsconfig.json
{
"compilerOptions": {
"module": "AMD",
"target": "es5",
"sourceMap": true,
"declaration": false
},
"exclude": [
"node_modules"
]
}
then you have to use require to import reference
import H = require('heremaps-core');
after you define external references
requirejs.config({
shim: {
'heremaps-core': {
exports: 'H'
},
'heremaps-ui': ['heremaps-core'],
'heremaps-service': ['heremaps-core'],
'heremaps-events': ['heremaps-core'],
'hogan': {
exports: 'Hogan'
}
},
paths: {
'jquery': [
'https://code.jquery.com/jquery-3.1.1.min',
'https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min',
'lib/jquery-3.1.1.min'
],
'hogan': [
'https://twitter.github.io/hogan.js/builds/3.0.1/hogan-3.0.1.js',
'lib/hogan.min'
],
'google.maps': [
'https://maps.googleapis.com/maps/api/js?v=3.21 &key=AIzaSyBtw3pgNVNPacgQGwLQt1nUbBrqGW-De90'
],
'heremaps-core': [
'https://js.api.here.com/v3/3.0/mapsjs-core'
],
'heremaps-ui': [
'https://js.api.here.com/v3/3.0/mapsjs-ui'
],
'heremaps-service': [
'https://js.api.here.com/v3/3.0/mapsjs-service'
],
'heremaps-events': [
'https://js.api.here.com/v3/3.0/mapsjs-mapevents'
]
}
});
I am not sure if it is all. I did not work at this project since a year.