EN
Browserify - compile Node.js JavaScript / EcmaScript / ES6+ to browser JavaScript
9
points
In this article, we would like to show how to compile any Node.js JavaScript / EcmaScript 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:
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-envis 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
*.jsfiles 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"
}
}