首页 > 解决方案 > Webpack 4:文件加载器不加载 .css 或 .scss 文件中的资产

问题描述

我正在尝试移动我的一个 .scss 文件中使用的资产(图像和字体),但似乎它们被忽略了:

这是我的 .scss 文件:

@font-face {
    font-family: 'myfont';
    src: url('../../assets/fonts/myfont.ttf') format('truetype');
    font-weight: 600;
    font-style: normal;
}

body {
    color: red;
    font-family: 'myfont';
    background: url('../../assets/images/bg.jpg');
}

这是我的 webpack.config.js:

const path = require('path');
const { CheckerPlugin } = require('awesome-typescript-loader');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    target: 'node',
    entry: path.resolve(__dirname, 'server.tsx'),
    output: {
        filename: 'server_bundle.js',
        path: path.resolve(__dirname, 'build'),
        publicPath: '/build'
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    module: {
        rules: [{
                test: /\.(tsx|ts)?$/,
                loader: 'awesome-typescript-loader',
                options: {
                    jsx: 'react'
                }
            },
            {
                test: /\.(scss|sass|css)$/,                
                use: [
                    MiniCssExtractPlugin.loader,
                    { loader: 'css-loader', options: { url: false, sourceMap: true } },
                    { loader: 'sass-loader', options: { sourceMap: true } },                    
                ]
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/,
                loader: 'file-loader',
                options: { outputPath: 'public/images' }
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                loader: 'file-loader',
                options: { outputPath: 'public/fonts' }
            }
        ]
    },
    plugins: [
        new CheckerPlugin(),
        new MiniCssExtractPlugin({
            filename: 'public/styles_bundle.css',
            chunkFilename: "public/styles/[id].css"
        })
    ]
}

为什么 Webpack 不处理字体和图像?

标签: csswebpackwebpack-file-loader

解决方案


在 webpack 4.32.2 中测试了 file-loader 和 url-loader。

file-loader 仅加载在 .tsx 文件中导入的文件。url-loader 不适合我。

最后,我找到的是 copy-webpack-plugin


推荐阅读