require is not defined error with browserify

前端 未结 4 1311
余生分开走
余生分开走 2020-12-02 17:17

I\'m new to browserify and trying to load npm modules in browser but I\'m getting the following error:

Uncaught ReferenceError: require is not defined

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 17:39

    I personally prefer to keep my library code and application code seperate. So i also create something like a bundle.js and a script.js.

    there is a simple workaround, that makes this work. This is somewhere in my browserify-file:

    window.require = require;
    

    this will expose require into the "global" namespace. You can then require all you want from your script.js.

    You do give up ONE advantage, though: you'll have to include all the required libraries in your browserify file. You don't get the luxury of it finding all your dependencies, then!

    I fully expect people to cry "dirty hack" or "this is not how it's meant to be". Yes, maybe. But I want those files seperate. And as long as i don't include anything else that is called "require", i'll be fine, thank you very much.

    Sometimes one global can make all the difference.

提交回复
热议问题