如何在TwinCAT HMI脚本中导入JSON文件?
在TwinCAT HMI TypeScript项目中读取JSON文件的问题
问题详情
我在基于TypeScript开发的TwinCAT HMI项目中,需要在自定义脚本里读取JSON文件内容,尝试多种方法均出现报错:
- 直接在TS文件旁放置JSON并导入
尝试两种导入写法:
import test = require("temperature-namings.json"); // 或添加相对路径前缀 import test from "./temperature-namings.json";
触发报错:Build:Cannot find module 'temperature-namings.json' or its corresponding type declarations.
调整文件位置到Imports文件夹
将JSON移入项目的Imports目录后,依然无法导入,智能提示也无法识别该文件。修改tsconfig.json配置
添加以下配置项:
"resolveJsonModule": true, "esModuleInterop": true,
出现新报错:Build:Option '--resolveJsonModule' cannot be specified without 'node' module resolution
请问该如何正确放置JSON文件,并在自定义TS函数中读取其内容?
解决方案
方法1:用fetch API读取静态JSON文件
TwinCAT HMI的前端运行环境支持浏览器标准API,可通过fetch加载静态JSON:
- 将JSON文件放到项目的WebContent文件夹(该目录是HMI的静态资源根目录,会被正确部署)
- 在TS脚本中编写异步读取逻辑:
async function loadTemperatureData() { try { const res = await fetch('./temperature-namings.json'); const tempData = await res.json(); // 此处使用读取到的JSON数据 console.log(tempData); return tempData; } catch (err) { console.error('JSON加载失败:', err); return null; } } // 调用读取函数 loadTemperatureData();
方法2:添加类型声明文件适配导入
若要使用import方式,需手动添加类型声明:
- 在JSON文件同目录下创建
temperature-namings.d.ts声明文件:
declare module './temperature-namings.json' { // 可替换为JSON对应的具体类型定义,代替any const data: Record<string, string>; export default data; }
- 使用相对路径导入JSON:
import tempData from './temperature-namings.json';
方法3:将JSON内容直接嵌入TS文件
如果JSON内容无需频繁修改,可直接转为TS对象使用:
// 复制JSON文件内容到TS对象中 const temperatureNamings = { "sensor1": "机柜温度", "sensor2": "电机温度", "sensor3": "环境温度" }; // 直接使用该对象 console.log(temperatureNamings.sensor1);
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

