Ben Racicot
Ben Racicot

Reputation: 5951

Using ES6 Module Libraries in Angular Applications and Unexpected token 'export' Error

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?

Upvotes: 3

Views: 830

Answers (1)

Owen Kelvin
Owen Kelvin

Reputation: 15083

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

Upvotes: 2

Related Questions