【问题标题】:Next.js typescript import aliases with babel-plugin-module-resolverNext.js typescript 使用 babel-plugin-module-resolver 导入别名
【发布时间】:2020-07-29 03:41:19
【问题描述】:

我正在使用 typescript 设置 Next.js 项目。我一直在关注几个指南,但我似乎遇到了导入别名的问题。

我不确定这是我的配置问题还是 Next.js 的问题。

这里有几页引用了类似的问题,但我没有成功地遵循这些问题:

我尝试使用 Next.js 的 webpack 配置来解决问题(将 resolve.alias 选项直接添加到 next.config.js,但这没有帮助,而且 Next.js 现在应该支持开箱即用的 typescript (resolve.extensions 定义明确)

Next.js 版本 9.3.5

babel-plugin-module-resolver 版本 4.0.0

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "baseUrl": ".",
    "paths": {
      "@components/*": ["./components/*"],
      "@icons/*": ["./assets/icons/*"],
      "@views/*": ["./views/*"]
    }
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

.babelrc

{
  "presets": [ "next/babel" ],
  "plugins": [
    "inline-react-svg",
    ["module-resolver", {
      "root": ["./"],
      "alias": {
        "@components": "./components",
        "@icons": "./assets/icons",
        "@views": "./views"
      }
    }]
  ]
}

【问题讨论】:

标签: typescript import next.js babel-plugin


【解决方案1】:

在考虑了更多之后,我意识到我正在尝试做两件事:

  • 处理打字稿别名
  • 使用 babel-plugin-inline-react-svg 导入 SVGS

提供的配置实际上适用于常规 typescript 导入,但是此配置不允许 svg 导入为别名,我尝试将扩展添加到模块解析器,但没有成功。

在做了更多研究后,我发现 babel-plugin-inline-react-svg 正在解决一个未解决的问题: https://github.com/airbnb/babel-plugin-inline-react-svg/pull/17

这似乎是 babel-plugin-module-resolver 和 babel-plugin-inline-react-svg 之间已知的兼容性问题。

【讨论】:

  • 我不知道,实际上我只是自己将我的 svg 转换为组件。
猜你喜欢
  • 2019-04-06
  • 2019-07-18
  • 2020-09-08
  • 2019-05-19
  • 2019-04-01
  • 1970-01-01
  • 2020-07-07
  • 2019-05-02
  • 1970-01-01
相关资源
最近更新 更多