在 Angular 应用程序中使用 ES6 模块库和意外令牌 'export' 错误

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

我有一个 JavaScript 库,我正尝试在 Angular 应用程序中使用。它使用 ES6 语法编写,并将自身作为模块导出。

export { Q as Library };

像您一样导入到 Angular.json

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

Angular 加载脚本但出现模块语法错误。

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

这是我的tsconfig

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

如何将此模块正确导入应用程序?

我相信你可以直接导入到你的组件中而不是添加到脚本文件中;

请参阅 This Sandbox

中的示例演示

在这个例子中,我创建了一个文件q.js,内容为

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

export {Q as Library};

在我的组件中,我像下面这样使用它

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

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

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

在控制台中我们看到

导入工作正常