簡體   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