简体   繁体   English

将 typescript 模块导入 React 应用程序中的 JS 模块

[英]Importing a typescript module to a JS module in a React app

I have a React app created with create-react-app.我有一个用 create-react-app 创建的 React 应用程序。 Recently I've added some source code for a module I need.最近我为我需要的模块添加了一些源代码。 It's in Typescript and will stay in Typescript.它在打字稿中,并将留在打字稿中。 Not my choice.不是我的选择。 I've installed what I needed to build Typescript and that part seems to work OK.我已经安装了构建 Typescript 所需的东西,这部分似乎工作正常。

However, when I try importing that TS module to my regular jsx, it says module not found .但是,当我尝试将该 TS 模块导入到我的常规 jsx 时,它说module not found

To illustrate:为了显示:

shared/
    - MyTSModule/
        - index.tsx
    - OtherModule/
        - index.jsx
view/
    - MyView/
        - index.jsx

I'm trying to import MyTSModule to MyView .我正在尝试将MyTSModule导入MyView The error is: Module not found: Error: Can't resolve 'shared/MyTSModule' in...错误是: Module not found: Error: Can't resolve 'shared/MyTSModule' in...

I'm importing like all the other modules from shared :我像所有其他模块一样从shared导入:

import MyTSModule from 'shared/MyTSModule ';

What am I missing?我错过了什么?

You cannot import typescript file from javascript.您不能从 javascript 导入打字稿文件。 You either need to:您要么需要:

  1. compile typescript to javascript and then import compiled file将打字稿编译为 javascript,然后导入编译后的文件
  2. convert your javascript files to typescript.将您的 javascript 文件转换为打字稿。

I personally recommend porting all files to typescript, this way you will have more type safety.我个人建议将所有文件移植到打字稿,这样你将有更多的类型安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM