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

React JS中.tsx文件转.js文件的解决方案求助

解决方案:将React+TypeScript项目从.tsx迁移到.js文件

步骤1:调整TypeScript配置以支持编译输出

首先修改你的tsconfig.json,让TypeScript能够编译生成对应的JavaScript文件:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false, // 改为false,允许TS编译输出文件
    "outDir": "./dist-temp", // 指定临时编译输出目录
    "jsx": "react-jsx" // 适配React 17+的JSX自动导入规则
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

执行编译命令生成JS文件:
npx tsc

步骤2:批量重命名.tsx文件为.js(或.jsx)

在Ubuntu终端执行以下命令,批量将src目录下的.tsx文件重命名为.js(若遵循React规范,建议改为.jsx,只需替换命令中的.js为.jsx):

find src -name "*.tsx" -exec sh -c 'mv "$0" "${0%.tsx}.js"' {} \;

步骤3:清理TypeScript语法残留

转换后的JS文件中可能存在TS专属语法,需要逐一清理:

  • 删除类型注解:比如const count: number = 0改为const count = 0
  • 移除接口、类型别名:比如interface UserProps { name: string }直接删除,或改用JSDoc注释/** @typedef {Object} UserProps @property {string} name */
  • 替换import type语句:若导入的是值则改为普通import,否则直接删除

步骤4:调整Vite配置为JavaScript格式

将vite.config.ts重命名为vite.config.js,并修改为CommonJS格式(适配你的Node.js 14版本):

const { defineConfig } = require('vite');
const react = require('@vitejs/plugin-react');

module.exports = defineConfig({
  plugins: [react()],
});

若不再需要TypeScript支持,可直接删除tsconfig.node.json。

步骤5:移除TypeScript相关依赖(可选,优化项目体积)

确认不再需要TypeScript后,执行命令卸载相关依赖:

npm uninstall typescript @types/react @types/react-dom

步骤6:验证项目运行与构建

  • 启动开发服务器:npm run dev,检查浏览器页面加载正常且无控制台报错
  • 执行生产构建:npm run build,查看dist目录下产物均为.js文件,且能正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:35:36