Typescript with async/await, Promise and function default parameters - node.js

I have a nodeJS-Express-Typescript project where I want to use some native promises with async/await and also some default value for a function. This would be a simple example of what I can achieve:
sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, 500));
}
async someFunction(param = "default") {
doStuff(param);
await sleep(500);
doSomeMoreStuff();
}
The IDE warns me about this error:
$ tsc -p .
error TS2468: Cannot find global value 'Promise'.
spec/routes/users.spec.ts(508,23): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.
src/utils/sleep.ts(10,20): error TS2693: 'Promise' only refers to a type, but is being used as a value here.
so I have to add es2015 as target in my tsconfig.json:
"target": "es2015"
But then, this error comes when executing the transpiled JS:
/../users-api/dist/src/repository/realm-helper.js:21
static init(development = false) {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/../users-api/dist/src/routes/users.js:4:24)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
So that I have to change the target to "es5":
"target": "es5"
Which leads to a vicious circle.
I've tried changing the value of "target" and "module" and it always fails something.
Am I missing something here? In theory, typescript 2.2 supports both features so I don't get why I can't transpile.
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"rootDir": ".",
"sourceMap": true,
"module": "commonjs",
"target": "es5"
},
"include": [
"./src/**/*",
"./spec/**/*"
]
}
typescript 2.4.1
node 4.4.7

Try Adding lib section with es2015.promise in tsconfig.json
"lib": [
"dom",
"es5",
"scripthost",
"es2015.promise"
],
You can see the full sample here: https://github.com/basarat/typescript-book/tree/master/code/async-await/es5

Related

jhipster based nhipster server start error

I am trying to generate Angular NestJS based application using Jhipster i.e, nhipster.
Below is my jhipster and nodejs version numbers:
Jhipster : 7.7.0
NodeJS: 16.14.0 LTS
But I am getting the below error, when I am trying to start the server:
Error:
/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:240
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: тип Unable to compile TypeScript:
src/client/header-util.ts:56:19 - error TS2552: Cannot find name 'URL'. Did you mean 'url'?
56 url = new URL('http://localhost' + url);
~~~
src/client/header-util.ts:55:32
55 private static prepareLink(url, pageNumber, pageSize, relType): any {
~~~
'url' is declared here.
at createTSError (/Users/kmadasu/kishore/mnkb/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:240:12)
at reportTSError (/Users/kmadasu/kishore/mnkb/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:244:19)
at getOutput (/Users/kmadasu/kishore/mnkb/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:360:34)
at Object.compile (/Users/kmadasu/kishore/mnkb/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:393:11)
at Module.m._compile (/Users/kmadasu/kishore/mnkb/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:439:43)
at Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Object.require.extensions.<computed> [as .ts] (/Users/kmadasu/kishore/mnkb/projects/nhipster/mauto/server/node_modules/ts-node/src/index.ts:442:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
[nodemon] app crashed - waiting for file changes before starting...
That "URL" function at your line "56" is not imported into the typescript module properly. It is a function that comes from dom definition inside the typescript compiler. You could find a way to import it into the header-util class. Another way, and what I'd do is enable "dom" in the compiler options in the ts-config file of the server, by adding "dom" to the lib array like so:
{
"compilerOptions": {
/* Basic Options */
"typeRoots": ["node_modules/#types"],
"target": "ES2017" /* Specify ECMAScript target version: 'ES3' (default),
'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs',
'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"lib": [
"es6",
"dom" /* <--- here you are */
]
...
}

require() of ES modules is not supported

I have an issue when I try to run webpack with webpack.config.ts written in typescript and ts-node has "require": ["tsconfig-paths/register"]
// tsconfig.json
{
compilerOptions:{
paths: { /* ----------------- */ }
},
'ts-node':{
"require": ["tsconfig-paths/register"],
"compilerOptions": {
"sourceMap": false,
"module": "commonjs"
}
}
}
when I remove "require": ["tsconfig-paths/register"] from ts-node it runs, but webpack cannot detect aliases.
I already set module: commonjs in my tsconfig.json and removed type: module from my package.json
trace
> webpack
(node:5932) Warning: require() of ES modules is not supported.
require() of /home/node_modules/colorette/index.js from /home/node_modules/webpack-cli/lib/utils/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /home/node_modules/colorette/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/node_modules/colorette/package.json.
(node:5932) UnhandledPromiseRejectionWarning: /home/node_modules/colorette/index.js:28
export const options = Object.defineProperty({}, "enabled", {
^^^^^^
SyntaxError: Unexpected token 'export'
at new Script (vm.js:84:7)
at NativeCompileCache._moduleCompile (/home/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
at Module._compile (/home/node_modules/v8-compile-cache/v8-compile-cache.js:184:36)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (/home/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object.get colors [as colors] (/home/node_modules/webpack-cli/lib/utils/index.js:3:16)
at Object.error (/home/node_modules/webpack-cli/lib/utils/logger.js:5:58)
(node:5932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:5932) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
`

Issue with JoinTable in NestJS + TypeORM

I'm struggling with a weird issue in NestJS + TypeORM.
Pretty much I've created a ManyToMany relation in an entity and, on the owning side of the relation, I've added the #JoinTable() with no parameters.
After running nest build, the entity.js file adds a new import const browser_1 = require("typeorm/browser");, which, I found out, is used in declaring the JoinTable option in the compiled JS file => browser_1.JoinTable().
The issue is that, when using typeorm to generate a new migration file, I keep getting the following error:
import { __awaiter, __generator } from "tslib";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .js] (C:\XXX\XXX\dev\XXX\pistis-api\node_modules\ts-node\src\index.ts:1045:43)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\XXX\XXX\dev\XXX\pistis-api\dist\modules\collaborator\entity\collaborator.entity.js:17:19)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
Tracking down the issue, it seems to be related to this browser import that is being imported from ./node_modules/typeorm/browser/index.js
I'm using .env to configure typeorm, with the following:
TYPEORM_CONNECTION=postgres
TYPEORM_HOST=localhost
TYPEORM_USERNAME=xxxxx
TYPEORM_PASSWORD=xxxxx
TYPEORM_DATABASE=xxxx
TYPEORM_PORT=5432
TYPEORM_SYNCHRONIZE=false
TYPEORM_LOGGING=true
TYPEORM_DROP_SCHEMA=false
TYPEORM_MIGRATIONS_RUN=true
TYPEORM_ENTITIES=dist/modules/**/entity/*.js
TYPEORM_ENTITIES_DIR=src/modules/**/entity
TYPEORM_MIGRATIONS=dist/migrations/*.js
TYPEORM_MIGRATIONS_DIR=src/migrations
TYPEORM_MIGRATIONS_TABLE_NAME='orm_migrations'
This configuration has worked until I've introduced the ManyToMany relation and the JoinTable.
As far as .tsconfig goes, I have:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"dom",
"es6",
"dom.iterable",
"esnext"
],
"allowJs": true,
"declaration": true,
"removeComments": true,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": false,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true
},
"include": [
"src"
]
}
Any help would be appreciated.
Thanks in advance!
So, after a month of not touching this project, I decided to restart it and take a fresh look into it. Pretty much came to find out it was a newbie issue related to the way I'm importing the JoinTable option. I pretty much trusted the IDE to do the import and that was my mistake.
So, to sum it up:
I had:
import {JoinTable} from 'typeorm/browser';
When I should have:
import {JoinTable} from 'typeorm';
For future reference, these import errors might also originate from simple mistakes like these and not the complex ones we find on Stackoverflow telling us to check tsconfig.json and the likes.
Thanks :)

NodeJS-Typescript-Yarn : Error: Cannot find module 'd3'

I'm getting this error and couldn't resolve d3 import . I'm using Typescript#4.0.5 and Yarn
The file Layout.ts (Layout.js) imports d3 which throws an error.
import * as D3 from "d3";
and yarn build
$ yarn build
yarn run v1.22.5
$ tsc && node dist/lib/index.js
internal/modules/cjs/loader.js:834
throw err;
^
Error: Cannot find module 'd3'
Require stack:
- /home/github/my-app/dist/lib/graphs/Layout.js
- /home/github/my-app/dist/lib/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:831:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Module.require (internal/modules/cjs/loader.js:903:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/github/my-app/dist/lib/graphs/Layout.js:27:25)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:903:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/github/my-app/dist/lib/graphs/Layout.js',
'/home/github/my-app/dist/lib/index.js'
]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
and my tsconfig,
{
"compileOnSave": true,
"compilerOptions": {
"target": "es2018", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["DOM","dom.iterable","ES2018.AsyncIterable","ES2017.TypedArrays","es2018", "esnext.asynciterable", "ES5", "ES6"], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true,
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"types": [
"node", /* Type declaration files to be included in compilation. */
],
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
//"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
any help is much appreciated. Thanks in advance.
There is in built in command build in yarn.
All possible options you can find here.
Try yarn install instead
After a few days, gave it a try again, found a solution for adding type d3,
for old versions,
add globals
yarn install typings --global.
search for typings named d3
yarn typings search --name d3
if not exist install it,
yarn typings install d3 --save. //for old versions
yarn add #types/d3. //latest versions
and it worked as expected!

How to use await async in firebase cloud function?

I've built a couple of cloud functions in nodejs 6 and now i want to use await. How do I do that? How can I upgrade to node 8? I don't want to shift to typescript.
I've tried adding "engines": {"node": "8"} to package.json but it changed nothing.
This is a test cloud function I made:
exports.awaittest = functions.https.onRequest(async (req, res)=>{
ref = await admin.database().ref("/something/");
res.send(ref)
})
when I try to deploy it (with package.json edited), I get this:
SyntaxError: Unexpected token (
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at getUserFunction (/var/tmp/worker/worker.js:413:24)
! functions[awaittest]: Deployment error.
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:59
exports.awaittest = functions.https.onRequest(async (req, res)=>{
^
How do I upgrade to node8? I already have 6 functions deployed in node6.
I solved it in the functions/.eslintrc.json directory by changing the following:
"parserOptions": {
"ecmaVersion": 6
}
// to
"parserOptions": {
"ecmaVersion": 2017
}
'''

Resources