簡體   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