How to use JS require() without Node.js

2019-04-21 05:04发布

问题:

This is probably a lame question, but how can you achieve the same thing as require() (Node.js) in regular JavaScript?

Some help would really be appreciated.

回答1:

There are several services that let you do this.

The most popular is Browserify.

Basically, it entails going through the file reading through the syntax tree and converting it to the a style similar to what RequireJS does.

Note that this requires an extra compilation step. (We will eventually get modules in ES6 though so there's that :) )



回答2:

http://requirejs.org/docs/start.html

A module loader called RequireJS exists for in-browser use without the use of Node.js or Rhino.

To use it download and save the script and include it in your page

<!DOCTYPE html>
<html>
    <head>
        <title>My Sample Project</title>
        <!-- data-main attribute tells require.js to load
             scripts/main.js after require.js loads. -->
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
        <h1>My Sample Project</h1>
    </body>
</html>

The data-main attribute will point to your main script where you can load the rest of your scripts using:

require(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until
    //util's dependencies have loaded, and the util argument will hold
    //the module value for "helper/util".
});

Checkout the documents at http://requirejs.org for more information.