繁体   English   中英

从 angular 中的 node_modules 导入 javascript

[英]Import javascript from node_modules in angular

我安装了一个 npm package ,其中包含一个 javascript 文件,我想使用什么。 js 文件名为all.js ,包含以下代码:

import { initExtended } from './extended'
import Header from './components/header/header'

function initAll(options) {
  // Set the options to an empty object by default if no options are passed.
  options = typeof options !== 'undefined' ? options : {}

  // Allow the user to initialise GOV.UK Frontend in only certain sections of the page
  // Defaults to the entire document if nothing is set.
  var scope = typeof options.scope !== 'undefined' ? options.scope : document
  
  // Find first header module to enhance.
  var $toggleButton = scope.querySelector('[data-module="govuk-header"]')
  new Header($toggleButton).init()

  initExtended(options)
}

export {
  initAll,
  Header
}

文件all.js位于 node_modules 中。

当我尝试直接从 index.html 导入它时:

<script type="module" src="node_modules/@id-sk/frontend/govuk/all.js"></script>

它不工作。 控制台错误,找不到文件。

我还尝试通过 angular.json 导入它:

"scripts": [
   "./node_modules/@id-sk/frontend/govuk/all.js"
]

也无法处理错误“未捕获的语法错误:无法在模块外部使用导入语句(在 scripts.js:15241:1)”。 错误是指行:

import { initExtended } from './extended'

我也尝试在 polyfills 中导入它,但我不知道如何调用它。

正如您所说的angular.json ,我假设您正在使用默认设置的 Angular 应用程序引导 Angular 应用程序。

为了能够在 typescript 文件中使用此 package @id-sk/frontend ,您必须将其直接导入 typescript 文件中。

1. 在你的 TS 文件中导入@id-sk/frontend

// Import everything into a local variable
import * as govuk from '@id-sk/frontend';
// Import specific object
import { HeaderExtended } from  '@id-sk/frontend';

2. 运行ng serve

剧透:会导致打字错误

3. 让我们添加或创建类型

由于@id-sk/frontend不是用 typescript 编写的,因此编译不知道这个库的类型。 在此声明之后,您有两个选择:

  • 查找或贡献给 distinctlyTyped 以创建package @id-sk/frontend类型

  • ./src文件夹中创建一个本地文件typings.d.ts以声明一个空模块

declare module "@id-sk/frontend"

4. 再次杀死并运行ng serve

好好享受!


Go 进一步

您可以在模块中添加类型,以便自动完成@id-sk/frontend提供的对象。

``ts 声明模块“@id-sk/frontend”{

export interface Options {
    scope?: Document
}

export function initAll(options: Options): void;    

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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