【发布时间】:2019-02-14 16:32:10
【问题描述】:
我有一个需要阅读的 javascript 文件。我设法使用 FileReader 将它作为字符串读取,但我想读取在该文件中导出的对象。
这是我的文件的样子:
const carsColor = {
audi: 'blue',
bmw: 'black',
};
export default carsColor;
将其作为字符串读取:
loadFile = async () => {
try {
const response = await fetch(PATH_TO_FILE);
const blob = await response.blob();
let read = new FileReader();
read.onload = function() {
console.log(read.result); // read.result returns the entire file as a string
};
read.readAsBinaryString(blob);
}
catch(e) {
console.log(e);
}
}
有没有办法从文件中获取 carsColor 对象?
谢谢。
【问题讨论】:
-
你试过import语句吗?
-
导入可以与文件的 url 一起使用吗?由于该文件可能存在也可能不存在,因此导入一个不存在的文件会给我使用 webpack 'Module not found'。
-
可以改一下文件格式吗?