Angular - How to import a module from a JS bundle

2.8k views Asked by At

I am trying to import a module from a generated Angular library bundle located inside a vendor subfolder under src/.

index.html

<head>
...
    <script type="text/javascript" charset="utf-8" src="./vendor/example/bundles/example.umd.js"></script>
    
</head>

Nevertheless, I am having some troubles importing module from this in my app.module.ts. Please, any idea of how to do it?

It seems that @angular/core and @angular/common peerDependencies of angular library should also be bundled inside script to work correctly.

I will appreciate any kind of help

1

There are 1 answers

12
Guerric P On

You shouldn't add a <script> tag that refers to a local file because this local file won't be included in the build.

Instead, use the scripts configuration section of the angular.json file, like this:

"scripts": [
    { "input": "src/vendor/example/bundles/example.umd.js" }
]

This will embed the example.umd.js file inside a dedicated file of the Angular's build. As it's packaged as UMD, an object will be attached to window which contains the API of the library you are importing.

In order to stop TypeScript for complaining about a non-existent variable, just add this: declare var example; (replace example with the real name of the global object).