【问题标题】:Read exported variable from remote js file从远程 js 文件中读取导出的变量
【发布时间】: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'。
  • 可以改一下文件格式吗?

标签: javascript async-await


【解决方案1】:

更改您的文件以仅返回 json 并解析它

文件

{
    audi: 'blue',
    bmw: 'black',
}

加载函数

loadFile = async () => {
    try {
        const response = await fetch(PATH_TO_FILE);
        const blob = await response.blob();
        let read = new FileReader();
        read.onload = function() {
            console.log(JSON.parse(read.result)); 
        };
        read.readAsBinaryString(blob); 
    }
    catch(e) {
        console.log(e);
    }
}

【讨论】:

  • 谢谢。我想过将我的文件从 js 修改为 json,但我现在需要看看它是否是一个好的解决方案。如果我没有找到与 js 文件不同的解决方案,我会将它们转换为 json。
  • 最后我将js文件转换为json。但是我没有使用response.blob(),而是response.json()。所以我不需要FileReader,我马上就得到了json数据。
【解决方案2】:

Fetch API 不加载 JS 模块,而是加载文件。它不会评估您的 JavaScript 文件。

我会改为使用打包器来获取源代码(例如 webpack)。然后你就可以通过require()使用你的JavaScript模块了:

// either this
const carColors = require('./carColors');
// or this
import carColors from './carColors';

console.log(carColors.audi);

【讨论】:

  • 我不能使用 require,因为 carColors 文件可能存在也可能不存在。即使我在 try catch 块中需要,webpack 也会给我“找不到模块”。请参阅我的其他问题了解更多信息:stackoverflow.com/questions/54679716/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多