【问题标题】:VSCode Extension webview load json file problemVSCode Extension webview加载json文件问题
【发布时间】:2019-11-02 15:06:42
【问题描述】:

我正在尝试构建一个项目,其中有一个我必须在我的主文件中解析的 json 文件。但我不能将它包含在主文件中。在终端中,main.ts 和 main.js 都没有错误。 Webview 面板显示来自 html 的内容,但没有显示主文件中的内容。如果我通过开发人员工具进行检查,则会显示错误。我在 main.ts 中导入 json,而 main.js 是 main.ts 的编译文件。我需要这两个文件,并且其中任何一个都发生错误。

我尝试了不同的组合

组合一:

import json from "./test.json"; //in main.ts file
"module": "commonjs" // in tsconfig.json file

错误是“未在 main.js 文件中定义导出”

组合2:

const json = require("./test.json"); //in main.ts file
"module": "commonjs" // in tsconfig.json file

错误是“要求未在 main.ts 中定义”

组合3:

const json = require("./test.json"); //in main.ts file
"module": "es2015" // in tsconfig.json file

错误是“要求未在 main.ts 中定义”

组合4:

import json from "./test.json"; //in main.ts file
"module": "es2015" // in tsconfig.json file

错误是“不能在模块外使用 import 语句”

下面是我完整的 tsconfig.json 的示例

{
    "compilerOptions": {
        "module": "es2015",
        "target": "es5",
        "outDir": "out",
        "sourceMap": true,
        "strict": true,
        "rootDir": "src",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "strictNullChecks":false,
        "lib": ["dom","es2015","es5","es6"]
    },
    "exclude": ["node_modules", ".vscode-test"],
    "include"        : [
        "src/**/*"
    ]
}

我做错了什么?请帮忙。提前致谢。

【问题讨论】:

  • 所以你无法在 js 文件中导入 json 文件是什么问题?
  • 是的。我在ts文件中导入json,js文件是编译后的文件。我需要这两个文件,并且其中任何一个都发生错误。
  • 是的,我也试过了
  • 打字稿的版本是多少?

标签: javascript json typescript webview vscode-extensions


【解决方案1】:

webview 沙箱运行纯 javascript,因此除非您做一些额外的事情,否则 node.js require()模块 的概念不可用。 只有来自配置位置的文件和资源才能加载。看 https://code.visualstudio.com/api/extension-guides/webview#loading-local-content

关于 VS Code Webview,我建议将逻辑保留在扩展代码中,将 Webview 保留为仅可视化逻辑,并使用此处描述的消息传递来回通信:https://code.visualstudio.com/api/extension-guides/webview#scripts-and-message-passing 并调用扩展命令。

这样,您可以在创建 Webview 的 typescript 代码中加载 json 文件,然后在发生事件(body onload 事件或用户按下按钮)时,Webview html 中的 javascript 将传递一条消息到您请求 json 数据的扩展程序。您的扩展程序将包含 json 数据作为有效负载的消息传回。

示例扩展代码:

    const json = require("./test.json");

    // Send a message to our webview.
    // You can send any JSON serializable data.
    currentPanel.webview.postMessage({ command: 'load', jsonData: json });

Webview javascript 代码示例:

        window.addEventListener('message', event => {

            const message = event.data; // The command and JSON data our extension sent

            switch (message.command) {
                case 'load':
                    // todo: do something with the json data
                    console.log(message.jsonData)
                    break;
            }
        });

【讨论】:

  • 我刚开始使用 webview,对我来说不是很清楚。你描述的那个想法,我什至没有想到! :(但是非常感谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 2022-11-10
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多