
Product
Rust Support Now in Beta
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
Transform CommonJS modules to a web browser suitable format with minimal code overhead.
There are many existing tools to transform CommonJS modules to a browser format
(examples: BrowserBuild,
Browserfiy,
OneJS,
modulr,
stitch).
Most of the them emulate the CommonJS environment and provide features
like client side versions of native node.js modules and require()
.
However if you only want to use the basic CommonJS syntax such tools unnecessarily bloat your project´s effective code size.
cjs2web transforms a CommonJS module and all its dependencies to a single script for the browser using the Module Pattern. This results in code which contains almost no overhead and can also be minified very well.
Supported features:
require()
for local modulesexports
module.exports
Unsupported features (now and probably in the future):
require()
for third party modulesrequire()
for files which do not have a "js" extensionthis
refers to window, not to module.exports
process
does not existglobal
does not existrequire()
does not existRoadmap for future features:
require()
for browser globals such window and documentnpm install cjs2web -g
For most projects the command line usage should be sufficient.
cjs2web <filename>
Options:
-b, --basePath base path to exclude from generated object names [string]
-p, --prefix prefix to add to the generated object names [string] [default: "__"]
-c, --combine combines all transformed modules to one script output [boolean]
-i, --iife wrap code in an immediately invoked function expression [boolean]
-o, --output filename to write the generated output to [string]
-w, --watch watch transformed files for change and automatically re-execute [boolean]
Normally you will want to enable the combine option. Otherwise the transformation output will not be a string of code but raw module data. The iife option wraps your code in an immediately invoked function expression to reduce global variables and can only be enabled in combination with combine.
The prefix option is very important and can lead to unexpected results if not provided. Therefore it defaults to "__". Consider the following example:
// index.js
var helper = require('./helper');
helper.doSomething();
// helper.js
exports.doSomething = function() { /*...*/ };
Without a prefix the transformation of the above would result in:
var helper = (function(module) {
var exports = module.exports;
exports.doSomething = function() { /*...*/ };
return module.exports;
}({exports: {}});
var index = (function(module) {
var helper = helper; // THIS WILL NOT WORK AS EXPECTED
helper.doSomething();
return module.exports;
}({exports: {}});
The helper variable inside the index object hides the variable from the outer scope and therefore results in assigning the value of the local variable to itself (which is undefined).
Recommendation: Always use a distinct and non conflicting prefix such as module_ or cjs_.
When an output name is provided the result is written to the disk and not to the standard output.
The watch option causes cjs2web to watch the main module and all its dependencies and re-execute the transformation whenever one of these files changes.
The transform
function accepts an options object of which fileName
is the only mandatory property.
Other option properties have the same names as the explicit parameters of the command line tool.
The return value is a Deferred object.
var cjs2web = require('cjs2web');
cjs2web.transform(options).then(function(result) {
// do something with result
});
CommonJS code:
// src/index.js
var two = require('./numbers/two');
var three = require('./numbers/three');
var sum = require('./calculation/sum');
console.log(sum(two, three));
// src/numbers/two.js
module.exports = 2;
// src/numbers/three.js
module.exports = 3;
// src/calculation/sum.js
module.exports = function(a, b) { return a + b; };
Transformation call:
node cjs2web ./src/index.js --basePath ./src --prefix cjs_ --combine --iife
Transformation result:
(function(){
var cjs_numbers_two = (function(module) {
module.exports = 2;
return module.exports;
}({exports: {}}));
var cjs_numbers_three = (function(module) {
module.exports = 3;
return module.exports;
}({exports: {}}));
var cjs_calculation_sum = (function(module) {
module.exports = function(a, b) { return a + b; };
return module.exports;
}({exports: {}}));
(function(module) {
var two = cjs_numbers_two;
var three = cjs_numbers_three;
var sum = cjs_calculation_sum;
console.log(sum(cjs_numbers_two, cjs_numbers_three));
return module.exports;
}({exports: {}}));
}());
Minified result using Closure Compiler with Simple Optimizations:
(function(){var a={},a=function(a,b){return a+b};console.log(a(2,3))})();
Minified result using Closure Compiler with Advanced Optimizations:
console.log(5);
FAQs
Transform CommonJS modules to a web browser suitable format
We found that cjs2web demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.