在Angular 6中导入Vanilla JavaScript库

尝试将现有的Vanilla JavaScript库导入Angular 6时出现以下错误。 请提出解决方法。

import * as ExistingLibrary from 'app/main/libs/ExistingLibrary.js';
ExistingLibrary.doJob is not a function

外部JavaScript库-ExistingLibrary.js

var ExistingLibrary = new (function () {
    this.doJob = doJob;
    function doJob(template, options) {

    function f1(template, options) {}
    function f2(template, options) {}
});
评论
  • 自作孽
    自作孽 回复
    var ExistingLibrary = new (function () {
        this.doJob = doJob;
        function doJob(template, options) {
    
        function f1(template, options) {}
        function f2(template, options) {}
    });
    

    与此相反,您需要导出如下功能:

    export function doJob(template, options) { }
    
  • iaut
    iaut 回复

    现有的库可能应该是一个简短的模块,以便模块捆绑器可以将其添加到模块系统中。

    现有库是否有npm软件包? 您可能需要类似

    export const ExistingLibrary = ...
    

    要么

    module.exports = ExistingLibrary =
    

    If modifying the existing library is not possible, you'll have to configure your module bundler or JS build pipeline to handle libraries that require global this. E.g. using something like https://www.npmjs.com/package/webpack-raw-bundler