【问题标题】:Angular 12 import json into tsAngular 12 将 json 导入 ts
【发布时间】:2021-08-06 21:42:57
【问题描述】:

我有一个包含以下内容的 json 文件到 src/assets/version.json 中:

{"VERSION":"1.0.0"}

然后我将文件导入*.ts,例如:

import * as VersionInfo from 'src/assets/version.json';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

 constructor() {
   console.log(`version ${VersionInfo['VERSION']}`);
 }

}

输出

version 1.0.0

这适用于 Angular 11,但在 Angular 12 上,CLI 会显示错误

Should not import the named export 'VERSION' (imported as 'VersionInfo') from default-exporting module (only default export is available soon)

这是我的 tsconfig.base.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "strictPropertyInitialization": false,
    "baseUrl": "./",
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "target": "es2015",
    "resolveJsonModule": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "jszip": [
        "node_modules/jszip/dist/jszip.min.js"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictTemplates": true,
    "strictInjectionParameters": true
  },
}

如何解决这个错误?

【问题讨论】:

    标签: angular typescript angular12


    【解决方案1】:

    以下应放在tsconfig.json

    {
     ...
     "compilerOptions": {
        ...
        "resolveJsonModule": true, //already there
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true // Add this line
        ...
       },
    ...
    }
    

    然后只需在您的组件中导入以下内容

    import VersionInfo from 'src/assets/version.json';
    

    【讨论】:

    • allowSyntheticDefaultImports 应该在 compilerOptions 内
    • @atlau 关于“allowSyntheticDefaultImports”的放置是正确的。另外,不需要添加“esModuleInterop”。
    【解决方案2】:

    import { default as VersionInfo } from 'src/assets/version.json';

    您也需要上面提到的两个 tsconfig 条目。

    【讨论】:

      【解决方案3】:

      您可以在tsconfig.json 中尝试:

      "compilerOptions": { "allowSyntheticDefaultImports":true }
      

      然后导入:

      import VersionInfo from 'src/assets/version.json';
      

      【讨论】:

      • 在所有答案中,这只是一个完全正确的答案
      猜你喜欢
      • 2020-06-30
      • 2019-03-26
      • 1970-01-01
      • 2021-01-24
      • 2021-11-11
      • 2019-01-18
      • 1970-01-01
      • 2019-12-25
      • 2019-09-01
      相关资源
      最近更新 更多