1. 程式人生 > 實用技巧 >weboack5webpack5用url-loader(file-loader)處理字型

weboack5webpack5用url-loader(file-loader)處理字型

file-loader(url-loader)可以用解析打包字型。

webpack配置loader

\\ webpack.config.js
    const webpack = require("webpack");
    const path = require("path");
    const htmlWebpackPlugin = require("html-webpack-plugin"); // 生成.html檔案的外掛
    const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // 把樣式提取為單獨的css檔案 的外掛
    const { CleanWebpackPlugin } = require("clean-webpack-plugin"); // 清除構建目錄的外掛
    module.exports = {
        entry: "./src/main.js", // 打包入口檔案
        mode: "development", // 使用開發模式
        devServer: {
            // 本地伺服器代理
            contentBase: path.join(__dirname, "dist"), //指定在哪個目錄下找要載入的檔案
            compress: true,
            port: 8080, // 配置埠
            hot: true, // 配置熱更新
        },
        plugins: [
            new MiniCssExtractPlugin({
                filename: "[name].css",
                ignoreOrder: false,
            }),
            new htmlWebpackPlugin({
                favicon: "./public/favicon.ico",
                filename: "index.html",
                template: "./public/index.html",
            }),
            new CleanWebpackPlugin(),
        ],
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader, "css-loader"], // 處理css的loader
                },
                {
                    //解析字型
                    test: /\.(woff|woff2|eot|ttf|otf)$/,
                    use: "file-loader", // url-loader 也可以用來解析字型
                },
            ],
        },
        output: {
            path: path.join(__dirname, "dist"),
            filename: "app.[hash:16].js",
            publicPath: "/", // 也可以用來處理路徑問題,加在所有檔案路徑前的根路徑
        },
    };

配置loader的demo https://github.com/cisbest/webpack5-demo-font