Read exported variable from remote js file

落爺英雄遲暮 提交于 2019-12-25 02:46:25

问题


I have a javascript file that I need to read. I managed to read it as a String using FileReader, but I want to read the object that is exported in that file.

This is how my file looks:

const carsColor = {
    audi: 'blue',
    bmw: 'black',
};

export default carsColor;

Read it as a String:

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);
    }
}

Is there a way to get the carsColor object from the file?

Thanks.


回答1:


Change your file to return only json and parse it

the file

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

the load function

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);
    }
}



回答2:


The Fetch API does not load JS modules, but files. It does not evaluate your JavaScript file.

I would instead use a bundler for the source code (such as webpack). Then you'll be able to use your JavaScript module with require():

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

console.log(carColors.audi);


来源:https://stackoverflow.com/questions/54685597/read-exported-variable-from-remote-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!