繁体   English   中英

从 Angular 中的 TS 导入普通 JS

[英]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 被调用并在控制台上输出它的消息; 但有几个问题

  • 在运行时我收到错误Uncaught SyntaxError: Unexpected token 'export' 这似乎指向一个没有加载type="module"的 JS 脚本(参见例如这篇文章),但脚本是通过angular.json此处加载的,因此它们应该已经作为模块加载(从此处显示)。 tsconfigmodule的默认值是es2020 ,所以这篇文章似乎并不适用。

  • 打字似乎没有效果。 例如,我可以从sayHello中删除字符串参数并且ng build成功,尽管该参数是在types.d.ts中声明的(当然我在 VSCode 中没有得到sayHello的类型化智能感知)。

我创建了一个新的 angular 项目,没有任何修改,它对我来说就像这样。 这是你想要的? 您还可以在 tsconfig.json 中将“noImplicitAny”设置为 false,它可以在没有 d.ts 文件的情况下工作。 例子

暂无
暂无

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

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