Solve the compatibility issue of typescript node tsx
Problem
There are various compatibility issues when using typescript + tsx + node in projects, including:
[esbuild Error]: Top-level await is currently not supported with the “cjs” output format
Cannot find module ‘X’. Did you mean to set the ‘moduleResolution’ option to ‘nodenext’, or to add aliases to the ‘paths’ option?
X is a type and must be imported using a type-only import when ‘verbatimModuleSyntax’ is enabled
An ‘export default’ must reference a value when ‘verbatimModuleSyntax’ is enabled, but ‘X’ only refers to a type
Solution
After configuring the following files, the above problem is solved.
package.json
Add and set the following:
{
"type": "module",
"script": {
"dev": "npx tsx src/app.ts"
}
}tsconfig.json
Set the following:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"customConditions": ["module"],
"allowArbitraryExtensions": true,
"noEmit": true,
"verbatimModuleSyntax": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
}import, export
Use `export type X = {}` to export a TypeScript Type, for example:
export type X = {
item_1: string,
item_2: string
}Likewise, use `import type { X } from path` to import TypeScript Type, for example:
import type { X } from './types'Import and export third-party libraries using the `ESM` form, for example:
import express from 'express'
export default X
