![](/img/trans.png)
[英]Can i import the SVG file as a react component with dynamic import() Expressions?
[英]Why IDE shows me error when I import SVG file to use as React component?
我正在嘗試使用 SVG 圖標作為帶有svgr
的 React 組件
一切正常。 我可以將 SVG 和 svgr 完美地轉換為 ReactComponents。
但是,當我像下面這樣導入 svg 時,我的 IDE webstorm 仍然顯示錯誤
我也在使用 typescript 和 nextjs。
什么是真正的問題? 是否僅由 IDE 引起? 或者我應該設置其他選項嗎?
這是我的配置文件
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": "src/"
},
"exclude": [
"node_modules"
],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.svg"
]
}
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
config.module.rules.push({
test: /\.svg$/,
use: [{
loader: '@svgr/webpack',
options: {
svgoConfig: {
plugins: {
removeViewBox: false
}
}
}
}],
})
return config
},
webpackDevMiddleware: (config) => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config
},
}
並且沒有 babelrc,因為我使用的是 nextjs 給出的默認 babel 設置。
提前致謝
我自己找的。 它是由 typescript 引起的。 我必須為.svg
聲明類型
我在根目錄下創建了 typing.d.ts 文件
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
IDE 不再顯示錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.