从组件中的资产目录导入静态 JSON 文件(Angular) [英] Import static JSON file from assets dir in component (Angular)
问题描述
我使用的是 Angular CLI(版本 6).我的 assets
文件夹中有一个小的 JSON
文件,我想将其导入到我的组件中.我想不使用来自我的组件的 GET 请求来执行此操作.
I am using Angular CLI (version 6).
I have a small JSON
file in my assets
folder which I want to import into my component. I want to do this without using a GET request from my component.
我做了什么:
我创建了一个新文件,
typings.d.ts
:
declare module "*.json" {
const value: any;
export default value;
}
... 并在 tsconfig.spec.json
中引用它.以下是 ts.config.spec.json
中引用的片段:
... and referred to it in tsconfig.spec.json
. Here is a snippet of the referral in ts.config.spec.json
:
"files": [
"test.ts",
"polyfills.ts",
"./typings.d.ts"
],
从我的组件中,我试图导入我的 JSON 文件:
From my component, I am trying to import my JSON file as such:
import * as myConfig from '../../assets/config.json';
然而,在该行,我收到一条错误消息:cannot find module ../../assets/config.json
.
At that line however, I get an error message: cannot find module ../../assets/config.json
.
我非常确定这个相对路径是正确的(我也尝试了其他几个选项,类似于typings.d.ts 引用 - 但无论如何,我的目录结构只是一个简单的 Angualr CLI 应用程序:
I am quite sure that this relative path is correct (I tried several other options as well, similarly for the typings.d.ts referral - but anyway, my directory structure is just a simple Angualr CLI app:
|- src
|
|-app
| |-component
| |-component.ts
|
|
|-assets
|-config.json
任何有关如何解决此问题的提示将不胜感激.
Any tips on how to solve this problem would be greatly appreciated.
推荐答案
您只需 import myConfig from 'path/to/json'
然后在您的文件中使用它.
You can just import myConfig from 'path/to/json'
then use it in your file.
这篇关于从组件中的资产目录导入静态 JSON 文件(Angular)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!