Bootstrap图标和Webpack 5 -你可能需要一个合适的加载器来处理这种文件类型



我遇到了很多问题,使引导图标与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",

这是我发现的使Boostrap图标与Webpack 5(和scss)一起工作的最干净的方法:

步骤1:使用NPM安装引导图标:

npm install --save bootstrap-icons

步骤2:在webpack.config.js中添加一条规则,复制输出目录下的所有woff2文件:

module.exports = {
module: {
rules: [{
test: /.woff2?$/,
type: "asset/resource",
}]
}
}

步骤3:在您的index.scss导入引导图标scss覆盖字体目录:

$bootstrap-icons-font-dir: "~bootstrap-icons/font/fonts";
@import "~bootstrap-icons/font/bootstrap-icons.scss";

步骤4:在你的HTML中使用图标:

<i class="bi-alarm"></i>

我有同样的问题,我通过阅读文档来解决它。我后来发现的问题是webpack没有使用purgecss清除bootstrap中不使用的图标。

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

在Webpack 5.65中使用Bootstrap Icons 1.72

  1. 安装以下库(如果尚未安装):
npm install bootstrap-icons
npm install --save-dev mini-css-extract-plugin css-loader postcss-loader sass-loader autoprefixer sass
  1. 添加以下Webpack规则:
// 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。请注意bootstrap-icons后面的。css扩展名。如果你忽略了扩展名,它将导致一个错误。
@import 'bootstrap-icons/font/bootstrap-icons.css';
  1. 添加到HTML文件中测试图标
<i class="bi-alarm" style="font-size: 3rem;"></i>

相关内容

  • 没有找到相关文章

最新更新