简体   繁体   中英

How to import JavaScript functions across files in manner that is simultaneously compatible with Node.js and with browser JavaScript

In vanilla browser-based JavaScript, I can do this:

<html>
<head>
</head>
<body>
    <script type="text/javascript" src="file1.js"></script>
    <script type="text/javascript" src="file2.js"></script>
</body>
</html>

Then:

// file1.js

function abc(foo) {
    console.log("abc received:", foo);
}

And:

// file2.js

abc(36);

...and things behave as expected. (Ie, "abc received 36" is printed to the console.)

How can I include functions from file1.js in file2.js in node.js, so as to preserve the functionality above, while also keeping the web page as-is? Specifically, I would like to keep the html as it appears above, while being able to run

node file2.js

at the command line, and getting abc received 36 at the terminal.

Edit

I found this question with a very similar motivation, by a seemingly more advanced user. But the main link in the answer to that question is dead, and I don't understand how the stated answer works, or what it's supposed to do. Maybe someone can provide me with a MWE tailored to my file1.js , file2.js ?

In order for scripts to be functional as both Node.js modules and browser vanilla (non-modular) scripts, they should be defined as UMD modules .

UMD is basically a boilerplate factory function that detects modular environment and falls back to global variables if needed.

Eg for CommonJS and globals (no AMD) the definition would be:

file1.js

(function (root, factory) {
    if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // Node
        module.exports = factory();
        // Global
    } else {
        root.file1 = factory();
    }
}(this, function () {
    // module body
    function abc(foo) {
        console.log("abc received:", foo);
    }

    return { abc: abc };
}));

file2.js

(function (root, factory) {
    if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // Node
        module.exports = factory(require('./file1'));
        // Global
    } else {
        root.file2 = factory(root.file1);
    }
}(this, function (file1) {
    // module body
    file1.abc(36);
}));

Omitting this boilerplate is the task that bundling tools are supposed to solve, notably Browserify that is intended specifically to bundle CommonJS modules to browser scripts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM