6
Let’s say I have a module alert.ts
:
export default function alert(message: string): void {
console.log('Alerta: ' + message)
}
When performing the build using the tsc
, and try to use the code generated by Node.js (with Javascript):
const alert = require('./dist/alert.js')
alert('Hello, World!') // ERRO! `alert` é `undefined`
It gives error. The only way to resolve this error is to use the .default
:
// ↓↓↓↓↓↓↓↓
const alert = require('./dist/alert.js').default
alert('Hello, World!') // OK!
The question is: How to configure Typescript so that when using the code generated with Node.js there is no need to use this one .default
?
PS: I’ve tried using the options esModuleInterop
, module
and/or moduleResolution
, but none of the three seem to solve the problem.
Have you tried
import alert from './dist/alert.js'; alert('Hello, World!');
?– Augusto Vasques
Yes, and it works. The problem only happens when I use Commonjs on Node.js (Javascript).
– Luiz Felipe
I thought the following the interpreter might not be understanding
function alert(message: string): void { alert(message); }
as a recursive function? If you dofunction alert(message: string): void { Window.alert(message); }
what would be the result?– Augusto Vasques
Actually the problem is in the Typescript build phase. I just don’t know how to fix it. TS can’t generate a build which is also compatible with Commonjs from Node.JS. By the way, the
alert
really was a wrong example, since it does not exist on Node... I edited the question.– Luiz Felipe
Buddy, transpile/Compile the typescript with webpack!
– user148754
@Luizfelipe are you using Typescript with the backend (nodejs) is that it? Post also more information about your typescript settings and how you are using it to compile.
– user148754
Try using this flag when calling Tsc, e.g.: Tsc --allowSyntheticDefaultImports documentation: https://www.typescriptlang.org/docs/handbook/compiler-options.html
– PaulaoDev
You are using the module
ts-node
?– user148754