how to use node.js module system on the clientside

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 nodejs clientside, ie without using node application.js

I included node.js like this in my html page:

<script type="text/javascript" src="node.js"></script>

Note that I didn't make nodejs on my local machine, I'm on Windows anyway (I'm aware of the Cygwin option). When I want to use the require function in my own javascript it says it's undefined.

var logger = require('./logger');

My question is, is it possible to use nodejs like this?

Answers:

Answer

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.

Answer

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!
Answer

Webpack

I would recommend Webpack which automates node module loading, dependencies, minification, and much more.

Installation

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.

Usage

Initialization

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)

Reorder Folder Structure

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)

Refactor dependencies

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

Run Webpack

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.

Additional resources

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.

Reference

https://webpack.js.org/guides/getting-started/

Answer

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

Answer

There is a good require node.js-like library for client side. It's called wrapup. Check it out kamicane/wrapup

Answer

Browserify magically lets you do that.

Answer

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". You could leverage ES modules already, e.g.

<!DOCTYPE html>
<head>
  <meta charset="utf-8" />
  <title>Hello 2020</title>
  <script
    src="https://code.jquery.com/jquery-3.5.1.min.js"
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
    crossorigin="anonymous"
  ></script>
  <!-- load the app as a module, also use defer to execute last -->
  <script defer 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'

(function () {
    $('#app').fadeOut(2000, function(e) {
        console.log(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 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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.