有时候需要读取组件为字符串,直接套代码很好用。传入路径即可
函数接收一个 filePath 参数,表示要读取的文件路径。该函数使用 XMLHttpRequest 对象发送 GET 请求,获取文件内容。
- const readFile = (filePath) => {
- // 创建一个新的xhr对象
- let xhr = null;
- if (window.XMLHttpRequest) {
- xhr = new XMLHttpRequest();
- } else {
- // eslint-disable-next-line
- xhr = new ActiveXObject("Microsoft.XMLHTTP");
- }
- const okStatus = document.location.protocol === "file" ? 0 : 200;
- xhr.open("GET", filePath, false);
- xhr.overrideMimeType("text/html;charset=utf-8");
- xhr.send(null);
- return xhr.status === okStatus ? xhr.responseText : null;
- };
具体实现步骤如下:
overrideMimeType 方法设置响应内容的 MIME 类型为 text/html;charset=utf-8,以确保中文字符不会乱码。null。需要注意的是,该函数使用了同步请求,即在请求未完成之前会阻塞程序执行。在实际开发中,应尽量避免使用同步请求,而是使用异步请求,以避免阻塞页面的渲染和交互。