【问题标题】:How can I resolve tsx file in Angular 2 / Angular - Cli如何在 Angular 2 / Angular - Cli 中解析 tsx 文件
【发布时间】:2017-06-07 08:55:16
【问题描述】:

我有一个 .tsx 文件并将其导入到一个 ts 文件中

import {ReactChildComponentView} from "./MessageBox";

但是当我运行 ng serve 时它会抛出一个错误

    ERROR in ./src/app/react/wrapper.component.ts
    Module not found: Error: Can't resolve './MessageBox' in '.../src/app/react'

在 Chrome 控制台中我可以看到以下错误

using description file: .../package.json (relative path: ./src/app/react/MessageBox)
  as directory
    .../src/app/react/MessageBox doesn't exist
  no extension
    .../src/app/react/MessageBox doesn't exist
  .ts
    .../src/app/react/MessageBox.ts doesn't exist
  .js
    .../src/app/react/MessageBox.js doesn't exist

似乎 Angular 不查找 .tsx 文件。我该如何改变呢?

【问题讨论】:

    标签: angular typescript webpack angular-cli


    【解决方案1】:

    首先,您需要确保您已配置 webpack 以通过在 webpack 配置中添加 .tsx in resolve.extensions 来查找具有 .tsx 扩展名的文件:

    resolve: {
        extensions: [
            '.js',
            '.ts',
            '.tsx'
        ]
    }
    

    然后,您需要通过在 webpack 配置中的 module.loaders 中为 ts 加载器设置 test: /\.tsx$/ 来配置 typescript 加载器以查找 .tsx 文件:

    module: {
        loaders: [
          {
            test: /\.tsx$/,
            exclude: /node_modules|typings/,
            loaders: [
              'ts'
            ]
          },
        // More loaders
       ]
    }
    

    您还可以在 Typescript Handbook 找到有关 webpack 和 react 集成的更多信息

    【讨论】:

    • 我不得不在 Webpack 5.5.1 中进行一些更改:在 module.rules 节点下,我修改了一个现有的加载器并让它使用 ts 使用的 @ngtools/webpack 加载器:{“test”:/ \.tsx?$/, "loader": "@ngtools/webpack" },此外,您可能需要修改 tsconfig.json 以在 compilerOptions 下包含` "jsx" : "react"`
    • 它给了我一个错误提示“意外的令牌您可能需要适当的加载程序来处理此文件类型。”
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 2023-04-03
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 2023-04-09
    • 2018-03-16
    • 2017-03-07
    相关资源
    最近更新 更多