Failed attempt at implementing the Node.js CommonJS require() module system for the browser, without any build step
For a working tool, see browserify (requires a build step), or for
the future, see ES6 modules / import/export
and <script type="module">
.
The main problem with using ordinary browser <script>
tags to include unmodified CommonJS modules
is that <script>
executes the script in the global context (window
).
function foo()
will create a new function window.foo
, and you cannot delete foo
later since
function declarations cannot be deleted.
window.foo
can be reassigned (window.foo = null
), but then any calls to that function will
fail.
Browserify's solution is to wrap CommonJS modules in an
immediately-invoked function expression,
therefore creating a new scope and avoiding the module from polluting the global scope. This means
a build step is required, to add (function() { ... })();
around the module source code, so
<script src>
cannot be used directly on the original CommonJS module files.
(XMLHttpRequest / fetch + eval is another possible "solution", with its own issues.)
MIT