3

I have a JavaScript library I'm trying use within an Angular application. It is written with ES6 syntax and exports itself as a module.

export { Q as Library };

Imported into Angular.json as you do:

architect: {
build: {
options: {
   "scripts": [
      "src/assets/libs/library.min.js"
   ]

Angular loads the script but with a module syntax error.

scripts.js:1 Uncaught SyntaxError: Unexpected token 'export'

Here is my tsconfig

compilerOptions
  "target": "es2020",
  "module": "es2020",
  "lib": [
      "es2020",
      "dom"
  ]

How can I properly import this module into the application?

1
  • 1
    can you provide a stackblitz? Commented Dec 28, 2020 at 18:39

1 Answer 1

2
+50

I believe you can import directly into your component instead of adding to the script file;

See this sample demo in This Sandbox

In this example I have made a file q.js with the contents

const Q = {
  qualityLog: (properties) => {
    Object.entries(properties).forEach(([key, element]) => {
      console.log("|============================")
      console.log("|------  >|",key)
      console.log("|------  =|",element)
      console.log("|============================")
    });
  }
}

export {Q as Library};

In my component I am using it like below

import { Library } from 'path/to/q';

export class AppComponent implements OnInit {
  title = "CodeSandbox";

  ngOnInit () {
    Library.qualityLog({title: this.title})
  }
}

In the console we see Console Log

The import is correctly working

Sign up to request clarification or add additional context in comments.

1 Comment

That seems to work when importing into a component. You mentioned importing into a module though? How can that work so all its deps can use the lib?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.