require a module with webpack

前端 未结 1 1483
北荒
北荒 2021-02-19 02:36

I use Webpack in order to build my javascript of my website.

Everything work perfectly but I would like to call require into a template (added dynamically).

I wa

相关标签:
1条回答
  • 2021-02-19 03:17

    An option which is available to you now is to create a context which you expose globally on window. I've had success using the following snippet:

    // Create a `require` function in the global scope so that scripts that have
    // not been webpack'd yet can still access them.
    window["require"] = function (module) {
        return require("./public_modules/" + module + ".js");
    }
    

    Basically what you're doing is exposing a folder to webpack and telling it to pack all the files in that folder in to a chunk. You can then type var moduleName = require("module-name") outside of a webpack'd script.

    As long as the above snippet is inside a file which gets bundled and evaluated, you will have a function defined on window (coincidentally named "require" but you can call it anything) which will use webpack's require functionality.

    0 讨论(0)
提交回复
热议问题