Issue with JoinTable in NestJS + TypeORM - nestjs

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 :)

Related

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!

Migration from Angular 6 to Angular 7 cause error - Can't resolve 'core-js/es7/reflect'

Global Angular CLI: 7.3.8
Node v10.15.3
NPM 6.4.1
macos
I'm getting this error on npm start
ERROR in
./node_modules/#angular-devkit/build-angular/src/angular-cli-files/models/jit-polyfills.js
Module not found: Error: Can't resolve 'core-js/es7/reflect' in
'/Users/XXX/projects/XXX/node_modules/#angular-devkit/build-angular/src/angular-cli-files/models'
ERROR in ./src/polyfills.ts Module not found: Error: Can't resolve
'core-js/es7/reflect' in '/Users/XXX/projects/XXX/src'
To solve this issue I've added the following paths to compilerOptions in tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"paths": {
"core-js/es7/reflect": [
"node_modules/core-js/proposals/reflect-metadata",
],
"core-js/es6/*": ["node_modules/core-js/es"]
},
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/#types"
],
"lib": [
"es2017",
"dom"
]
}
}
After Migrated to new Angular version, 'core-js/es6' or 'core-js/es7' Will not work.
You have to simply replace import 'core-js/es/'
For ex. import 'core-js/es6/symbol' to import 'core-js/es/symbol'
This will work properly.
just remove the number at the end of 'es' in the path, like 'core-js/es/reflect'. It worked for me.
I just copy all from my oldest project src/polyfills to the new imported. That's help ;) .
Getting this error in "#angular/cli": "~10.1.5" project:
Cannot find module 'core-js/es7/reflect' or its corresponding type declarations.ts(2307)
Solution:
import * as Reflect from 'core-js/es';

Typescript with async/await, Promise and function default parameters

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

How do I figure out all the global imports and from where are those imported?

when I add the following line at the beginning of app.ts
const crypto = require('crypto');
I get the following error,
Cannot redeclare block-scoped variable 'crypto'
Seems like it has been globally imported from somewhere else,
this is how my tsconfig.json looks like
{
"compilerOptions": {
"allowJs": true,
"outDir": "./dist",
"target": "ES6",
"module": "commonjs",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false,
"strictNullChecks": true,
"noUnusedLocals": true,
"types": [
"node"
],
"typeRoots": [
"./node_modules/#types"
],
"lib": ["es2015", "dom"]
},
"include": [
"./src/"
]
}
PS:
The above error is when I try to transpile it from terminal.
I am using VisualStdioCode, in VisualStdioCode it doesn't show any error as it points to,
/path/to/VisualStdioCode/Visual Studio
Code.app/Contents/Resources/app/extensions/typescript/node_modules/typescript/lib/lib.dom.d.ts
EDIT(solved):
The problem here was slightly different than cannot redeclare block scoped variable (typescript)
The aim of this question was to detect duplicate import source than use ES6 non explicit assignment to atomatically solve it for us.
The solution here was to import either from libs or node_modules and not to scope it unlike mentioned in answers there.
crypto is already a global read-only property in the browser, so TypeScript is keeping you from trying to overwrite it.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
But since you're using commonJS, you may be building for Node and maybe you didn't mean to include the "dom" typings in "lib"?

Error importing node modules in TypeScript

I had a problem this morning that was driving me crazy. I'll explain the issue and then I'll provide my answer below (so that others who come across this can get to a solution sooner).
It is very easy to duplicate the issue by just issuing these commands:
tsd query react --action install
mkdir src
echo "import React = require('react');" > src/foo.ts
I also included the following tsconfig.json file in src:
{
"version": "1.6.2",
"compilerOptions": {
"outDir": "./tsdir",
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"isolatedModules": false,
"jsx": "react",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true
},
"files": [
"foo.ts"
]
}
If I try to compile this by simply running the tsc (version 1.6.2) command inside src, I get:
foo.ts(1,24): error TS2307: Cannot find module 'react'.
What I find baffling here is that I've installed the react bindings with tsd but when I run tsc, I get this error. It looks like I've done everything right, so why the error?
So what I eventually figured out was that I need to explicitly include the typings file in my list of "files", i.e.,
{
"version": "1.6.2",
"compilerOptions": {
...
},
"files": [
"foo.ts",
"../typings/react/react.d.ts"
]
}
In other words, I had to include the typings files explicitly in the "files". I don't really know why. I thought tsc was smart enough to look for them itself.
If there is a better solution that doesn't involve having to list all the .d.ts files explicitly in "files", I'm all ears. But I just wanted to point out that this is at least a workaround.

Resources