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

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

Related

How to bundle npm packages for vanilla JavaScript frontend development and production builds on CDN servers?

I have a vanilla HTML/CSS/JavaScript site (repository) which uses ES6 modules. It can be successfully deployed to GitHub pages and Netlify.
In my HTML, I import main.js like this:
<script src="js/main.js" type="module" defer></script>
In my main.js file, I import other modules I have made like this:
import * as data from './data.js';
import displayUserCard from './displayUserCard.js';
Now I want to also install and import npm modules to use on my site just as I use my own code on my site.
I install lodash like this:
npm i lodash
Then in my main.js file, I import lodash like this, just as I do in my Node apps:
import _ from 'lodash';
This of course doesn't work and gives me the following error, since we are now in the browser and not in a Node app:
^Uncaught TypeError: Failed to resolve module specifier "lodash". Relative references must start with either "/", "./", or "../".^
Researching this, I understand that such a development environment needs a web bundler, but I find everything from dated tools such as Browserify and RequireJS, to over-complex tools such as WebPack, to newer bundlers such as Parcel, Vite and Snowpack which all don't seem to address this problem of easily bundling npm packages for both development and production builds.
What is the most straight-forward way in 2021/2022 to use node modules such as lodash in vanilla HTML/CSS/JavaScript frontend apps so that they can be bundled, built and deployed at CDNs like GitHub pages, Netlify and Vercel?
What you need to do is install a javascript bundler that translates and stores all the needed modules(e.g lodash) in an accessible place for your browser to find.
Watch this video, its straight to the point and sums up everything.

CSVto json client side [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

Including node modules in HTML

I'm struggling to get my head around how npm manages dependencies - in terms of how they are actually referenced in HTML.
Say I have a specific version of a plugin installed, which includes a version number in its path or file name - if npm is configured to update to a new minor release - the files referenced via script tags will no longer be present.
I've also read that exposing node_modules path is incorrect and should be avoided.
How then should these files be referenced so that they are loaded and so version updates do not break a site?
The idea is that you use these modules in your code. Let's say you have a main.js file which has your application, then you import modules using import $ from 'jquery'; (this could depend on your configuration, you could also use 'require'). Then use a tool like browserify which is going resolve all your dependencies for you and package it into a nice file which can then be loaded into your browser.
This is only one setup out of many so this could vary, for example if you use webpack this will be different but the idea is the same, you import what you need into your main.js.
npm uses package.json file as reference to build dependency map. And installs all dependencies in node_modules folder. When you publish an update to your module, you also publish a new version of package.json file which will include modifications to dependencies.
So short answer is - package.json file... I hope you can figure things out from this.

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