Languages
[Edit]
EN

Browserify - compile Node.js JavaScript / EcmaScript / ES6+ to browser JavaScript

9 points
Created by:
DEX7RA
220

In this article, we would like to show how to compile any Node.js JavaScriptEcmaScript code to browser JavaScript with Browserify (second section contains the minified version).

Quick solution:

npx browserify -t [ babelify --presets [ @babel/preset-env ] ] input.js -o output.js

or

npx browserify -t [ babelify --presets [ @babel/preset-env ] ] -g uglifyify input.js -o output.js

 

Project structure:

Node.js JavaScript / EcmaScript compilation to browser JavaScript with Browserify.
Node.js JavaScript / EcmaScript compilation to browser JavaScript with Browserify.

Example: src/index.js file:

const jsdom = require('jsdom');

module.exports = jsdom.JSDOM;

 

Compilation to browser JavaScript

Creating project

npm init
npm install --save jsdom
npm install --save-dev browserify babelify @babel/core @babel/preset-env

Note: @babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms are needed by your target environment(s).
https://babeljs.io/docs/en/babel-preset-env.

Code compilation (run the following command):

npx browserify -t [ babelify --presets [ @babel/preset-env ] ] ./src/index.js -o build/bundle.js

package.json file example:

{
  "name": "jsdom-bundle",
  "version": "1.0.0",
  "dependencies": {
    "jsdom": "^16.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.5",
    "babelify": "^10.0.0",
    "browserify": "^17.0.0"
  }
}

 

Compilation to minified browser JavaScript

Creating project

npm init
npm install --save jsdom
npm install --save-dev browserify babelify @babel/core @babel/preset-env uglifyify terser

Code compilation (run the following command):

npx browserify -t [ babelify --presets [ @babel/preset-env ] ] -g uglifyify ./src/index.js -o build/bundle.js

Note: got to this article to know how to achieve better *.js files compression.

package.json file example:

{
  "name": "jsdom-bundle",
  "version": "1.0.0",
  "dependencies": {
    "jsdom": "^16.6.0"
  },
  "devDependencies": {
    "@babel/core": "^7.14.6",
    "@babel/preset-env": "^7.14.5",
    "babelify": "^10.0.0",
    "browserify": "^17.0.0",
    "terser": "^5.7.0",
    "uglifyify": "^5.0.2"
  }
}

 

References

  1. https://github.com/browserify/browserify
  2. https://github.com/babel/babelify
  3. https://www.npmjs.com/package/uglifyify
  4. https://github.com/terser/terser
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join