带有真棒字体的webpack.config

我将在源代码中使用fontawesome 5,但在这里遇到一些麻烦。

我已经安装了4个npm模块。

  

“ @ fortawesome / fontawesome-free”:“ ^ 5.11.2”,

     

“ @ fortawesome / fontawesome-svg-core”:“ ^ 1.2.25”,

     

“ @ fortawesome / free-solid-svg-icons”:“ ^ 5.11.2”,

     

“ @ fortawesome / react-fontawesome”:“ ^ 0.1.7”,

webpack.config.js

'use strict';

/**
 * Webpack Config
 */
const path = require('path');
const fs = require('fs');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

// Webpack uses `publicPath` to determine where the app is being served from.
// In development,we always serve from the root. This makes config easier.
const publicPath = '/';

// Make sure any symlinks in the project folder are resolved:
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory,relativePath);

// plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsplugin = require("optimize-css-assets-webpack-plugin");

const CopyWebpackPlugin = require('copy-webpack-plugin');

// the path(s) that should be cleaned
let pathsToClean = [
    'dist','build'
]

// the clean options to use
let cleanOptions = {
    root: __dirname,verbose: false,// Write logs to console.
    dry: false
}

module.exports = {
    entry: ["babel-polyfill","react-hot-loader/patch","./src/index.js"],output: {
        // The build folder.
        path: resolveApp('build'),// Generated JS file names (with nested folders).
        // There will be one main bundle,and one file per asynchronous chunk.
        // We don't currently advertise code splitting but Webpack supports it.
        filename: 'assets/js/[name].[hash:8].js',chunkFilename: 'assets/js/[name].[hash:8].chunk.js',// We inferred the "public path" (such as / or /my-project) from homepage.
        publicPath: publicPath,hotUpdateChunkFilename: 'hot/hot-update.js',hotUpdateMainFilename: 'hot/hot-update.json'
    },devserver: {
        contentBase: './src/index.js',compress: true,port: 3000,// port number
        historyApiFallback: true,quiet: true
    },// resolve alias (Absolute paths)
    resolve: {
        alias: {
            Components: path.resolve(__dirname,'src/components/'),Containers: path.resolve(__dirname,'src/containers/'),Assets: path.resolve(__dirname,'src/assets/'),Util: path.resolve(__dirname,'src/util/'),Routes: path.resolve(__dirname,'src/routes/'),Constants: path.resolve(__dirname,'src/constants/'),Redux: path.resolve(__dirname,'src/redux/'),Data: path.resolve(__dirname,'src/data/')
        }
    },module: {
        rules: [
            {
                test: /\.(js|jsx)$/,exclude: /node_modules/,use: {
                    loader: "babel-loader"
                }
            },{
                test: /\.html$/,use: [
                    {
                        loader: "html-loader",options: { minimize: true }
                    }
                ]
            },{
                test: /\.css$/,use: [MiniCssExtractPlugin.loader,"css-loader"]
            },// Scss compiler
            {
                test: /\.scss$/,use: [
                    MiniCssExtractPlugin.loader,"css-loader","sass-loader"
                ]
            }
        ]
    },optimization: {
        minimizer: [
            new UglifyJsPlugin({
                cache: true,parallel: true,uglifyOptions: {
                    compress: false,ecma: 6,mangle: true
                },sourceMap: true
            }),new OptimizeCSSAssetsplugin({})
        ]
    },performance: {
        hints: process.env.NODE_ENV === 'production' ? "warning" : false
    },plugins: [
        new CopyWebpackPlugin([
            { from: 'src/assets/img',to: 'assets/img' },{ from: 'src/assets/fonts',to: 'assets/fonts' }
        ]),new FriendlyErrorsWebpackPlugin(),new CleanWebpackPlugin(pathsToClean,cleanOptions),new HtmlWebPackPlugin({
            template: "./public/index.html",filename: "./index.html",favicon: './public/favicon.ico'
        }),new MiniCssExtractPlugin({
            filename: "assets/css/[name].[hash:8].css"
        }),new MiniCssExtractPlugin({
            filename: "[name].[hash:8].css",chunkFilename: "[id].[hash:8].css"
        })
    ]
};

import '@fortawesome/fontawesome-free/css/solid.css';

时出现错误
Failed to compile with 1 errors                                                                                                        3:21:04 AM
 error  in ./node_modules/@fortawesome/fontawesome-free/css/solid.css

Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleParseError: 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
(Source code omitted for this binary file)
    at handleParseError (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\lib\NormalModule.js:469:19)
    at doBuild.err (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\lib\NormalModule.js:503:5)
    at runLoaders (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\lib\NormalModule.js:358:12)
    at E:\workspace\pulse\projectai-pulse-survey\node_modules\loader-runner\lib\LoaderRunner.js:373:3
    at iterateNormalLoaders (E:\workspace\pulse\projectai-pulse-survey\node_modules\loader-runner\lib\LoaderRunner.js:214:10)
    at Array.<anonymous> (E:\workspace\pulse\projectai-pulse-survey\node_modules\loader-runner\lib\LoaderRunner.js:205:4)
    at Storage.finished (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:55:16)    at provider (E:\workspace\pulse\projectai-pulse-survey\node_modules\webpack\node_modules\enhanced-resolve\lib\CachedInputFileSystem.js:91:9)
    at E:\workspace\pulse\projectai-pulse-survey\node_modules\graceful-fs\graceful-fs.js:115:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)

 @ ./src/components/MyMap/KGraph/index.js 17:0-54
 @ ./src/components/MyMap/index.js
 @ ./src/routes/mymap/index.js
 @ ./src/routes/index.js
 @ ./src/containers/App.js
 @ ./src/App.js
 @ ./src/index.js
 @ multi babel-polyfill react-hot-loader/patch ./src/index.js

我已经尝试了多种方法来解决此问题,但都失败了。 请帮助我。

jiaoshi_910 回答:带有真棒字体的webpack.config

在我的情况下,使用 file-loader url-loader 而不是仅测试图像文件扩展名,我还添加了以下字体扩展名:

module: {
  rules: [
   {
    test: /\.(png|svg|jpg|jpeg|gif|woff|woff2|eot|ttf|)$/i,use: [
      {
        loader: "file-loader",options: {//your options},}
      // ...other loaders here
    ],},]
}
,

尝试根据建议here将“ CSS”文件的导入更改为“'~@fortawesome/fontawesome-free/css/solid.css'”导入。

,

解决了!

我已将以下代码添加到webpack.config.js

module: {
    rules: [
        ...
        { 
            test: /\.(png|woff|woff2|eot|ttf|svg)$/,loader: 'url-loader?limit=100000' 
        }
    ]
}

谢谢

本文链接:https://www.f2er.com/3149422.html

大家都在问