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

Windows下构建后Index.js引用.tsx文件问题求助

解决Windows下Rollup构建后引用未编译.tsx文件的问题

看起来你遇到的是Windows文件系统与Rollup/TypeScript插件交互时的路径/扩展名解析差异问题——在Linux/macOS上,工具链能正确将.tsx导入替换为编译后的.js文件,但Windows下由于大小写不敏感或插件配置的细微差异,导致build目录里的index.js仍然引用原始的.tsx路径,自然找不到对应的文件。

下面是一步步的排查和解决方法,即使你没使用过Rollup也能跟着操作:

1. 先单独验证TypeScript编译是否正常

首先排除TypeScript本身的问题:

  • 运行命令 tsc(确保全局安装了TypeScript,或者用npx tsc)
  • 查看build目录,确认是否生成了Calendar.js和Calendar.d.ts文件
    • 如果没有,打开tsconfig.json检查:
      • include字段是否包含了Calendar.tsx所在的目录(比如"src/**/*")
      • outDir是否设置为"./build",确保编译产物输出到正确位置

2. 检查Rollup配置文件(rollup.config.js)

Rollup需要正确配置TypeScript插件来处理.tsx文件,并替换导入路径。修改你的配置如下:

import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

// 检测当前是否为Windows环境
const isWindows = process.platform === 'win32';

export default {
  input: 'src/index.ts', // 确保入口文件正确
  output: {
    dir: 'build',
    format: 'cjs', // 对应你的项目模块格式,比如cjs或esm
    sourcemap: true,
  },
  plugins: [
    // 解析模块路径,强制包含.tsx扩展名
    resolve({
      extensions: ['.ts', '.tsx', '.js', '.jsx'],
      preferBuiltins: false,
    }),
    // 处理CommonJS模块
    commonjs(),
    // 配置TypeScript编译
    typescript({
      tsconfig: './tsconfig.json',
      // 明确指定要编译的文件类型
      include: ['**/*.ts', '**/*.tsx'],
      // 针对Windows的额外配置,确保输出正确的扩展名
      tsconfigOverride: {
        compilerOptions: {
          outDir: 'build',
          jsx: 'react', // 根据你的React版本调整,比如'react-jsx'
          target: 'ES6',
          module: 'ESNext',
        },
      },
    }),
  ],
};

3. 添加干净的构建脚本

Windows下旧的build文件可能残留导致问题,在package.json里添加清理+构建的脚本:

"scripts": {
  "clean": "rm -rf build || rd /s /q build",
  "build": "npm run clean && rollup -c"
}
  • rm -rf build适配Linux/macOS,rd /s /q build适配Windows,确保每次构建前清空旧产物

4. (可选)强制替换导入路径

如果上述步骤后仍然存在问题,可以添加@rollup/plugin-replace插件,强制将.tsx导入替换为.js:

  1. 安装插件:npm install @rollup/plugin-replace --save-dev
  2. 在Rollup配置里添加:
import replace from '@rollup/plugin-replace';

// ... 在plugins数组里添加
replace({
  './Calendar.tsx': './Calendar.js',
  preventAssignment: true,
}),

为什么Linux/macOS正常?

Linux/macOS的文件系统是大小写敏感的,工具链在处理导入路径时会更严格地替换扩展名;而Windows的大小写不敏感特性可能让Rollup/TypeScript插件在路径解析时跳过了扩展名替换步骤,导致最终产物里仍然保留.tsx的引用。

按照这些步骤调整后,重新运行npm run build,应该就能解决Unable to resolve module './Calendar.tsx'的报错了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:22:59