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

设置type为module后,Vue预构建TS脚本无法导入package.json

问题:设置type:module后,TypeScript预构建脚本无法导入package.json

此前功能正常,将package.json中的type设为module后,用于写入版本号到.env的预构建脚本出现异常。

预构建脚本代码(prebuild.ts)

// Adds the version as an environment variable
import { existsSync, readFileSync, writeFileSync } from 'fs';

import { version } from './package.json';

const versionVariable = 'VITE_APP_VERSION = ';
const versionRegExp = new RegExp(`^${versionVariable}.*$`, 'gm');

let envContent = existsSync(".env") ? readFileSync(".env", 'utf-8') : '';

if (envContent.match(versionRegExp)) {
  envContent = envContent.replace(versionRegExp, `${versionVariable}${version}`);
} else {
  envContent += `\n${versionVariable}${version}`;
}

writeFileSync(".env", envContent);

运行报错

Cannot find module './package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.

当前配置

tsconfig.json

{
  "files": [],
  "compilerOptions": {
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
  },
  "references": [
    {
      "path": "./tsconfig.node.json"
    },
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ]
}

package.json相关片段

{
  "type": "module",
  "scripts": {
    ...
    "build": "run-p type-check build-only",
    "prebuild": "tsc prebuild.ts && node prebuild.js && rm prebuild.js"
  }
  ...
}

解决方法

核心原因

  1. 根目录的tsconfig.json是项目引用型配置(files为空,仅包含references),直接用tsc prebuild.ts编译时,不会自动应用该配置里的resolveJsonModule。
  2. 启用type:module后,Node.js的ES模块规则对JSON导入有额外限制,即使TypeScript编译通过,运行时仍可能报错。

方案1:编译时强制启用resolveJsonModule

修改package.json中的prebuild脚本,在tsc命令中直接指定参数:

"prebuild": "tsc prebuild.ts --resolveJsonModule && node prebuild.js && rm prebuild.js"

这种方式简单直接,确保编译prebuild.ts时启用JSON模块解析。

方案2:使用ES标准的JSON导入断言

调整prebuild.ts中的导入语句为ES模块兼容的断言语法:

import pkg from './package.json' assert { type: 'json' };
const { version } = pkg;

注意:Node.js 17.1+支持该语法,同时需要TypeScript 4.5+版本配合。

方案3:单独给预构建脚本配置tsconfig

新建tsconfig.prebuild.json文件:

{
  "compilerOptions": {
    "strict": true,
    "resolveJsonModule": true,
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020"
  },
  "include": ["prebuild.ts"]
}

修改prebuild脚本使用该配置:

"prebuild": "tsc -p tsconfig.prebuild.json && node prebuild.js && rm prebuild.js"

这种方式让预构建脚本拥有独立的、生效的TypeScript配置,避免和项目其他配置冲突。

方案4:直接读取解析package.json文件

绕开模块导入的限制,用fs读取文件后手动解析:

import { existsSync, readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';

// 读取并解析package.json
const pkgPath = resolve(process.cwd(), 'package.json');
const pkgContent = readFileSync(pkgPath, 'utf-8');
const { version } = JSON.parse(pkgContent);

// 后续逻辑不变...

这种方式兼容性最好,不受ES模块或TypeScript配置的影响。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:59:51