从 Next.JS 上的绝对路径导入内联 SVG

Lea*_*rso 6 svg typescript eslint babeljs next.js

我在配置 Next.Js 以绝对方式进行导入时遇到困难。

\n

我使用baseUrl作为“src”配置了tsconfig.json,它甚至可以工作,但内联 SVG 文件除外。我正在使用“inline-react-svg”,如果您导入相对路径,它就可以工作,但完全忽略我配置的绝对路径。无论导入是否有效,Eslint都会给出错误。这是代码:

\n

首先,我的结构如下所示:

\n
\n
    \n
  • 源\n
      \n
    • 资产
    • \n
    • 页面
    • \n
    • 风格
    • \n
    \n
  • \n
\n
\n

tsconfig.json

\n
{\n  "compilerOptions": {\n    "target": "es5",\n    "lib": [\n      "dom",\n      "dom.iterable",\n      "esnext"\n    ],\n    "allowJs": true,\n    "skipLibCheck": true,\n    "strict": false,\n    "forceConsistentCasingInFileNames": true,\n    "noEmit": true,\n    "esModuleInterop": true,\n    "module": "esnext",\n    "moduleResolution": "node",\n    "resolveJsonModule": true,\n    "isolatedModules": true,\n    "jsx": "preserve",\n    "baseUrl": "./src",\n  },\n  "include": [\n    "next-env.d.ts",\n    "**/*.ts",\n    "**/*.tsx",\n  ],\n  "exclude": [\n    "node_modules",\n  ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n

babel.config.js

\n
module.exports = {\n  "presets": ["next/babel"],\n  "plugins": [\n    ["styled-components", { "ssr": true }],\n    "inline-react-svg"\n  ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n

.eslintrc.json

\n
{\n  "env": {\n    "browser": true,\n    "es2021": true,\n    "node": true,\n    "jest": true\n  },\n  "extends": [\n    "plugin:react/recommended",\n    "standard",\n    "plugin:@typescript-eslint/recommended",\n    "prettier/@typescript-eslint",\n    "prettier/standard",\n    "prettier/react"\n  ],\n  "parser": "@typescript-eslint/parser",\n  "parserOptions": {\n    "ecmaFeatures": {\n      "jsx": true\n    },\n    "ecmaVersion": 12,\n    "sourceType": "module"\n  },\n  "plugins": [\n    "react",\n    "@typescript-eslint",\n    "prettier"\n  ],\n  "rules": {\n    "prettier/prettier": "error",\n    "space-before-function-paren": "off",\n    "react/prop-types": "off",\n    "react/react-in-jsx-scope": "off"\n\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

例子:

\n

在文件“./src/pages/_app.tsx”中,它完全按照预期导入主题(theme.ts)和样式组件的GlobalStyles :

\n

src/pages/_app.tsx

\n
import GlobalStyle from 'styles/global'\nimport theme from 'styles/theme'\n
Run Code Online (Sandbox Code Playgroud)\n

检查它是否不需要返回带有'../'的文件夹,但在index.tsx中它仅相对导入 SVG。

\n

src/pages/index.tsx

\n
import Logo from '../assets/logo.svg' /* assim funciona */\nimport Logo from 'assets/logo.svg' /* assim n\xc3\xa3o funciona */\n
Run Code Online (Sandbox Code Playgroud)\n

完后还有!无论它是否有效,Eslint 都会显示一条错误消息,指出文件不存在或类型未定义,这会让您很恼火。

\n
\n

找不到模块“../assets/logo.svg”或其相应的类型声明.ts(2307)

\n
\n

好吧,我正在使用Next.JS 10.0.5'next-images'。我认为它为所有图像文件添加了打字功能,包括SVG。我对吗?我必须进行什么配置才能发生此错误并能够绝对内联导入 SVG?

\n