【问题标题】:import in react-scripts react-app-env.d.ts breaks tsc build在 react-scripts 中导入 react-app-env.d.ts 会破坏 tsc 构建
【发布时间】:2023-03-18 00:14:01
【问题描述】:

我想在由 react-scripts 生成的文件中导入类型。

我创建了this minimal repo 来显示问题。

到目前为止我有这个:

// import * as React from 'react';
// import { MemoryHistory } from 'history';
// import { RenderResult } from 'react-testing-library';

interface Window {
  env: any;
}

type ContextDefaultValue = [string, (val: string) => void];

/* global function for rendering with Router */
declare function renderWithRouter(ui: any, { route, history, }?: {
  route?: string;
  history?: any;
}): any;

如果我取消注释任何导入语句并运行 tsc,则 renderWithRouter 不再位于全局命名空间中,并且我收到此错误:

找不到名称“renderWithRouter”。

我不能在 .d.ts 文件中导入类型吗?

【问题讨论】:

  • 能否提供一个最小的 github 项目来重现该问题?
  • @Mu-TsunTsai 我创建了这个 repo 来说明问题github.com/dagda1/fooky-types
  • 抱歉,我无法重现您的问题。以下是我采取的步骤: (1) 下载 repo 并使用 VS Code 打开。 (2) 运行npm install。 (3) 运行npm run build。没有错误发生,成功生成“build”文件夹。
  • 运行 tsc build 也不会产生任何错误,只是没有生成任何东西。
  • 来自我发送的链接中的回购?

标签: typescript


【解决方案1】:

向文件添加导入使其成为模块。所以在一个模块中,如果你声明一个接口Window,它就被声明为该模块的本地。

如果您想使用导入,但仍保持全局声明,您有两种选择:

使用declare global

import * as React from 'react';
import { History } from 'history';
import { RenderResult } from 'react-testing-library';

declare global {
  interface Window {
    env: any;
  }

  declare function renderWithRouter(ui: any, { route, history, }?: {
    route?: string;
    history?: History;
  }): RenderResult;
}

使用import 类型

interface Window {
  env: any;
}

declare function renderWithRouter(ui: any, { route, history, }?: {
  route?: string;
  history?: import('history').History;
}): import('react-testing-library').RenderResult;

任何一个版本都可以,如果您使用来自其他模块的大量类型,declare global 会更容易。

【讨论】:

    【解决方案2】:

    如果你看typescript的官方文档,工作逻辑(包括这个错误)和它的结构解释的很清楚。 1, 2

    从模块导入

    您一开始可能会遇到一堆错误,例如 Cannot find name 'require'.Cannot find name 'define'.. 在这些情况下,您很可能正在使用模块。虽然你可以通过写出让 TypeScript 相信这些存在

    // 对于 Node/CommonJS

    declare function require(path: string): any;
    

    // 对于 RequireJS/AMD

    declare function define(...args: any[]): any;
    

    最好摆脱这些调用并使用 TypeScript 语法进行导入。

    首先,您需要通过设置 TypeScript 的模块标志来启用一些模块系统。有效选项为 commonjsamdsystemumd

    如果你有以下 Node/CommonJS 代码:

    var foo = require("foo");
    
    foo.doStuff();
    

    或以下 RequireJS/AMD 代码:

    define(["foo"], function(foo) {
        foo.doStuff();
    })
    

    那么您将编写以下 TypeScript 代码:

    import foo = require("foo");
    
    foo.doStuff();
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2019-04-30
      • 1970-01-01
      • 2021-07-19
      • 2019-02-10
      • 1970-01-01
      • 2022-12-29
      • 1970-01-01
      • 2018-12-13
      相关资源
      最近更新 更多