【问题标题】:What is the correct way to import a file in typescript?在打字稿中导入文件的正确方法是什么?
【发布时间】:2019-04-25 12:33:07
【问题描述】:

过去导入 javascript 文件时,您将文件命名为 index.js,然后像这样导入

import something from 'components/path/something' 其中最后的内容是包含index.js 文件的目录

但是在使用 TS 时,我收到一条错误消息:当我将文件名切换为 index.ts 时没有文件或目录

目前有2个解决方案import something from 'components/path/something/index.ts'

import something from 'components/path/something/something'

两者都不是超级粉丝,有更好的方法吗?

【问题讨论】:

标签: javascript reactjs typescript import


【解决方案1】:

没有正确的方法:

进口通常是相对的:

import whatever from '../another/folder/'; // will import index

当然你可以在 tsconfig.json 中调整这种行为:

{
  ....
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@services/*": ["services/*"],
      "@shared/*": ["shared/*"],
      "@models/*": ["models/*"],
    },
    ...
  }
}

为您提供“绝对项目路径”:

import WhateverService from '@services/WhateverService';

https://www.typescriptlang.org/docs/handbook/modules.html

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多