Значки начальной загрузки и Webpack 5 — Вам может потребоваться соответствующий загрузчик для обработки файлов этого типа

#webpack #bootstrap-icons

Вопрос:

У меня возникли большие проблемы с получением значков начальной загрузки для работы с webpack:

Получение следующего:

 ERROR in ./node_modules/bootstrap-icons/font/bootstrap-icons.css 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> @font-face {
|   font-family: "bootstrap-icons";
|   src: url("./fonts/bootstrap-icons.woff2?856008caa5eb66df68595e734e59580d") format("woff2"),
 @ ./src/index.js 3:0-50
 

С правилами webpack:

       {
        test: /.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(?((v=d .d .d )|(w*)))?$/,
        use: { loader: "file-loader?name=/[hash].[ext]" }
      },
      ...

      {
        test: /.(sa|sc|c)ss$/,
        exclude: /node_modules/,
        use: [
          "style-loader",
          MiniCssExtractPlugin.loader,
          "css-loader",
          "postcss-loader",
          "sass-loader"
        ]
      }
 

И .js как

 import "./scss/main.scss";
import "bootstrap-icons/font/bootstrap-icons.css";
 

Я перепробовал все, что смог найти. Я следил за каждой строчкой этого туроиала и все еще не могу заставить его работать: https://odan.github.io/2021/01/07/webpack-bootstrap-icons.html

 webpack: "5.52.1",
"bootstrap-icons": "^1.5.0",
"file-loader": "^6.2.0",
 

Ответ №1:

У меня была та же проблема, я вроде как решил ее, прочитав документацию. Проблема, которую я понял впоследствии, заключалась в том, что webpack не удаляет неиспользуемые значки начальной загрузки с помощью purgecss.

   {
    test: /.(woff|woff2|eot|ttf|otf)$/i,
    type: "asset/inline",
  },
 

Ответ №2:

Для использования значков начальной загрузки 1.72 с Webpack 5.65

  1. Установите следующие библиотеки (если они еще не установлены):
 npm install bootstrap-icons
npm install --save-dev mini-css-extract-plugin css-loader postcss-loader sass-loader autoprefixer sass

 
  1. Добавьте следующие правила веб-пакета:
 // Put this at the top of index.js or other entry files
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// Rule for processing the Bootstrap icons
{
    test: /.woff($|?)|.woff2($|?)|.ttf($|?)|.eot($|?)|.svg($|?)/i,
    type: 'asset/resource',
    generator: {
        //filename: 'fonts/[name]-[hash][ext][query]'
        filename: 'fonts/[name][ext][query]'
    }
},

...

// Rule for processing .css and .scss files
{
    test: /.s?css$/,
    use: [
        // Save the CSS as a separate file to allow caching                            
        MiniCssExtractPlugin.loader,
        {
            // Translate CSS into CommonJS modules
            loader: 'css-loader',
        },
        {
            // Run postcss actions
            loader: 'postcss-loader',
            options: {
                postcssOptions: {
                    plugins: [
                        function () {
                            return [ require('autoprefixer') ];
                        }
                    ],
                },
            },
        },
        {
            loader: 'sass-loader',
            options: {
                sassOptions: {
                    outputStyle: "compressed",
                }
            }
        }
    ],
},
 
  1. Добавьте следующее в main.scss . Пожалуйста, обратите внимание на расширение .css после значков начальной загрузки. Если вы опустите расширение, это приведет к ошибке.
 @import 'bootstrap-icons/font/bootstrap-icons.css';
 
  1. Проверьте значок, добавив его в HTML-файл.
 <i class="bi-alarm" style="font-size: 3rem;"></i>