在NestJS中导入.ts及.json文件的问题求助
解决NestJS中"constants.ts is not a module"错误及JSON文件导入方法
解决constants.ts模块错误
你当前用的是Node.js的CommonJS导出语法(module.exports),但NestJS基于TypeScript,默认采用ES模块/TS原生模块系统,因此会识别不了该文件为合法模块。
直接改用TS原生导出语法即可,两种常用写法:
- 方式一:单独导出ROLES常量
对应导入方式:export const ROLES = { ADMIN: 'admin', LOCAL: 'local' };import { ROLES } from '../lib/constants'; - 方式二:导出完整常量集合(和你原结构更匹配)
对应导入方式(可沿用你原来的写法):export const constants = { ROLES: { ADMIN: 'admin', LOCAL: 'local' } };import * as constants from '../lib/constants'; // 或直接解构导入:import { constants } from '../lib/constants';
导入JSON文件的方法
在NestJS/TypeScript中导入JSON需两步配置:
- 修改项目根目录的
tsconfig.json,在compilerOptions中添加两项配置:"resolveJsonModule": true, "esModuleInterop": true - 直接导入JSON文件即可,示例:
假设存在config.json文件:
导入代码:{ "port": 3000, "secret": "nestjs-demo-secret" }import * as config from './config.json'; // 或解构导入需要的字段:import { port, secret } from './config.json';
内容的提问来源于stack exchange,提问作者user20181423
相关产品推荐
相关产品推荐

