在使用 Webpack 的情况下,Monaco Editor 不会加载 codicons

Monaco Editor doesn't load codicons in case of using Webpack

尝试使用 Monaco Editor in case of using Webpack, codicons are not loaded. I used the monaco-editor-webpack-plugin and followed the instruction 时,但目前我无法在测试页面的 Monaco Editor 实例上显示任何图标。

我是不是忘记加载密码子了?

您可以重现此问题:https://github.com/yoichiro/monaco-editor-test/tree/main

index.html

<!doctype html>
<html lang="en">
<head>
  <style>
    .source-editor {
                width: 640px;
                height: 320px;
        }
  </style>
</head>
<body>
  <div class="source-editor"></div>
</body>
</html>

index.ts

import * as monaco from 'monaco-editor';

window.addEventListener('load', () => {
        monaco.editor.create(document.querySelector('.source-editor'));
});

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
const MonacoEditorWebpackPlugin = require('monaco-editor-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/index.ts',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js',
    clean: true,
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
      },
      {
        test: /\.scss$/i,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
          },
          {
            loader: 'sass-loader',
            options: {
              sassOptions: {
                outputStyle: 'expanded',
              },
            },
          },
        ],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.ttf$/,
        use: ['file-loader'],
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js', 'scss', 'html'],
  },
  plugins: [
    new MonacoEditorWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: 'style.css',
    }),
    new HtmlWebpackPlugin({ template: './src/index.html' }),
  ],
  devtool: 'source-map',
  watchOptions: {
    ignored: /node_modules/,
  },
  devServer: {
    static: './build',
    // open: true,
    watchFiles: ['src/**/*'],
  },
};

从 Webpack 5 开始,我们需要使用 Asset Modules 而不是加载器。

也就是说,以下代码适用于 Webpack 5:

{
  test: /\.ttf$/,
  type: 'asset/resource'
}

如果使用 Webpack 4 及更低版本,以下代码将起作用:

{
  test: /\.ttf$/,
  use: ['file-loader']
}

摩纳哥为具有 codicon 字体图标的元素插入的 css 默认具有 font-family: inherit;

.codicon-find-previous-match:before {
    content: '\eaa1';
}

除非您为 codicon 代码提供了一些自定义图标字体,否则请确保您有一个 CSS 规则指定由 monaco-editor 提供的 font-family:

 [class^="codicon-"], [class*="codicon-"] {
        font-family: "codicon"!important;
 }