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

如何在Angular 15私有NPM包中正确使用jQuery?

解决Angular私有NPM包引入jQuery后的构建报错问题

1. 修正jQuery的导入与类型配置

  • 先确认安装了jQuery及其类型定义包:
    npm install jquery @types/jquery --save
    
  • 在pdf-viewer.service.ts里用命名导入替代默认导入,避免模块解析问题:
    import * as $ from 'jquery';
    
    要是依赖全局jQuery,就在库的tsconfig.json里把jquery加入全局类型列表:
    {
      "compilerOptions": {
        "types": ["jquery"]
      }
    }
    

2. 修复类型定义文件缺失导入的问题

  • 检查库的tsconfig.lib.json,确保开启了类型声明生成,且包含所有源码文件:
    {
      "compilerOptions": {
        "declaration": true,
        "declarationMap": true
      },
      "include": ["src/**/*.ts"]
    }
    
    这样构建时会自动生成包含jQuery导入的.d.ts文件;如果还是遗漏,可以手动在PDFViewer.service.d.ts里补加import * as $ from 'jquery';,不过优先靠配置自动生成更稳妥。
  • 要是库需要对外暴露jQuery类型,在public-api.ts里加一句:
    export * from 'jquery';
    

3. 调整Angular库的打包配置

  • 打开angular.json,找到你的库项目的build配置,把jquery加入允许的CommonJS依赖列表,避免webpack打包时的模块错误:
    {
      "projects": {
        "你的库名称": {
          "architect": {
            "build": {
              "options": {
                "allowedCommonJsDependencies": ["jquery"]
              }
            }
          }
        }
      }
    }
    
  • 在库的package.json里把jquery和@types/jquery加到peerDependencies里,确保使用该库的主项目会安装对应版本,避免版本冲突:
    {
      "peerDependencies": {
        "jquery": "^3.6.0",
        "@types/jquery": "^3.6.0"
      }
    }
    

4. 清理缓存后重新构建发布

  • 先清掉本地构建缓存:
    npm run clean
    
  • 重新构建生产版本的库:
    ng build 你的库名称 --prod
    
  • 最后重新发布到私有仓库,确认发布的包里包含正确的.d.ts文件和打包产物。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:37:26