You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Monaco Editor加载Codicon.ttf报错:不允许加载本地资源

解决Angular+NX项目中Monaco Editor字体资源加载错误

问题根源

Monaco Editor自带的editor.main.css默认包含指向本地node_modules路径的@font-face规则,若MonacoWebpackPlugin未正确配置资源路径替换逻辑,或NX的Webpack规则未对字体资源做打包处理,会导致浏览器尝试加载file://协议的本地文件,触发权限限制错误。

解决方案

  • 修正MonacoWebpackPlugin配置
    在项目Webpack配置中,给MonacoWebpackPlugin添加publicPath参数,指定资源的基础路径,让插件自动替换CSS中的字体路径:

    const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
    
    module.exports = {
      plugins: [
        new MonacoWebpackPlugin({
          publicPath: '/', // 匹配项目资源根路径,若资源存放在assets下可设为'/assets/'
          // 保留原有配置项(如languages等)
        })
      ]
    };
    
  • 强制覆盖默认字体规则
    在global.scss中,给自定义@font-face规则添加!important,确保优先级高于editor.main.css中的默认规则:

    @font-face {
      font-family: 'codicon';
      src: url('/assets/resources/codicon.ttf') format('truetype') !important;
      font-weight: normal;
      font-style: normal;
    }
    
  • 配置Webpack处理字体资源
    在Webpack的module.rules中添加字体文件处理规则,让Webpack将字体打包到指定目录并生成正确的访问路径:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.(ttf|woff|woff2)$/,
            type: 'asset/resource',
            generator: {
              filename: 'assets/resources/[contenthash][ext]' // 输出路径与你的资源目录对应
            }
          }
        ]
      }
    };
    
  • 清理NX缓存后重新构建
    执行NX缓存清理命令,避免旧的CSS规则残留:

    nx clean
    nx build <你的项目名称>
    

内容的提问来源于stack exchange,提问作者BGestel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 18:34:56