Angular Library无法在捆绑包中包含第三方库

时间:2019-03-14 10:24:51

标签: angular webpack-4 angular-library ng-build angular-cli-v7

我的要求是创建具有自己视图的库,并根据用户的配置,该库将从AWS S3 Bucket中获取,并在运行时包含在最终应用程序中。 See this example。我可以在主应用程序中添加dist/library/bundles/library.lib.umd.js并将其显示给用户。但是,当我尝试使用uuidmomentng2-dragula之类的第三方库时,ng build命令在最终捆绑包中不包含任何第三方库。我得到警告

'ng2-dragula' is imported by ..\..\dist\torab-custom-lib\esm5\lib\custom-lib.service.js, but could not be resolved – treating it as an external dependency

在构建库和显示projects/library的我的应用程序时显示

ERROR in dist/torab-custom-lib/lib/custom-lib.component.d.ts(2,32): error TS2307: Cannot find module 'ng2-dragula

我想要在最终捆绑包中包含我使用的任何第三方库,因为我无法在运行时安装/导入它们。我尝试过

"bundledDependencies": [
    "ng2-dragula"
  ]

package.json中按照建议的here

"embedded": [
    "ng2-dragula"
      ],
我的ng-package.json中的

建议here。这是我的环境信息

Angular CLI: 7.1.4
Node: 11.10.0
OS: win32 x64
Angular: 7.1.4
... animations, cli, common, compiler, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.11.4
@angular-devkit/build-angular      0.13.5
@angular-devkit/build-ng-packagr   0.11.4
@angular-devkit/build-optimizer    0.13.5
@angular-devkit/build-webpack      0.13.5
@angular-devkit/core               7.1.4
@angular-devkit/schematics         7.1.4
@angular/compiler-cli              7.2.9
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.3.5
@schematics/angular                7.1.4
@schematics/update                 0.11.4
ng-packagr                         4.7.1
rxjs                               6.3.3
typescript                         3.1.6
webpack                            4.29.0

请帮助。另外,如果在应用程序运行时加载第三方库的方式不同,请提出建议。

1 个答案:

答案 0 :(得分:0)

构建库之后,使用rollupjs从fesm5文件中捆绑第三方库。

这是我的rollup.config:

import resolve from 'rollup-plugin-node-resolve';
import sourcemaps from 'rollup-plugin-sourcemaps';
import commonjs from 'rollup-plugin-commonjs';

export default {
    plugins: [
       resolve(), 
       sourcemaps(),
       commonjs({
        namedExports: { 
            'node_modules/chart.js/dist/Chart.js': ['Chart' ]
        }
      })
   ],
   onwarn: () => { return },
   output: {
       format: 'umd',
       name: 'mylib',
       globals: globals,
       sourcemap: true,
       amd: { id: 'mylib' }
    }
}

然后我使用此汇总命令:

 rollup -c rollup.config.js -i .\dist\mylib\fesm5\mylib.js -o .\dist\mylibwiththirdparty.umd.js