简体   繁体   English

如何使用VueJS / Typescript导入JSON文件?

[英]How do you import a JSON file with VueJS / Typescript?

I just created a clean VueJS new project and I can't get loading a JSON file to work. 我刚刚创建了一个干净的VueJS新项目,但无法加载JSON文件才能正常工作。

Reproduction / Issue 复制/发行

For easy reproduction I've created a Github repo with my issue: https://github.com/devedse/VueJSImportJsonFile 为了便于复制,我创建了一个带有问题的Github存储库: https : //github.com/devedse/VueJSImportJsonFile

In the Home.vue page I'm trying to get Json loading to work. 在Home.vue页面中,我试图让Json加载工作。 ( https://github.com/devedse/VueJSImportJsonFile/blob/master/src/views/Home.vue ) https://github.com/devedse/VueJSImportJsonFile/blob/master/src/views/Home.vue

When you open this solution in VSCode the following line shows an error: 当您在VSCode中打开此解决方案时,以下行显示错误:

import theJson from '@/assets/hi.json';

VSCode中的错误 Can't find module '@/assets/hi.json'

When running NPM Serve the following error pops up: 运行NPM服务时,会弹出以下错误: 在此处输入图片说明

What I've already tried 我已经尝试过的

I've already searched all of stackoverflow and tried everything in the following posts: 我已经搜索了所有stackoverflow并尝试了以下文章中的所有内容:

Importing json file in TypeScript 在TypeScript中导入json文件

Typescript compiler error when importing json file 导入json文件时出现Typescript编译器错误

https://github.com/chybie/ts-json https://github.com/chybie/ts-json

Edit 1: 编辑1:

Ok I now managed to get it to work when running npm run serve by adding this to the tsconfig.json: 好的,我现在设法通过将其添加到tsconfig.json来使其在运行npm run serve时起作用:

{
  "compilerOptions": {
    "resolveJsonModule": true
  }
}

However the error in VSCode seems to stay. 但是,VSCode中的错误似乎仍然存在。 Is there a way to fix this too? 有没有办法解决这个问题?

Simply add resolveJsonModule": true to your tsconfig.json under compilerOptions : 只需添加resolveJsonModule": truetsconfig.jsoncompilerOptions

diff --git a/tsconfig.json b/tsconfig.json
index 499f5e2..a05dab1 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -6,6 +6,7 @@
     "jsx": "preserve",
     "importHelpers": true,
     "moduleResolution": "node",
+    "resolveJsonModule": true,
     "esModuleInterop": true,
     "allowSyntheticDefaultImports": true,
     "sourceMap": true,

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

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