简体   繁体   中英

Import Vanilla JavaScript library in Angular 6

I am getting following error when try to import existing Vanilla JavaScript library to Angular 6 component. Please suggest how to fix it.

Syntax to import the library, I have written

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

External JavaScript library - ExistingLibrary.js

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

    function f1(template, options) {}
    function f2(template, options) {}
});

The existing library should probably be a module of some short, so that you module bundler can add it to your module system.

The first thing to look up is if the existing library has a npm package? In that case you probably should use the NPM version of the existing library, or consider upgrading the existing library to a version that comes with module system.

You probably need something like

export const ExistingLibrary = ...

or

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 do not include modules and/or require global this. Eg using something like https://www.npmjs.com/package/webpack-raw-bundler

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

    function f1(template, options) {}
    function f2(template, options) {}
});

instead of this you need to export the functions like this:

export function doJob(template, options) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM