WebStorm和Typescript争夺Node16模块解析绝对导入

ztmd8pv5  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(218)

为了使用true-myth包,我需要切换到Node16模块分辨率,这在WebStorm中似乎不稳定,或者可能我做错了什么。
无论我使用什么样式的导入,似乎都会产生错误:
这两个错误都是由WebStorm产生的:

// TS2307: Cannot find module '@/utils/helpers' or its corresponding type declarations.
import { classNames } from "@/utils/helpers";
// TS2691: An import path cannot end with a '.ts' extension. Consider importing '@/utils/helpers.js' instead.
import { classNames } from "@/utils/helpers.ts";

当我使用.js时,错误来自应用程序构建系统/开发模式,而不是WebStorm产生错误。

// error - ./src/pages/index.tsx:13:0
// Module not found: Can't resolve '@/utils/helpers.js'
import { classNames } from "@/utils/helpers.js";

当我切换回"moduleResolution": "node"时,所有这些导入都消失了。
短型tsconfig.jsonfull

{
  "compilerOptions": {
    "target": "es2020",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "module": "esnext",
    "moduleResolution": "Node16",
    "baseUrl": "./src/",
    "paths": {
      "@/*": [
        "./*"
      ]
    },
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
  ]
}

对于某些规范,这是一个Next.js项目,具有以下版本:

  • Windows专业版10.0.19045内部版本号19045
  • 网络 Storm 2022.3.2
  • typescript 4.9.5
  • Yarn1.22.19
  • 下一个13.1.1
  • 节点v18.15.0和节点v16.19.1(使用nvm-windows管理)
cngwdvgl

cngwdvgl1#

这是您的tsconfig.json和typescript@4.9.5所预期的,当在终端中运行tsc -p .时,您将看到相同的问题。

  • 无延期进口:
>tsc -p .
src/app.ts:1:22 - error TS2307: Cannot find module '@/utils/helpers/foo' or its corresponding type declarations.

1 import {helper} from '@/utils/helpers/foo';
                       ~~~~~~~~~~~~~~~~~~~~~
  • 使用.ts扩展名:
>tsc -p .
src/app.ts:1:22 - error TS2691: An import path cannot end with a '.ts' extension. Consider importing '@/utils/helpers/foo.js' instead.

1 import {helper} from '@/utils/helpers/foo.ts';
                       ~~~~~~~~~~~~~~~~~~~~~~~~

第一个问题的发生是因为当“--moduleResolution”是“node 16”或“nodenext”时需要显式扩展,请参见https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#esm-nodejs;由于仅在typescript@5之后才支持在导入中使用.ts扩展,因此抛出后者,请参见https://github.com/microsoft/TypeScript/issues/37582

相关问题