在 TypeScript 和 Next.js 中解析具有绝对导入的模块

Lan*_*nce 6 typescript webpack next.js

我一直在尝试消除当我使用绝对导入从文件导入函数时不断出现的一些错误。我得到的错误如下所示。 在此输入图像描述

函数确实是导入的,可以正常使用。然而,每当使用绝对路径导入某些内容时,我的打字稿配置都会使 VS code 抛出类似的错误。我的理解是,从 Next.js 版本 9 开始,typescript 就得到了开箱即用的支持,而无需做太多额外的工作。

我的 tsconfig.json 文件

{
"compilerOptions": {
"target": "esnext",
"lib": [
  "dom",
  "dom.iterable",
  "esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"strictNullChecks": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"sourceMap": true,
"baseUrl": ".",
"paths": {
  "@actions/*": [
    "redux/actions/*"
  ],
  "@components/*": [
    "./components/*"
  ],
  "@controllers/*": [
    "controllers/*"
  ],
  "@interfaces/*": [
    "interfaces/*"
  ],
  "@layouts/*": [
    "layouts/*"
  ],
  "@lib/*": [
    "lib/*"
  ],
  "@models/*": [
    "models/*"
  ],
  "@options/*": [
    "options/*"
  ],
  "@public/*": [
    "public/*"
  ],
  "@reducers/*": [
    "redux/reducers/*"
  ],
  "@redux/*": [
    "redux/*"
  ],
  "@static/*": [
    "static/*"
  ],
  "@store/*": [
    "./store/*"
  ],
  "@style": [
    "style/*"
  ],
  "@utils": [
    "utils/*"
  ],
  "@dummy/*": [
    "__dummy__/*"
  ]
}
},
"exclude": [
  "node_modules"
],
"include": [
  "next-env.d.ts",
  "**/*.ts",
  "**/*.tsx"
]
}
Run Code Online (Sandbox Code Playgroud)

我的 next.config.js 文件

/* eslint-disable */
const withPlugins = require("next-compose-plugins")
const withFonts = require("next-fonts")
const withImages = require("next-images")
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin")
/* eslint-enable */

module.exports = withPlugins([[withFonts], [withImages]], {
webpack: (config) => {
    if (config.resolve.plugins) {
        config.resolve.plugins.push(new TsconfigPathsPlugin())
    } else {
        config.resolve.plugins = [new TsconfigPathsPlugin()]
    }

    config.resolve.extensions.push(".ts", ".tsx")
    return config
}
})
Run Code Online (Sandbox Code Playgroud)

Nik*_*lev 0

如果您使用 Next.js 9.4,您可以删除tsconfig-paths-webpack-plugin插件。

绝对导入和别名