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

使用Webpack构建React应用生成bundle.js时遇ts-loader编译错误

Webpack打包React+TypeScript应用时ts-loader构建错误排查

我尝试用Webpack将React+TypeScript应用打包为bundle.js文件,构建时触发以下错误:

ERROR in ./src/index.tsx Module build failed (from ./node_modules/ts-loader/index.js)

我的Webpack配置代码如下:

const path = require('path');

module.exports = {
    mode: 'development',
    devtool: 'inline-source-map',
    entry: './src/index.tsx', // 应用入口
    output: {
        path: path.resolve(__dirname, 'dist'), // 输出目录
        filename: 'bundle.js', // 输出文件名
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.css$/, // 处理CSS文件的规则
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.svg$/, // 处理SVG文件的规则
                use: ['@svgr/webpack'],
            },
            {
                test: /\.(png|jpe?g|gif)$/i,
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
        ],
    },
    
    resolve: {
        extensions: ['.ts', '.tsx'],
    },
};

错误截图:
错误截图

排查与解决步骤

  1. 检查TypeScript配置文件
    确保项目根目录存在tsconfig.json,并配置React相关编译选项,基础配置示例:
{
  "compilerOptions": {
    "target": "ES5",
    "module": "ESNext",
    "jsx": "react",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]
}
  1. 确认依赖安装完整
    执行以下命令安装所有必要的开发依赖:
npm install --save-dev typescript ts-loader webpack webpack-cli react react-dom @types/react @types/react-dom style-loader css-loader @svgr/webpack file-loader
  1. 完善Webpack的扩展名解析
    当前resolve配置仅支持.ts、.tsx,补充.js、.jsx避免模块解析失败:
resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
  1. 检查入口文件语法
    确认src/index.tsx不存在TypeScript语法错误,比如未声明的变量、不符合TS规范的JSX写法等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:42:05