【问题标题】:How to use .js file with declarations .d.ts in Angular如何在 Angular 中使用带有声明 .d.ts 的 .js 文件
【发布时间】:2020-03-23 01:43:44
【问题描述】:

我有 Angular 7 应用程序,我想包含一些来自项目外部的类型化 JS 常量(这些常量在 AngularJS 应用程序中使用,因此我需要将其保留在 js 中)。我在 tsconfig.json 的路径中定义了新路径

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowJs": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "baseUrl": "src",
    "paths": {
      "@app/*": ["app/*"],
      "@env/*": ["environments/*"],
      "@dep/*": ["../../web-common/*"]
    }
  }
} 

在@dep 我有 test.js 和 test.d.ts 包含以下内容

export const TEST_CONST = {
  parser: 'CSV',
  styler: 'XVE'
};

export interface TEST_CONST {
  parser: string;
  styler: number;
}

但是当我导入它并开始使用时

import {TEST_CONST} from '@dep/constants/test';

...

console.log(TEST_CONST.styler);

它给了我

错误 TS2693:“TEST_CONST”仅指一种类型,但在此处用作值。

我也尝试过导入 '@dep/constants/test.js' 但它是一样的...... 如何将带有类型的js文件导入Angular应用程序?据我了解,这应该是可能的。

【问题讨论】:

    标签: angular typescript typescript-typings


    【解决方案1】:

    尝试添加declare并删除export

    declare interface TEST_CONST {
      parser: string;
      styler: number;
    }
    

    【讨论】:

    • 它给了我文件不是一个模块
    • 如果直接导入呢? import {TEST_CONST} from '@dep/constants/test.js'
    猜你喜欢
    • 2020-12-24
    • 2021-09-28
    • 1970-01-01
    • 2021-02-18
    • 2018-03-23
    • 2015-11-22
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多