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

avwztpqn  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(85)

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

{
  "name": "myskillreactapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@babel/preset-env": "^7.15.8",
    "bootstrap": "^5.0.0-beta3",
    "bootstrap-dark-5": "^1.1.3",
    "font-awesome": "^4.7.0",
    "next": "^10.0.4",
    "next-images": "^1.8.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-icons": "^4.3.1",
    "react-placeholder": "^4.1.0"
  },
  "devDependencies": {
    "babel-plugin-inline-react-svg": "^2.0.1",
    "eslint": "7.32.0",
    "eslint-config-next": "^0.2.4",
    "file-loader": "^6.2.0",
    "sass": "^1.43.3"
  }
}

next-config.js

const webpack = require('webpack');

module.exports = {
  reactStrictMode: true,
  entry: './src/index.js',
  module: {
    rules: [
      //...
      {
        test: /\.(png|jp(e*)g|svg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[hash]-[name].[ext]',
            },
          },
        ],
      },
    ],
  },
  //...
};

_app.js

//import 'bootstrap/dist/css/bootstrap.css';
//import '/node_modules/bootstrap/scss/bootstrap.scss';
import '../styles/globals.scss';
import '../styles/Home.module.scss';
import 'font-awesome/css/font-awesome.min.css';


function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp
z4iuyo4d

z4iuyo4d1#

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

xkftehaa

xkftehaa2#

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

webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/i,
      loader: '@svgr/webpack',
      options: {
        svgoConfig: {
          plugins: [
            {
              name: 'preset-default',
              params: {
                overrides: {
                  removeViewBox: false, // important
                },
              },
            },
          ],
        },
      },
    });

    return config;
  },

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

<svg ... fill="currentColor">
...
</svg>

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

type AvailableIcons =
  | 'facebook' // ./svg/facebook.svg
  | 'google';

interface IProps {
  name?: AvailableIcons;
  style?: React.CSSProperties;
  className?: string;
  width?: number;
  height?: number;
}

export const Icon = async ({ name, ...iconProps }: IProps) => {
  const Icon = await import(`./svg/${name}.svg`).then((icon) => icon.default); // lazy import
  return <Icon {...iconProps} />;
};

相关问题