How to access json file imported into Angular - node.js

I am importing a json file via:
import * as menuJson from './menu.json';
If console.log menuJson I get:
If I try to console.log menuJson.default I get:
The error is:
Property 'default' does not exist on type
How can I turn turn this back into regular json and not a module so I can access the json content?

If your Typescript version is 2.9+, you can Do the followings:
Add these to your compilerOptions in tsconfig.json file:
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
and import your json:
import menu from './menu.json';

Related

Using TS absolute paths in import statement triggers an error in react-native

I am currently converting relative paths to absolute paths in my React-Native app and it triggers the following error:
Error response to absolute import
And I have set up my tsconfig.json as follows:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"#buttons/*": ["src/components/buttons/*"]
},
"jsx": "react",
"resolveJsonModule": true
}
}
The following statement is how it looks in the file that I am importing it in:
import {CoreButton} from '#buttons/CoreButton';
Any ideas or suggestions would be amazing :)
The solution to this problem has been found at the following link:
React native Typescript path alias unable to resolve module

module resolution from 'dist' folder

I'm working on a nodeJs/Typescript app and I would like to be able to launch it from the dist/ folder.
The structure of each src and dist folders is something like that :
server/
|---dist/
| |---server/
| |---src/
| |---index.js
| |---utils/
| |---connection.js
|---src/
| |---index.ts
| |---utils/
| |---connection.ts
|
|---package.json
|---tsconfig.json
This dist folder is the generated code, with this path being configured using outDir inside of my tsconfig.json file.
I have also configured the main property in my package.json to be dist/server/src/index.js and the type property to be module
In this project, I am using Typescript 4.0.5
I have specified paths property in my tsconfig.json to be "utils/*" : ["src/utils/*"], the baseUrl property to be './' and the property moduleResolution strategy to be node
Now this is my issue. I would like to be able to import my modules the same way i do in my source code, but this time directly from the dist folder, like this :
import createConnection from 'utils/connexion';
However, when i hover the import declaration in VScode, it does not seems to resolve the module and i get an error Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'utils' imported from /home/maxime/Dev/JeuxDuPlacard/packages/server/dist/server/src/index.js
When i do the same operation from my Typescript files, it works as expected.
The paths of the files in the dist folder is the same in the Server folder. If the problem comes form the module resolution, Is there a way to persist the paths aliases in the dist folder (without installing a third party library) ?
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es2020",
"moduleResolution": "node",
"sourceMap": true,
"baseUrl": "./",
"outDir": "dist",
"strict": true,
"lib": ["ES2017", "ES2020"],
"types": [
"node"
],
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"incremental": true,
"skipLibCheck": true,
"strictPropertyInitialization": false,
"paths": {
"utils/*": ["src/utils/*"]
}
}
}
Thanks
That's right, because you CAN'T import files from outside your workdir. What you could do, is you could link a local module and access it as you would any other npm package.
npm link (in package dir)
npm link [<#scope>/]<pkg>[#<version>]
alias: npm ln
https://docs.npmjs.com/cli/v6/commands/npm-link

Typescript declaration file for an external npm package - constructor

I am using ES6 and Typescript for my Node project, however one library is a commonjs library.
For that library, I created my own .d.ts declaration file:
module "#alpacahq/alpaca-trade-api" {
export interface AlpacaParams { ... }
// ...
export class Alpaca implements Broker {
// ...
constructor(params: AlpacaParams);
}
export default Alpaca;
}
Everything works as expected, but I'm having a problem with the constructor.
If I use that class from within my project, and I try this:
this.alpaca = new Alpaca.Alpaca({...});
I get told that Alpaca.Alpaca is not a constructor.
The only way it seems to work is if I do:
this.alpaca = new Alpaca.default({...});
I'm quite new to Typescript, so I'm sure I'm doing something wrong. Any ideas?
The latter works, so I'm not blocked in my work, but I would like to set things up properly.
Thank you!
Edited to show TS config and imports
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"lib": ["es6", "es5"],
"sourceMap": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"moduleResolution": "node",
"typeRoots": ["./types"],
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
This is how I import it. Couldn't figure out how to make it work otherwise. If I import modules ES6 style, it breaks unless I use commonjs. If I use commonjs, I get an "export undefined" error.
import * as Alpaca from '#alpacahq/alpaca-trade-api';
The problem is that you're importing all named exports with import * meaning that Alpaca refers to the module and .default refers to the exported class. Instead you should be importing just the default member.
Change your import to look like this:
// Import default member from module
import Alpaca from '#alpacahq/alpaca-trade-api';
this.alpaca = new Alpaca({...});

Nodejs Typescript type only package is not exporting all types properly

The package I'm building (https://github.com/plastikfan/xiberia/tree/develop) is a type only package (I'm not using DefinitelyTyped and this question is not about DT).
The package essentially is just a single file (index.ts) which contains various exported types such as:
export interface IYargsFailHandler {
(msg: string, err: Error, inst: yargs.Argv, command: any): yargs.Argv;
}
The problem is, when I use this in a client app, most of the types are missing and the only type that appears by intellisense is:
export const CoercivePrimitiveStrArray = ['boolean', 'number', 'symbol'];
All the other types are missing.
When I look at the corresponding index.js file, all it contains is:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoercivePrimitiveStrArray = ['boolean', 'number', 'symbol'];
// -----------------------------------------------------------------------------
//# sourceMappingURL=index.js.map
The generated index.d.ts looks correct and contains all the types, (well there is one very weird definition that I can't account for at the end of the file):
export {};
My typescript config file is:
{
"compilerOptions": {
"allowJs": true,
"alwaysStrict": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "Node",
"noImplicitAny": true,
"sourceMap": true,
"strictNullChecks": true,
"target": "es5",
"declaration": true,
"declarationDir": "./dist",
"outDir": "./dist",
"diagnostics": true,
"lib": [
"es5",
"es2015",
"es6",
"dom"
],
"types": [
"node", "yargs"
],
},
"include": [
"./index.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
So why are most of the types missing and how do I correct it, thanks.
EDIT: OOPS, I just made a really silly mistake. The types should not be in the resultant .js file. The only valid js is indeed the CoercivePrimitiveStrArrayCoercivePrimitiveStrArray which is being exported.
But that doesnt explain why the types that are being exported are not shown by intellisense on the clienbt side.
So on the client, this is what I have:
in a client file:
import * as xiberia from 'xiberia';
When I type, "xiberia.", I would expect to see all the types being exported, but I don't see any.
I read up on the triple slash directive and it appears they are not appropriate for this situation.
So what other config setting do i need for te intellisense to work as expected?
I fixed this problem by simplifying the package as much as possible. Previously, I was building artefacts into the 'dist' folder, a pattern which is widely used. I have removed this (this is a simple single file package, so using a dist folder is overkill) and simply build out the resultant index.d.ts, index.js and the .map files into the root directory. This also required explicity specifiying these files in the 'files' property in package.json (this ensures that these files are included in the resultant package tarball built when performing npm pack via the publish mechanism).
I don't understand why now intellisense is working as a result of these actions; perhaps somebody who knows better can comment.

How to reference externally defined node modules with string identifiers with typescript

I'm writing a set of node helper modules in typescript. I'm having difficulty getting typescript to interpret type information for external node modules such as "fs" and "path".
Importantly, I want to separate my module into a bunch of Typescript files, with a class/interface per file. They file layout is like this:
ts/ISomeInterface1.ts
ts/ISomeInterface2.ts
ts/SomeClass1.ts
ts/SomeClass2.ts
A class instantiates one or more interfaces, and is written as follows:
///<reference path="IFileSystemHelpers.ts" />
var fs = require("fs");
namespace myNmspace {
export class SomeClass1 implements SomeInterface1 {
public someIFunction() {
//do work
}
}
}
I'm using gulp-typescript to install type declarations for NodeJs. And I use a tsconfig.json file to build and reference these external typings. Here's a snippet:
{
"version": "1.8.9",
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"declaration": true,
"suppressImplicitAnyIndexErrors": true,
"out": "./outputfile.js"
},
"filesGlob": [
"./**/*.ts",
"!./node_modules/**/*.ts"
],
"files": [
"./typings/main.d.ts",
"./ts/ISomeInterface1.ts",
"./ts/ISomeInterface2.ts",
"./ts/SomeClass1.ts",
"./ts/SomeClass2.ts",
"./ts/exports.ts"
]
}
Then classes are exported in the exports.ts file:
declare var exports: any;
if (exports) {
exports.SomeClass1 = myNmspace.SomeClass1;
exports.SomeClass2 = myNmspace.SomeClass2;
}
Then comes my problem. How do I get type information for the "fs" module?
I can see the following in the node.d.ts file (see here)that typings has installed:
declare module "fs" {
import * as stream from "stream";
import * as events from "events";
...
}
How do I force Typescript to interpret my fs variable in the SomeClass1.ts file as strongly-typed? In other words, what do I write here:
var fs : ??? = require("fs");
Can anyone help?
As an aside, I've noticed that if I replace the var with an import keyword, I get correct type interpretation for the fs variable. However the terms which point to my interfaces break and I get a squiggly line under the implements ISomeInterface1. Changing the pattern to use imports breaks my file separation, and seems valid only if I want to create a single-file node module.
Use ES6 style imports
import * as fs from 'fs'
import * as path from 'path'
This will also import the definitions from the definition file.
The syntax var x = require('x') does not (however import x = require('x') does, to add to the confusion)

Resources