简体   繁体   中英

Writing webpack browser code that works without webpack

I'm making a webpack project, but I would like to keep it working even without webpack. Specifically I need to transpile script loading that my native project does to webpack's require system.

For example:

const Library = await require_script_promise("./Library.js");

Should become (for webpack):

const Library = require("./Library.js");

How should I do that?

I created this replacement require function:

/**
 Polyfill for using require without webpack **/
if (typeof require != "function") {
    function require(path) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", path, true);
            xhr.addEventListener("load", function () {
                try {
                    var module = { exports: {}, path: path };
                    eval(this.responseText);
                    resolve(module.exports);
                }
                catch (anyError) {
                    reject(anyError);
                }
            });
            xhr.addEventListener("error", reject);
            xhr.send();
        });
    }
}

It seems to work quite well using await :

const Library = await require("./Library.js");

Webpack apparently handles the await as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM