[英]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.