首页 > 解决方案 > 在 Material-UI 自定义主题(ReactJS)中实现自托管字体?

问题描述

目前,我正在使用 Material-UI for ReactJS 设置我的第一个项目。因为我想使用例如自定义字体(托管在服务器上,而不是 Google 字体或类似的东西)来自定义默认主题,所以我开始研究这个。

但是,虽然在构建期间或在浏览器控制台中没有出现任何错误,但它只是没有加载。我已经尝试了 StackOverflow 和 Material-UI repo 提出的多个解决方案,但我无法让它工作,因此我不知道下一步该做什么。

我已经尝试了 StackOverflow 上的其他线程、官方 Material-UI 文档和 Material-UI GitHub 存储库中的问题中建议的几种方法,但无济于事。我可能忽略了一些明显的东西,或者混淆了不同的概念,所以任何帮助都会非常感激:)

主题定义:

import {createMuiTheme} from "@material-ui/core";

import Penna from "./../../assets/fonts/penna.otf";

const pennaFont = {
    fontFamily: 'Penna',
    fontStyle: 'normal',
    fontDisplay: 'swap',
    fontWeight: 400,
    src: `
    local('Penna'),
    url(${Penna})
  `,
}

const MUI_THEME = createMuiTheme({
    typegraphy: {
        fontFamily: ['Penna', "'Helvetica Neue'", 'Helvetica', 'Arial', 'sans-serif'].join(","),
        fontSize: "16px",
        fontWeightLight: "300",
        fontWeightRegular: "400",
        fontWeightMedium: "700",
    },
    overrides: {
        MuiCssBaseline: {
            '@global': {
                '@font-family': [pennaFont],
            },
        },
    },
});

export default MUI_THEME;

顶级入口点:


// ReactJS related
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';

// Material-UI
import {ThemeProvider} from "@material-ui/styles";
import CssBaseline from '@material-ui/core/CssBaseline';

// Custom
import MuiTheme from "./base/MuiTheme";
import Main from "./Main";

ReactDOM.render(
    <ThemeProvider theme={MuiTheme}>
        <CssBaseline/>
        <BrowserRouter>
            <Main/>
        </BrowserRouter>
    </ThemeProvider>,
    document.getElementById("root"));

网络包配置:

const path = require("path");

module.exports = {
    mode: "development",
    entry: path.join(__dirname, "../..", "src", "client", "js", "index.js"),
    output: {
        path: path.join(__dirname, "../..", "dist", "js"),
        filename: "index.js"
    },
    module: {
        rules: [
            {
                exclude: path.join(__dirname, "node_modules"),
                test: /\.jsx?$/,
                use: {
                    loader: "babel-loader",
                },
            },
            {
                test: /\.scss$/,
                use: [{
                    loader: "style-loader"
                }, {
                    loader: "css-loader"
                }, {
                    loader: "sass-loader",
                    options: {}
                }]
            },
            {
                test: /\.(woff(2)?|eot|ttf|otf)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'assets/fonts'
                    }
                }]
            }
        ],
    },
    resolve: {
        extensions: [".css", ".scss", ".js", ".jsx", ".json", ".otf"],
    },
    target: "web",
    context: __dirname,
    stats: {
        colors: true,
        reasons: true,
        chunks: true,
    },
};

包.json:

{
  "name": "romys-hairstyling",
  "version": "0.0.1",
  "description": "Official page for Romy's Hairstyling.",
  "main": "index.js",
  "scripts": {
    "build:react": "webpack --config ./config/webpack/webpack.config.js",
    "build:scss:base": "sass src/client/scss/base/_index.scss dist/css/base.css",
    "copy:html": "node ./scripts/copy.js ./src/client/index.html ./dist/index.html -f",
    "copy:images": "node ./scripts/copy.js ./src/client/assets/images ./dist/images -Rf",
    "watch": "npm-run-all -p watch:react watch:scss:base watch:html watch:images -l",
    "watch:react": "webpack --config ./config/webpack/webpack.config.js --watch --watch-aggregate-timeout 500 --watch-poll 1000 --info-verbosity verbose",
    "watch:scss:base": "chokidar \"./src/client/scss/base\" -c \"npm run build:scss:base\" --verbose --initial",
    "watch:html": "chokidar \"./src/client/index.html\" -c \"npm run copy:html\" --verbose --initial",
    "watch:images": "chokidar \"./src/client/assets/images\" -c \"npm run copy:images\" --verbose --initial",
    "start:server": "nodemon ./src/server/server.js",
    "test:eslint:summary": "eslint -c ./.eslintrc ./src/client/js/index.js",
    "test:eslint:fix": "eslint --fix -c ./.eslintrc ./src/client/js/index.js"
  },
  "keywords": [
    "Romy",
    "Hairstyling"
  ],
  "author": "Tomas Schlepers",
  "license": "ISC",
  "dependencies": {
    "@material-ui/core": "^3.9.3",
    "@material-ui/icons": "^3.0.2",
    "express": "^4.16.4",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-router-dom": "^4.3.1"
  },
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/preset-env": "^7.4.3",
    "@babel/preset-react": "^7.0.0",
    "@material-ui/styles": "^4.0.0",
    "babel-loader": "^8.0.5",
    "chokidar-cli": "^1.2.2",
    "css-loader": "^2.1.1",
    "eslint": "^5.16.0",
    "eslint-plugin-react": "^7.12.4",
    "file-loader": "^3.0.1",
    "node-sass": "^4.12.0",
    "nodemon": "^1.18.11",
    "normalize.css": "^8.0.1",
    "npm-run-all": "^4.1.5",
    "sass": "^1.20.1",
    "sass-loader": "^7.1.0",
    "shelljs": "^0.8.3",
    "style-loader": "^0.23.1",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.1"
  }
}

如前所述,我没有收到任何错误消息。我还可以在编译的 JS 代码中看到对 Penna 字体的引用,但是在查看渲染的 DOM 树时,我看不到定义的自定义主题。

标签: javascriptreactjsmaterial-uireact-material

解决方案


步骤1

将字体文件添加到字体目录 (./fonts/Raleway-Regular.woff2)


第2步

以 woff/woff2 格式将字体导入代码中。文档说明 ttf/woff/woff2 支持,但 ttf 对我不起作用。

https://material-ui.com/customization/typography/

import RalewayWoff2 from './fonts/Raleway-Regular.woff2';
import RalewayBoldWoff2 from './fonts/Raleway-Bold.woff2';

const raleway = {
  fontFamily: 'Raleway',
  fontStyle: 'normal',
  fontDisplay: 'swap',
  fontWeight: 400,
  src: `
    local('Raleway'),
    local('Raleway-Regular'),
    url(${RalewayWoff2}) format('woff2')
  `,
};

const ralewayBold = {
  fontFamily: 'Raleway',
  fontStyle: 'normal',
  fontDisplay: 'swap',
  fontWeight: 700,
  src: `
    local('Raleway'),
    local('Raleway-Bold'),
    url(${RalewayBoldWoff2}) format('woff2')
  `,
};
第 3 步

在终端中运行它以在构建过程中使用加载器来处理加载文件

npm install --save-dev file-loader

参考https://jimthedev.com/2016/07/28/using-google-fonts-in-webpack-and-react/


第4步

然后在主题中定义字体

const theme = createMuiTheme({
  typography: {
    fontFamily: [
      'Raleway',
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        '@font-face': [raleway,ralewayBold],
      },
    },
  },
});

您可以使用像这样导入的粗体字体。

font-weight: 700;


推荐阅读