Carlos Gonçalves
Carlos Gonçalves

Reputation: 86

Unexpected token export {} after importing cjs file in Typescript+ESM project

EDIT

I have a pretty simple typescript+esm project with a CJS dependency, so my code looks like this:

index.ts

import myFunc from "./myfile.cjs"
(...)

I also have the compilerOptions (inside tsconfig.json) allowSyntheticDefaultImportsand esModuleInterop set

But when I try to run it using ts-node (node --loader ts-node/esm --experimental-specifier-resolution=node src/index.ts) it fails with a syntax error saying that my cjs file, myfile.cjs has an unexpected token export (export {};)

It is clear to me that something (ts-node probably) is trying to convert this into an ESM module, but it just creates a syntax error and breaks the code. Obviously, I'm not adding it there manually.

Command used: node --loader ts-node/esm --experimental-specifier-resolution=node src/index.ts

Complete error log:

export {};
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1027:15)
    at Module._compile (node:internal/modules/cjs/loader:1063:27)
    at Module.m._compile (/Users/cjg/Git/ast/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .js] (/Users/cjg/Git/ast/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)

tsconfig.json

{
    "compilerOptions": {
        "moduleResolution": "node",
        "baseUrl": "./src",
        "module": "es2020",
        "outDir": "./dist",
        "allowJs": true,
        "target": "es2020",
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
    },
        "include": [
        "./src/**/*"
    ]
}

Does anyone have a clue?

Thanks in advance!

Upvotes: 1

Views: 1873

Answers (1)

Franz Zemen
Franz Zemen

Reputation: 11

There are several threads on this when generating code for a ".ts" file, even for a commonjs target. From what I can tell, typescript developers think the generated export {}; is a feature in those files and provide the rationale (which many disagree with).

From your description, and I tested the same, they're doing the same in very specifically (.cjs) files.

The solution for now is to remove the line in your build. Maybe using gulp-replace?

Upvotes: 0

Related Questions