[英]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 文件中。
@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';
ng serve
⚠劇透:會導致打字錯誤
由於@id-sk/frontend
不是用 typescript 編寫的,因此編譯不知道這個庫的類型。 在此聲明之后,您有兩個選擇:
查找或貢獻給 distinctlyTyped 以創建package @id-sk/frontend
類型
在./src
文件夾中創建一個本地文件typings.d.ts
以聲明一個空模塊
declare module "@id-sk/frontend"
ng serve
好好享受!
您可以在模塊中添加類型,以便自動完成@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.