next.js SVG下一个错误您可能需要一个适当的加载器来处理此文件类型,目前没有加载器配置为处理此文件

avwztpqn  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(107)

我有一个问题,我的应用程序,一切都工作正常,直到我运行npm运行审计修复力,然后当我运行我的应用程序后,我得到下面的错误消息相关的svg文件。
您可能需要一个适当的加载器来处理此文件类型,目前没有配置加载器来处理此文件。我不明白出了什么问题。
有人能帮帮我吗
package.json

  1. {
  2. "name": "myskillreactapp",
  3. "version": "0.1.0",
  4. "private": true,
  5. "scripts": {
  6. "dev": "next dev",
  7. "build": "next build",
  8. "start": "next start",
  9. "lint": "next lint"
  10. },
  11. "dependencies": {
  12. "@babel/preset-env": "^7.15.8",
  13. "bootstrap": "^5.0.0-beta3",
  14. "bootstrap-dark-5": "^1.1.3",
  15. "font-awesome": "^4.7.0",
  16. "next": "^10.0.4",
  17. "next-images": "^1.8.1",
  18. "react": "17.0.2",
  19. "react-dom": "17.0.2",
  20. "react-icons": "^4.3.1",
  21. "react-placeholder": "^4.1.0"
  22. },
  23. "devDependencies": {
  24. "babel-plugin-inline-react-svg": "^2.0.1",
  25. "eslint": "7.32.0",
  26. "eslint-config-next": "^0.2.4",
  27. "file-loader": "^6.2.0",
  28. "sass": "^1.43.3"
  29. }
  30. }

next-config.js

  1. const webpack = require('webpack');
  2. module.exports = {
  3. reactStrictMode: true,
  4. entry: './src/index.js',
  5. module: {
  6. rules: [
  7. //...
  8. {
  9. test: /\.(png|jp(e*)g|svg|gif)$/,
  10. use: [
  11. {
  12. loader: 'file-loader',
  13. options: {
  14. name: 'images/[hash]-[name].[ext]',
  15. },
  16. },
  17. ],
  18. },
  19. ],
  20. },
  21. //...
  22. };

_app.js

  1. //import 'bootstrap/dist/css/bootstrap.css';
  2. //import '/node_modules/bootstrap/scss/bootstrap.scss';
  3. import '../styles/globals.scss';
  4. import '../styles/Home.module.scss';
  5. import 'font-awesome/css/font-awesome.min.css';
  6. function MyApp({ Component, pageProps }) {
  7. return <Component {...pageProps} />
  8. }
  9. export default MyApp
z4iuyo4d

z4iuyo4d1#

通过再次运行npm run audit fix force解决了这个问题,它恢复正常。希望它能帮助某人。感谢Leo

xkftehaa

xkftehaa2#

安装加载程序:yarn add @svgr/webpack
next.config.js

  1. webpack: (config) => {
  2. config.module.rules.push({
  3. test: /\.svg$/i,
  4. loader: '@svgr/webpack',
  5. options: {
  6. svgoConfig: {
  7. plugins: [
  8. {
  9. name: 'preset-default',
  10. params: {
  11. overrides: {
  12. removeViewBox: false, // important
  13. },
  14. },
  15. },
  16. ],
  17. },
  18. },
  19. });
  20. return config;
  21. },

检查填充属性(svg,path等)并将所有值替换为currentColor以扩展当前文本颜色(来自css)

  1. <svg ... fill="currentColor">
  2. ...
  3. </svg>

我更喜欢在组件中动态导入图标:

  1. type AvailableIcons =
  2. | 'facebook' // ./svg/facebook.svg
  3. | 'google';
  4. interface IProps {
  5. name?: AvailableIcons;
  6. style?: React.CSSProperties;
  7. className?: string;
  8. width?: number;
  9. height?: number;
  10. }
  11. export const Icon = async ({ name, ...iconProps }: IProps) => {
  12. const Icon = await import(`./svg/${name}.svg`).then((icon) => icon.default); // lazy import
  13. return <Icon {...iconProps} />;
  14. };
展开查看全部

相关问题