How to use a CommonJS dependency without Browserify? - javascript

I want to use a JavaScript library in a web application which is not a single-page app and does not yet use a module loader.
But the library (virtual-dom) is only published as an npm package for Browserify, and all the examples use require.
How can I use a CommonJS dependency in a client-side app that does not use Browserify or a module loader?

Easy, simply download this file here:
https://github.com/Matt-Esch/virtual-dom/blob/master/dist/virtual-dom.js
and then include it in your page:
<script src="virtual-dom.js"></script>
Now you can access it like:
virtualDom.create(...);
virtualDom.diff(...);
virtualDom.h(...);
virtualDom.patch(...);

The Browserify --standalone option uses "a window global if no module system is found".
The virtual-dom/dist directory is built with the command browserify --standalone virtual-dom index.js > dist/virtual-dom.js and can therefore be used in this way.

Related

Hot to import JS module in browser environment? [duplicate]

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?
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!
Browserify magically lets you do that.
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.
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.
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/
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
There is a good require node.js-like library for client side. It's called wrapup. Check it out kamicane/wrapup

Why use Webpack to bundle applications that run in node environment

For me, Webpack is a bundler for "web" since browsers don't have good support for js module system. Thus using Webpack we could still use "module" way to develop and pack them for browsers.
Webpack has a config option target
module.exports = {
target: 'node'
};
using node webpack will compile for usage in a Node.js-like environment
But NodeJS already support CommonJS modules, why need Webpack to build something that runs in NodeJS environment?
Besides, if you want to compile your javascript, for example, using the ES module, you could just use babel to do so, using es module transform plugins or proper presets.
Why use Webpack, set the target to node and then use babel loader... instead of using babel directly?
I cannot think of the use case of using Webpack to bundle application running in node.
One reason I can think of when to use webpack for node is when you have a node_modules package where it's not compiled yet (Still in ES6).
babel-node won't be able to help you bundle the node_modules packages that need to be transpiled along with the rest of your code
I had to go through this process.. ): This scenario is helpful in Yarn Workspaces where you want your server to depend on another package in your workspace. Where your server will re-update whenever you make changes in the other package with the help of webpack
How to include a few node_modules package in babel-node
Having a single server.js output
instant deployable on a server
no worry about mismatching dependencies compared to your dev environment.

How can I use System.Web.Optimization (.net js bundler) with amd modules?

Now I am working with the project using System.Web.Optimization as js bundler.
How can I use amd modules with this bundler?
define('myModule', function(myModule){})
Now I am obviously getting define is not defined error.
Webpack and r.js can handle dependencies, but I dont want to change bundler yet.
AFAIK System.Web.Optimization is deprecated and there is no method to support it "from the box". Now I am using webpack with es6 modules. I am using this extension to run webpack.

Browserify: using external libraries from within bundle

Our team develops browser side javascript app. We use angularjs as framework and some helper libraries in global namespace. For example: underscore.
We carried out a large piece of code (input/output data tranformation) into a standalone library for unit testing reasons.
Now i try to use browserify with this library. The question is about what the best way to exclude from bundle shared (with main app) dependences (underscore for example).
I tried 2:
Using --external. I have to create bundle from underscore and use it for all code stuff in app. If i understood right this way seems inconvenient.
Using browser property in package.json to replace underscore with stub:
module.exports = _;
I believe that there is more clean approach, but where is it?
You don't have to use --external or something like that. Just include the library like this:
<script src="external/lib.js"></script>
then you can use it within your bundle (without require).
BUT: In my opinion you shouldn't mix global libs with browserify. All benefits of browserify will decrease drastically this way.
Contras:
more than one file to include
worse readability cause fewer `require` statements
RECOMMEND:
create one bundle with all external libs and install them as npm modules.
npm install --save angular
npm install --save lodash
create external bundle:
browserify -r angular -r lodash > external/libs.js
you only have to bundle it once because they should never change. then create main app bundle without external modules:
browserify --no-bundle-external app.js > bundle.js
then include these two bundles to your page:
<script src="external/libs.js"></script>
<script src="bundle.js"></script>

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?
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!
Browserify magically lets you do that.
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.
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.
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/
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
There is a good require node.js-like library for client side. It's called wrapup. Check it out kamicane/wrapup

Categories