I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can\'t find any tutorial or docs on how to use no
SubStack on github has a module called node-browserify.
It will compress and bundle your modules and deliver it as a single js file, but you use it just like Node.js (example from module readme):
<html>
<head>
<script type="text/javascript" src="/browserify.js"></script>
<script type="text/javascript">
var foo = require('./foo');
window.onload = function () {
document.getElementById('result').innerHTML = foo(100);
};
</script>
</head>
<body>
foo = <span style='font-family: monospace' id="result"></span>
</body>
</html>
From the module description:
Browserify
Browser-side require() for your node modules and npm packages**
Browserify bundles everything ahead-of-time at the mount point you specify. None of this ajaxy module loading business.
More features:
- recursively bundle dependencies of npm modules
- uses es5-shim for browsers that suck
- filters for {min,ugl}ification
- coffee script works too!
The accepted answer is correct when it comes to RequireJS. But, fast-forward to 2020 and we now have ES modules pretty much on every browser except IE <= 11.
So, to answer your question "how to use node.js module system on the clientside". Let's start with the fact that you could leverage ES modules already, e.g.
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>Hello 2020</title>
<!-- load the app as a module, also use defer to execute last -->
<script type="module" src="./app.js"></script>
</head>
<html lang="en">
<body>
<div id="app">
<h1>Demo</h1>
</div>
</body>
</html>
app.js
import { hello } from './utils.js'
window.addEventListener('DOMContentLoaded', function (e) {
document.getElementsByTagName('h1')[0].innerText = hello('world');
});
util.js
function hello(text) {
return `$hello {text}`;
}
export { hello };
Now let's assume you want to use an npm package in your browser (assuming this package can run on both browser and node). In that case, you may want to check out Snowpack.
Snowpack 2.0 is a build system designed for this new era of web development. Snowpack removes the bundler from your dev environment, leveraging native ES Module (ESM) support to serve built files directly to the browser
In other words, you can use npm packages thus allowing you to use the "node module system" in your client application.
If you'd like to write code for browser with same style modules as you do for Node.js, try Webmake. Take a look also at simple prototype of application build that way: SoundCloud Playlist Manager
Node.js
is a serverside application where you run javascript on the server. What you want to do is use the require
function on the client.
Your best bet is to just write the require
method yourself or use any of the other implementations that use a different syntax like requireJS.
Having done a bit of extra research it seems that no-one has written a require module using the commonJS syntax for the client. I will end up writing my own in the near future, I recommend you do the same.
[Edit]
One important side effect is that the require
function is synchronous and thus loading large blocks of javascript will block the browser completely. This is almost always an unwanted side-effect. You need to know what you're doing if you're going to do this. The requireJS syntax is set up so that it can be done asynchronously.
I would recommend Webpack which automates node module loading, dependencies, minification, and much more.
To use node modules in your project, first install node.js on your machine. The package management system NPM should be installed along the way. If you have already installed node.js, update Node.js and NPM to the latest version.
Open your project in your code editor and inititialize npm by typing npm init -y
to the command line. Next, install webpack locally by typing npm install webpack webpack-cli --save-dev
. (--save-dev
means these dependencies are added to the devDependencies
section of your package.json
file which are not required for production)
Follow the tree structure below to reconstruct your project folder:
yourProjectName
|- package.json
|- /dist
|- index.html
|- /src
|- index.js
Create a dist
folder to hold all distribution files and move index.html
to that folder. Next, create a src
folder for all source files and move your js file to that folder. You should use the exact same file and folder names as appeared in the tree structure. (these are the default of Webpack but you can configure them later by editing webpack.config.js
)
Remove all <script>
importations in index.html
and add <script src="main.js"></script>
before the </body>
tag. To import other node modules, add import statements at the beginning of your index.js
file. For example, if you want to import lodash
, just type import _ from 'lodash';
and proceed to use the _
in your index.js
file.
NOTE: Don't forget to first install the node package first before importing it in JS. To install lodash
locally, type npm install lodash
. Lodash will be automatically saved to your production dependencies in package.json
Finally, run webpack by typing npx webpack
in your command line. You should see main.js
generated in the dist
folder for you by Webpack.
The above guide provides only the most basic way to use Webpack. To explore more useful use cases, go to the official tutorial of Webpack. It provides extremely comprehensive tutorials on topics such as asset management, output management, guides for development and production, etc.
https://webpack.js.org/guides/getting-started/
Browserify magically lets you do that.