You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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需两步配置:

  1. 修改项目根目录的tsconfig.json,在compilerOptions中添加两项配置:
    "resolveJsonModule": true,
    "esModuleInterop": true
    
  2. 直接导入JSON文件即可,示例:
    假设存在config.json文件:
    {
        "port": 3000,
        "secret": "nestjs-demo-secret"
    }
    
    导入代码:
    import * as config from './config.json';
    // 或解构导入需要的字段:import { port, secret } from './config.json';
    

内容的提问来源于stack exchange,提问作者user20181423

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:42:39