【问题标题】:Typescript [React] not converting .tsx imports to .jsx importsTypescript [React] 未将 .tsx 导入转换为 .jsx 导入
【发布时间】:2016-09-25 21:50:57
【问题描述】:

我将 typescript react 组件保存在不同的文件中,所以我使用以下语句来导入我的子组件。

//app.tsx

import {SideBar} from "./sidebar"

但是当 typescript 将 app.tsx 编译为 app.jsx 时,import 语句会切换到 require("sidebar")。我在 javascript 上遇到错误,因为 require 语句需要具有“sidebar.jsx”和“.jsx”扩展名。有没有办法让我自动化?

我的 tsconfig 设置是:

{
    "compilerOptions": {
        "jsx": "preserve",
        "target": "ES5",
        "noImplicitAny":false,
		"module": "commonjs",
        
    }
}

也许我需要在 tsconfig 文件中添加一些内容?

提前致谢。

【问题讨论】:

  • 也许将所有.tsx 文件完全放在一个单独的文件夹中?

标签: javascript reactjs typescript


【解决方案1】:

选项 1

我在 javascript 上遇到错误,因为 require 语句需要具有“sidebar.jsx”和“.jsx”扩展名。

修复此错误,例如如果您使用的是 webpack,您可以添加 .jsx 作为可解析路径。

resolve: {
  // Add `.jsx` as a resolvable extension.
  extensions: ['', '.webpack.js', '.web.js', '.jsx']
},

如果是这样,甚至可以使用 ts-loader : https://github.com/TypeStrong/ts-loader 而不是 jsx: preserve 而是 jsx: react。更多:https://basarat.gitbooks.io/typescript/content/docs/jsx/tsx.html

选项 2

使用module: es6 代替"module": "commonjs",,打字稿不会将import 重写为require

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2019-07-22
    • 2016-12-01
    • 2016-09-27
    • 2017-05-14
    • 1970-01-01
    • 2018-04-29
    • 2022-01-01
    • 2017-11-03
    相关资源
    最近更新 更多