简体   繁体   English

从 Angular 中的 TS 导入普通 JS

[英]Importing plain JS from TS in Angular

I have to consume some ES6 JavaScript code (so, just a bunch of ES6 files, not a 3rd party library) from a Typescript file, in the context of an Angular app (or library).我必须在 Angular 应用程序(或库)的上下文中使用 Typescript 文件中的一些 ES6 JavaScript 代码(因此,只是一堆 ES6 文件,而不是第三方库)。 Given that's a corner usage case, I cannot find much information by googling around (most directions refer to importing JS libraries), except for what I have already done;鉴于这是一个角落用例,我无法通过谷歌搜索找到太多信息(大多数方向是指导入 JS 库),除了我已经完成的; yet, I'm still having issues.然而,我仍然有问题。

As a test, I just created a new Angular 13 workspace ( ng new test ), without routing and with plain CSS. Then, I made these changes to its default template:作为测试,我刚刚创建了一个新的 Angular 13 工作区 ( ng new test ),没有路由,只有 CSS。然后,我对其默认模板进行了以下更改:

(1) in tsconfig.json , I added "allowJs": true ( reference here ) to the compiler options. (1) 在tsconfig.json中,我在编译器选项中添加了"allowJs": true参考这里)。 The result is:结果是:

{
  "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) added a dummy JS module under /src/assets/js/hello.js with this content: (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) included the JS file in the app via angular.json (under architect/build/options/scripts ): (3) 通过angular.json将 JS 文件包含在应用程序中(在architect/build/options/scripts下):

"scripts": [
  "src/assets/js/hello.js"
]

(4) imported sayHello into app.component.ts : (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) added src/typings.d.ts to include ambient type declarations, with this content: (5) 添加了src/typings.d.ts以包含环境类型声明,内容如下:

declare function sayHello(name: string): void;

Now, the app builds, and the function gets invoked and outputs its message on the console;现在,应用程序构建,function 被调用并在控制台上输出它的消息; but there are a couple of issues :但有几个问题

  • at runtime I get error Uncaught SyntaxError: Unexpected token 'export' .在运行时我收到错误Uncaught SyntaxError: Unexpected token 'export' This would appear to point at a JS script loaded without type="module" (see eg this post ), but scripts are loaded via angular.json here, so they should already be loaded as modules (as it appears from here ).这似乎指向一个没有加载type="module"的 JS 脚本(参见例如这篇文章),但脚本是通过angular.json此处加载的,因此它们应该已经作为模块加载(从此处显示)。 The default value for module in tsconfig is es2020 , so this post does not seem to apply. tsconfigmodule的默认值是es2020 ,所以这篇文章似乎并不适用。

  • typings do not seem to be in effect.打字似乎没有效果。 I can eg remove the string argument from sayHello and ng build succeeds, despite the argument being declared in types.d.ts (and of course I get no typed intellisense in VSCode for sayHello ).例如,我可以从sayHello中删除字符串参数并且ng build成功,尽管该参数是在types.d.ts中声明的(当然我在 VSCode 中没有得到sayHello的类型化智能感知)。

I created a new angular project, without any modifications it works like this for me.我创建了一个新的 angular 项目,没有任何修改,它对我来说就像这样。 Is this what you are looking for?这是你想要的? You can also set "noImplicitAny" to false in tsconfig.json and it will work without a d.ts file.您还可以在 tsconfig.json 中将“noImplicitAny”设置为 false,它可以在没有 d.ts 文件的情况下工作。 例子

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

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