首页 > 解决方案 > 通过 webpack 和 css 导入自定义字体的正确方法是什么?

问题描述

我有一个 aurelia 项目,我需要在其中导入一系列自定义字体,但我无法让它工作。

我在 ./fonts 下有 .ttf 文件

这是我的 webpack.config

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
  condition ? ensureArray(config) : ensureArray(negativeConfig);

// primary config:
const outDir = path.resolve(__dirname, project.platform.output);
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '';

const cssRules = [
  {
    loader: 'css-loader',
    options: {
      esModule: false
    }
  }
];


module.exports = ({ production } = {}, {extractCss, analyze, tests, hmr, port, host } = {}) => ({
  resolve: {
    extensions: ['.js'],
    modules: [srcDir, 'node_modules'],

    alias: {
      'aurelia-binding': path.resolve(__dirname, 'node_modules/aurelia-binding')
    }
  },
  entry: {
    app: [
      'aurelia-bootstrapper'
    ]
  },
  mode: production ? 'production' : 'development',
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? 'aureliaScript/[name].[chunkhash].bundle.js' : 'aureliaScript/[name].[hash].bundle.js',
    sourceMapFilename: production ? 'aureliaScript/[name].[chunkhash].bundle.map' : 'aureliaScript/[name].[hash].bundle.map',
    chunkFilename: production ? 'aureliaScript/[name].[chunkhash].chunk.js' : 'aureliaScript/[name].[hash].chunk.js'
  },
  optimization: {
    runtimeChunk: true,
    moduleIds: 'hashed',
    splitChunks: {
      hidePathInfo: true, 
      chunks: "initial",
      maxSize: 200000, 

      cacheGroups: {
        default: false, 
        vendors: { 
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          priority: 19,
          enforce: true, 
          minSize: 30000
        },
        vendorsAsync: { 
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors.async',
          chunks: 'async',
          priority: 9,
          reuseExistingChunk: true,
          minSize: 10000 
        },
        commonsAsync: { 
          name: 'commons.async',
          minChunks: 2,
          chunks: 'async',
          priority: 0,
          reuseExistingChunk: true,
          minSize: 10000
        }
      }
    }
  },
  performance: { hints: false },
  devServer: {
    contentBase: outDir,
    historyApiFallback: true,
    open: project.platform.open,
    hot: hmr || project.platform.hmr,
    port: port || project.platform.port,
    host: host
  },
  devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map',
  module: {
    rules: [
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? [{
          loader: MiniCssExtractPlugin.loader
        }, ...cssRules
        ] : ['style-loader', ...cssRules]
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      { test: /\.html$/i, loader: 'html-loader' },
      {
        test: /\.js$/i, loader: 'babel-loader', exclude: nodeModulesDir,
        options: tests ? { sourceMap: 'inline', plugins: ['istanbul'] } : {}
      },
      // embed small images and fonts as Data Urls and larger ones as files:
      { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
      { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
      { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
      // load these fonts normally, as files:
      { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
      { test: /environment\.json$/i, use: [
        {loader: "app-settings-loader", options: {env: production ? 'production' : 'development' }},
      ]},
    ]
  },
  plugins: [
    ...when(!tests, new DuplicatePackageCheckerPlugin()),
    new AureliaPlugin(),
    new ModuleDependenciesPlugin({
      'aurelia-testing': ['./compile-spy', './view-spy']
    }),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      metadata: {
        // available in index.ejs //
        baseUrl
      }
    }),
    // ref: https://webpack.js.org/plugins/mini-css-extract-plugin/
    ...when(extractCss, new MiniCssExtractPlugin({ // updated to match the naming conventions for the js files
      filename: production ? 'css/css_[name].[contenthash].bundle.css' : 'css/css_[name].[hash].bundle.css',
      chunkFilename: production ? 'css/css_[name].[contenthash].chunk.css' : 'css/css_[name].[hash].chunk.css'
    })),
    ...when(!tests, new CopyWebpackPlugin({
      patterns: [
        { from: 'static', to: outDir, globOptions: { ignore: ['.*'] } }
      ]
    })), // ignore dot (hidden) files
    ...when(analyze, new BundleAnalyzerPlugin()),
    new CleanWebpackPlugin()
  ]
});

这是我的CSS

@font-face {
  font-family: 'Averta-Bold';
  src: url('./fonts/Averta-Bold.ttf') format('ttf');
}

body{
  font-family:'Averta-Bold';
}

webpack 构建运行没有任何问题,但我看不到我的字体应用于我放在正文中的文本。

我究竟做错了什么?

标签: csswebpackfontsaureliafont-face

解决方案


推荐阅读