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

从内部npm包导入的常量表达式为何为undefined?

问题

我维护一个内部npm包,用于共享类型和常量,使用TypeScript开发,配置了"target": "ESNext"和"module": "NodeNext"。在包的某个文件中定义并导出了flagCssValues常量:

export type SupportedLocale = 'en-GB' | 'cy';

export const flagCssValues: Record<SupportedLocale, string> = {
  ['en-GB']: 'fi-gb',
  cy: 'fi-gb-wls'
};

发布包后,在项目中通过import { flagCssValues } from '@myorg/myfile';导入该常量,在Jasmine测试中使用时,flagCssValues的值始终为undefined。我也尝试了另一种导出方式:

const flagCssValues: Record<SupportedLocale, string> = {
  ['en-GB']: 'fi-gb',
  cy: 'fi-gb-wls'
};

export { flagCssValues };

结果问题依旧。TypeScript编译生成的JS代码如下:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flagCssValues = void 0;
exports.flagCssValues = {
    ['en-GB']: 'fi-gb',
    cy: 'fi-gb-wls'
};

请问如何正确导出该值?

解决方案

从编译后的JS代码来看,导出语法本身没有问题,问题大概率出在包的发布配置或导入环境的模块解析逻辑上,以下是具体排查和解决方向:

  • 检查package.json的模块入口配置
    由于使用了module: NodeNext,必须确保包的package.json正确配置type字段,并指定对应入口:

    {
      "type": "module",
      "main": "./dist/index.cjs",
      "module": "./dist/index.js",
      "types": "./dist/index.d.ts"
    }
    

    如果只输出ES模块,至少要保证type设为"module",且main指向正确的编译后JS文件。

  • 确认发布包包含编译产物
    检查package.json的files字段,确保编译输出目录(比如dist)被包含在内,避免发布后项目拿到未编译的TS源码,导致模块解析异常。

  • 适配测试环境的模块系统
    若Jasmine默认使用CommonJS模块,而包输出的是ES模块,可通过两种方式解决:

    • 改用CommonJS格式导入:
      const { flagCssValues } = require('@myorg/myfile');
      
    • 配置Jasmine支持ES模块:在Jasmine配置文件中开启esModuleInterop,或在测试文件顶部添加// @ts-nocheck\n"type": "module"注释。
  • 验证TypeScript编译配置
    确保tsconfig.json中设置了"outDir": "./dist"和"declaration": true,让编译后的JS和类型定义文件统一输出到指定目录,保证包的引用路径正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:38:24