Node.js生产环境TypeScript转JavaScript及tsc编译错误求助
Node.js TypeScript生产环境编译问题解决
刚接触Node.js生产环境开发,用TypeScript写了后端应用,目前靠ts-node启动项目。知道生产环境得把TypeScript转成JavaScript来提升性能,不想自己写批量转换脚本,用tsc编译时碰到了一堆错误,具体错误信息如下:
src/index.ts:1:8 - error TS1259: Module "c:/myProject/node_modules/@types/express/index" can only be default-imported using the 'esModuleInterop' flag 1 import express from "express"; ~~~~~~~ node_modules/@types/express/index.d.ts:133:1 133 export = e; ~~~~~~~~~~~ This module is declared with 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. src/index.ts:6:8 - error TS1259: Module "path" can only be default-imported using the 'esModuleInterop' flag 6 import path from "path"; ~~~~ node_modules/@types/node/ts4.8/path.d.ts:178:5 178 export = path; ~~~~~~~~~~~~~~ This module is declared with 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. src/lib/data.ts:36:7 - error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. 36 get taxYears() { ~~~~~~~~ src/lib/reader.ts:5:8 - error TS1192: Module "fs/promises" has no default export. 5 import fs from "fs/promises"; ~~ src/lib/reader.ts:6:8 - error TS1259: Module "path" can only be default-imported using the 'esModuleInterop' flag 6 import path from "path"; ~~~~ node_modules/@types/node/ts4.8/path.d.ts:178:5 178 export = path; ~~~~~~~~~~~~~~ This module is declared with 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. Found 5 errors in 3 files. Errors Files 2 src/index.ts:1 1 src/lib/data.ts:36 2 src/lib/reader.ts:5
错误修复方案
1. 解决TS1259:默认导入CommonJS模块报错
express、path这类模块用的是CommonJS的export =语法,TypeScript默认不支持直接默认导入。修改tsconfig.json的编译选项,开启两个关键配置:
{ "compilerOptions": { "esModuleInterop": true, "allowSyntheticDefaultImports": true, // 保留你原来的其他配置 } }
esModuleInterop:生成兼容CommonJS模块的代码,让TypeScript能正确处理默认导入allowSyntheticDefaultImports:允许TypeScript对没有默认导出的模块使用默认导入语法
2. 解决TS1056:访问器(get/set)不支持当前编译目标
当前TypeScript的编译目标版本太低,访问器需要ES5及以上版本支持。修改tsconfig.json的target字段:
{ "compilerOptions": { "target": "ES2020", // 也可以设为ES5、ES2017等,根据你Node.js版本选择,推荐用ES2020 // 其他配置不变 } }
3. 解决TS1192:fs/promises无默认导出
fs/promises是ES模块,没有默认导出,改成命名导入或者整体导入:
// 方法1:整体导入 import * as fs from "fs/promises"; // 方法2:按需导入(更推荐) import { readFile, writeFile, mkdir } from "fs/promises";
生产环境编译脚本配置
在package.json里添加编译和启动命令,方便一键构建生产环境代码:
{ "scripts": { "build": "tsc", // 执行TypeScript编译 "start:prod": "node dist/index.js" // 启动编译后的JS代码 } }
同时在tsconfig.json里指定编译输出目录,避免源码和编译后的代码混在一起:
{ "compilerOptions": { "outDir": "./dist", // 编译后的JS文件输出到dist目录 // 其他配置... }, "include": ["src/**/*"], // 只编译src目录下的文件 "exclude": ["node_modules"] // 排除node_modules }
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

