在SASS中导入本地字体文件时,Webpack构建失败

时间:2018-12-10 15:07:28

标签: webpack fonts sass

由于最终需要捆绑我们的Javascript代码,我正在尝试将项目构建系统从gulp迁移到webpack。

我遇到的问题是Webpack似乎无法读取从SASS导入的字体。

该目录非常标准,有点像这样:

application
 |_assets
 | |__fonts
 | |__images
 | |__scripts
 | |__styles
 |
 |_public
 | |__fonts
 | |__images
 | |__scripts
 | |__styles
 ...

在我们的.scss文件之一中,我导入了这样的字体:

@include font-face('Visuelt', '../fonts/visuelt-regular');
@include font-face('VisueltMedium', '../fonts/visuelt-medium');
@include font-face('VisueltBold', '../fonts/visuelt-bold');
@include font-face('VisueltLight', '../fonts/visuelt-light');

问题是,当我运行webpack构建时,每种字体都会引发以下错误:

ERROR in ./assets/styles/main.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./assets/styles/main.scss) Module not found: Error: Can't resolve '../fonts/visuelt-bold.svg' in '/Users/jgarcia/Repositories/foo/assets/styles' @ ./assets/styles/main.scss (./node_modules/css-loader!./node_modules/sass-loader/lib/loader.js!./assets/styles/main.scss) 7:4499-4535

我注意到,如果我将路径更改为/fonts/visuelt-regular,则webpack会停止抱怨。问题在于,当我运行应用程序时,字体不会被加载。为了使捆绑的代码正确加载字体,捆绑的CSS必须具有../fonts/visuelt-regular作为路径。我不确定我是否了解发生了什么。

我已经尝试了多种方法,但是似乎无法使其正常工作。有见识吗?

这是webpack配置:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const buildPath = path.join(__dirname, 'public');

module.exports = {
  mode: 'development',
  entry: './assets/entry.js',
  output: {
    filename: 'assets/scripts/bundle.js',
    path: buildPath,
    publicPath: buildPath,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: { // TODO Potentially not necesary?
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-transform-runtime'],
          },
        },
      },
      {
        test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
        loader: 'file-loader',
        options: {
          name: '[path][name].[ext]',
          publicPath: 'assets/',
          emitFile: false,
        },
      },
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '/assets/styles/[name].css',
      chunkFilename: '[id].css',
    }),
    new CopyWebpackPlugin([
      { from: 'assets/fonts', to: 'assets/fonts' },
      { from: 'assets/images', to: 'assets/images' },
    ]),
  ],
};

0 个答案:

没有答案