[英]Importing plain JS from TS in Angular
我必須在 Angular 應用程序(或庫)的上下文中使用 Typescript 文件中的一些 ES6 JavaScript 代碼(因此,只是一堆 ES6 文件,而不是第三方庫)。 鑒於這是一個角落用例,我無法通過谷歌搜索找到太多信息(大多數方向是指導入 JS 庫),除了我已經完成的; 然而,我仍然有問題。
作為測試,我剛剛創建了一個新的 Angular 13 工作區 ( ng new test
),沒有路由,只有 CSS。然后,我對其默認模板進行了以下更改:
(1) 在tsconfig.json
中,我在編譯器選項中添加了"allowJs": true
(參考這里)。 結果是:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"lib": [
"es2020",
"dom"
],
"allowJs": true
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
(2) 在/src/assets/js/hello.js
下添加了一個虛擬 JS 模塊,內容如下:
// just to be explicit, yet strict is implied by export:
// see https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
'use strict';
export const SOME_CONSTANT = 10;
export function sayHello(name) {
console.log('Hello ' + name);
}
(3) 通過angular.json
將 JS 文件包含在應用程序中(在architect/build/options/scripts
下):
"scripts": [
"src/assets/js/hello.js"
]
(4) 將sayHello
導入到app.component.ts
:
import { Component } from '@angular/core';
import { sayHello } from 'src/assets/js/hello';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
sayHello('world!');
}
}
(5) 添加了src/typings.d.ts
以包含環境類型聲明,內容如下:
declare function sayHello(name: string): void;
現在,應用程序構建,function 被調用並在控制台上輸出它的消息; 但有幾個問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.