require a module with webpack

ε祈祈猫儿з 提交于 2019-12-21 07:22:10

问题


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 want to be able to require a module after the build. (require is not defined into the global context).

Is it possible ?

Thx


回答1:


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.



来源:https://stackoverflow.com/questions/23365846/require-a-module-with-webpack

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