Typescript build does not support Commonjs from Node.js

Asked

Viewed 479 times

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!'); ?

  • Yes, and it works. The problem only happens when I use Commonjs on Node.js (Javascript).

  • I thought the following the interpreter might not be understanding function alert(message: string): void { alert(message); } as a recursive function? If you do function alert(message: string): void { Window.alert(message); } what would be the result?

  • 3

    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.

  • 1

    Buddy, transpile/Compile the typescript with webpack!

  • @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.

  • Try using this flag when calling Tsc, e.g.: Tsc --allowSyntheticDefaultImports documentation: https://www.typescriptlang.org/docs/handbook/compiler-options.html

  • You are using the module ts-node?

Show 3 more comments

2 answers

0


Although I didn’t feel like it was the most ideal, I managed to solve attributing value exported to keyword export:

export = function alert(message: string) {
  console.log(message);
}

I think one more way "correct" to do so would be using tools such as webpack or rollup. However, what I did above served my needs.

Here it is possible to consult a configuration file of the rollup that could also solve my problem. I did not search an example for the webpack.

0

I don’t know if you’ve ever tried it, but what if default of the module you created? Example:

export function alert(message: string): void {
  console.log('Alerta: ' + message)
}

Another thing, you’re calling the module as alert.js, but is creating how alert.ts.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.