【问题标题】:Resolving modules with absolute imports in TypeScript and Next.js在 TypeScript 和 Next.js 中使用绝对导入解析模块
【发布时间】:2020-10-18 05:04:36
【问题描述】:

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

函数实际上是导入的,可以正常使用。但是,每当使用绝对路径导入某些内容时,我的 typescript 配置都会使 VS 代码抛出类似的错误。我的理解是,从 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"
]
}

我的 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
}
})

【问题讨论】:

    标签: typescript webpack next.js


    【解决方案1】:

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

    Absolute Imports and Aliases

    【讨论】:

      【解决方案2】:

      你只需要使用@/name:

      import name from '@/name'
      

      【讨论】:

        猜你喜欢
        • 2015-08-07
        • 2023-04-02
        • 2022-06-13
        • 1970-01-01
        • 2023-04-07
        • 2017-07-10
        • 1970-01-01
        • 2014-05-27
        • 2020-07-28
        相关资源
        最近更新 更多