[英]VSCode Extension webview load json file problem
我正在尝试构建一个项目,其中我有一个 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
错误是“不能在模块外使用导入语句”
下面是我完整的 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/**/*"
]
}
我究竟做错了什么? 请帮忙。 提前致谢。
webview 沙箱运行普通的 javascript,所以除非你做一些额外的事情,否则 node.js require()
或模块的概念不可用。 只有来自配置位置的文件和资源才能加载。 请参阅https://code.visualstudio.com/api/extension-guides/webview#loading-local-content
关于 VS 代码 Webview,我建议将逻辑保留在您的扩展代码中,将 Webview 保留为仅可视化逻辑,并使用此处描述的消息传递来回通信: Z5E056C500A1C4B6A7110B50D807/BADE。 guides/webview#scripts-and-message-passing并调用您的扩展命令。
That way, you can load the json file in your typescript code that creates the Webview, then upon an event (either the body onload event, or the user pressing a button), the javascript in your Webview html shall pass a message to your extension请求 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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.