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

如何将Angular应用部署至无网络连接的离线测试服务器

解决Angular应用离线部署时字体无法加载的问题

核心思路

把依赖的外部字体(比如Roboto)下载到本地项目,修改样式引用为本地路径,确保构建时将字体文件打包进dist目录,实现完全离线运行。

具体步骤

  1. 下载字体到本地项目

    • 在项目的src/assets目录下创建fonts/roboto子目录(路径可自定义,后续对应调整即可)。
    • 下载Roboto字体的所需格式文件(通常是.woff2、.woff,覆盖项目用到的字重,比如300、400、500、700),把文件放进上述roboto目录。
  2. 替换全局样式的字体引用

    • 打开全局样式文件(一般是src/styles.scss或src/styles.css)。
    • 删除原有的谷歌CDN字体引入语句,比如:
      @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
      
    • 添加本地字体的@font-face声明(根据实际字重和文件路径调整):
      @font-face {
        font-family: 'Roboto';
        font-style: normal;
        font-weight: 300;
        src: url('./assets/fonts/roboto/Roboto-Light.woff2') format('woff2'),
             url('./assets/fonts/roboto/Roboto-Light.woff') format('woff');
      }
      
      @font-face {
        font-family: 'Roboto';
        font-style: normal;
        font-weight: 400;
        src: url('./assets/fonts/roboto/Roboto-Regular.woff2') format('woff2'),
             url('./assets/fonts/roboto/Roboto-Regular.woff') format('woff');
      }
      
      @font-face {
        font-family: 'Roboto';
        font-style: normal;
        font-weight: 500;
        src: url('./assets/fonts/roboto/Roboto-Medium.woff2') format('woff2'),
             url('./assets/fonts/roboto/Roboto-Medium.woff') format('woff');
      }
      
      @font-face {
        font-family: 'Roboto';
        font-style: normal;
        font-weight: 700;
        src: url('./assets/fonts/roboto/Roboto-Bold.woff2') format('woff2'),
             url('./assets/fonts/roboto/Roboto-Bold.woff') format('woff');
      }
      
    • 项目中依赖Roboto的组件(比如Angular Material)会自动识别本地字体,无需修改组件样式。
  3. 确认资源打包配置

    • 打开angular.json,检查assets数组是否包含"src/assets"(默认配置已包含):
      "assets": [
        "src/favicon.ico",
        "src/assets"
      ],
      
    • 如果字体放在自定义路径,要把该路径添加到assets数组,确保构建时复制到dist目录。
  4. 重新构建部署

    • 执行生产构建命令:
      ng build --configuration production
      
    • 把新生成的dist文件夹内容复制到Tomcat的webapps/myapp目录,重启Tomcat后就能离线访问,字体加载不再依赖外部网络。

额外提示

  • 要是项目用了其他第三方组件依赖外部资源(比如图标、其他字体),用同样思路把资源本地化并修改引用路径。
  • 优先用.woff2格式的字体,它压缩率更高、加载更快,同时保留.woff作为兼容 fallback。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:27:25