microsoft / tslib

Runtime library for TypeScript helpers.
BSD Zero Clause License
1.25k stars 126 forks source link

Problem with tslib and ES modules #81

Closed sosoba closed 3 years ago

sosoba commented 4 years ago

When Typescript compiler produces esm output, ex:

{
  "compilerOptions": {
    "target" : "esnext",
    "module": "esnext",
    "experimentalDecorators": true,
    "importHelpers": true,
  }
}

source test.ts

@foo()
class Bar {
}

dest test.js

import { __decorate } from "tslib";

let Bar = class Bar {
};

Bar = __decorate([
    foo()
], Bar);

Node 12/13 (which support esm natively) give error:

import { __decorate } from "tslib";
         ^^^^^^^^^^
SyntaxError: The requested module 'tslib' does not provide an export named '__decorate'

I seems to me, that Node treat tslint like as cjs module but his tslib.js does not contain standard cjs export.default expression.

nalply commented 4 years ago

It's because tslib.js is not an ES module.

See: https://github.com/microsoft/tslib/blob/master/tslib.js#L257 If you search the file, you'll find no import nor export statements, as you already discovered.

You'll need to import tslib.es6.js instead. It's a hassle, I know. If you use the new browser import map you could add something like "tslib": "/node_modules/tslib/tslib.es6.js" to the import map JSON.

I am watching this issue because I think TypeScript should switch to tslib.es6.js when using "ESNext" in tsconfig.json. It's a bug IMHO.

sla100 commented 4 years ago

May be you can publish in parallel package? See (https://gitlab.com/sosoba/tslib)

npm install tslib@npm:@sosoba/tslib
nalply commented 4 years ago

I solved the problem with the help of an import map. My project already uses an import map, so it was easy to have or to modify the property "tslib": "/node_modules/tslib/tslib.es6.js" in the "imports" object of the import map. It's still a hassle because when tslib fixes this bug I will need to remove this work-around.

frankwallis commented 4 years ago

It looks like https://github.com/microsoft/tslib/pull/44 is the solution to this (rename tslib.es6.js -> tslib.mjs)

nalply commented 4 years ago

I am not sure about the .mjs extension. I don't know, perhaps it's better the TypeScript compiler emit the right import or require instead.

avaly commented 4 years ago

Possibly related to this: https://github.com/typegoose/typegoose/issues/172

sla100 commented 4 years ago

The offer #84 will solve the problem