代码之家  ›  专栏  ›  技术社区  ›  Turnipdabeets

TS将不同类型的文件导入到单个index.d.TS文件中

  •  0
  • Turnipdabeets  · 技术社区  · 7 年前

    我想将组件类型分为单独的组件类型 index.d.ts 然后将这些类型导入到最终版本中 索引d.ts 索引d.ts 没有得到错误 [ts] Import or export declaration in an ambient module declaration cannot reference module through relative module name.

    文件夹:

    src
     |__components  
     |  |__Text  
     |     |__index.js
     |     |__index.d.ts
     |  |__Button
     |     |__index.js
     |     |__index.d.ts
     |__index.js
     |__index.d.js
    

    src/index.d.ts

    declare module "my-module-name" { 
      export { default as Text } from "./components/Text/index.d.ts";
    }
    

    src/index.js

    export { default as Text } from "./components/Text";
    export { default as Button } from "./components/Button";
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Karol Majewski    7 年前

    你不需要使用 declare module . 相对路径在那个里无论如何都不起作用,它们只能在模块中使用 增强

    首先在各自的文件夹中声明组件。我过去只是 React.ComponentType ,但你可以更具体一些。

    ./src/components/Button/index.d.ts

    import * as React from 'react';
    
    declare const Button: React.ComponentType;
    
    export default Button;
    

    ./src/components/Text/index.d.ts

    import * as React from 'react';
    
    declare const Text: React.ComponentType;
    
    export default Text;
    

    桶锉

    ./src/index.d.ts

    export { default as Text } from './components/Text'
    export { default as Button } from './components/Button'
    

    现在您的组件可以从这两个站点访问 ./src 和从各自的文件夹中。如果我们创建了另一个名为 consumer

    ./consumer/index.ts

    /**
     * Import the re-exported components from `./src/index.d.ts`:
     */
    import { Button } from '../src/';
    
    /**
     * Or import from their respective folders:
     */
    import Text from '../src/components/Text';
    

    请记住,以这种方式解析路径需要设置 "moduleResolution" "node" 在你的 tsconfig.json .

    {
      "compilerOptions": {
        "baseUrl": ".",
        "moduleResolution": "node"
      }
    }
    
    推荐文章