Webpack无法打包TypeScript代码

5

我遇到了打包TS项目的问题。看起来ts-loader不能识别TypeScript语法。

我收到的错误信息:

ERROR in ./src/common/components/chat/chatComponent.tsx
Module parse failed: The keyword 'interface' is reserved (10:0)
You may need an appropriate loader to handle this file type.
| import { ChatItemComponent, ChatMessageItem, isMessage, Props as Item } from "./chatItem";
|
| interface Props {
|   className?: string;
|   fullHistoryFetched?: boolean;

并且

ERROR in ./src/common/closer.tsx
Module parse failed: Unexpected token (10:13)
You may need an appropriate loader to handle this file type.
| import * as chatItem from "./components/chat/chatItem";
| import * as chatItemStyles from "./components/chat/chatItem.css";
| import Timer = NodeJS.Timer;
| import { ImageComponent } from "./components/image/image";
| import { InitialsAvatar } from "./components/initialsAvatar";

以下是我的 webpack.config.js:

const webpack = require('webpack');
const path = require('path');

module.exports = {
    mode: "development",
    devtool: "inline-source-map",
    entry: {
        index: './src/agent/index.tsx',
        preloader: './src/agent/preloader.js',
    },
    target: 'web',
    output: {
        path: path.resolve(__dirname, 'dist/agent'),
        filename: '[name].js',
        publicPath: '/dist/agent/'
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)?$/,
                include: path.resolve(__dirname, 'src/agent'),
                use: [
                    {
                        loader: 'ts-loader'
                    }
                ]
            },
            ...
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']
    }
};

以下是我的tsconfig.json文件:

{
  "buildOnSave": false,
  "compileOnSave": false,
  "compilerOptions": {
    "alwaysStrict": true,
    "experimentalDecorators": true,
    "jsx": "react",
    "module": "commonjs",
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "pretty": true,
    "removeComments": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "lib": [
      "es2015",
      "dom"
    ],
    "types": [
      "jasmine",
      "node",
      "react"
    ]
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

我使用的版本是:"typescript": "2.5.3""ts-loader": "4.0.1""webpack": "^4.1.1"。
我是否漏掉了什么?在我的tsconfig.json文件中,我将源代码的目标生成为ES5,所以根据我的知识,我不需要使用babel。

我认为这是一个版本问题 https://github.com/TypeStrong/ts-loader/releases/tag/v4.0.0 - lukas-reineke
1
嘿@lukas-reineke。我希望是这样的。不幸的是,所有版本都匹配。我使用webpack 4。 - Petr Shypila
1个回答

5
include是个问题。你只限制了ts-loadersrc/agent文件夹中运行。但错误却出现在src/common文件夹中的一个文件上。
include也可以是一个数组,将包含typescript文件的每个文件夹都传入即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接