User Rating 0.0
Total Usage 0 times
CommonJS Input
AMD Output
Is this tool helpful?

Your feedback helps us improve.

About

JavaScript module systems are not interchangeable. A file using require() and module.exports follows the CommonJS specification designed for Node.js synchronous loading. AMD (define()) targets asynchronous browser environments via RequireJS. Deploying CommonJS code directly in an AMD pipeline causes silent runtime failures: undefined dependencies, broken dependency graphs, and load-order race conditions. This tool performs the same wrapping operation as the RequireJS Optimizer's internal commonJs.convert function. It detects whether a file already contains a define() call and skips conversion if so. It also verifies the presence of CommonJS signatures (require(), exports, or module.exports) before wrapping. Files that match neither pattern pass through unchanged.

Limitations apply. This converter handles standard single-file CommonJS modules. It does not resolve dependency trees, rewrite paths, or handle dynamic require() calls computed at runtime. Circular dependencies remain the developer's responsibility. For multi-file batch conversion, replicate this logic in a Gulp or Grunt pipeline. The wrapping template matches the output of gulp-require-convert and is compatible with RequireJS 2.x and r.js optimizer.

commonjs amd javascript module converter requirejs define gulp module format

Formulas

The conversion follows a deterministic rule-based algorithm rather than a mathematical formula. The logic can be expressed as a decision function:

{
output = input if hasDefine(input) = TRUEoutput = input if hasCJS(input) = FALSEoutput = wrap(input) otherwise

Where hasDefine(input) tests the regex pattern /define\s*\(/ against the source. The function hasCJS(input) tests for the presence of any of these patterns: require("..."), module.exports, or bare exports. references. The wrap function constructs the output as:

output = "define(function (require, exports, module) {" + \n + indent(input) + \n + "});"

Where indent(input) prepends the configured indentation string (default: 4 spaces) to each non-empty line of input. If a shebang line (#!/usr/bin/env node) is detected at position 0, it is extracted and placed above the define() wrapper to maintain compatibility with command-line execution.

Reference Data

FeatureCommonJS (CJS)AMDES Modules (ESM)UMD
SpecificationNode.js / ServerJSRequireJSECMAScript 2015+Universal wrapper
LoadingSynchronousAsynchronousStatic & AsyncBoth
Import syntaxrequire()define() / require()importrequire() or define()
Export syntaxmodule.exportsreturn valueexportmodule.exports
Browser nativeNoNo (needs loader)Yes (modern)No
Node.js nativeYesNoYes (.mjs / type:module)Yes (CJS path)
Tree shakingLimitedNoYesNo
Circular depsPartial (cached)PartialLive bindingsPartial
Dynamic importrequire(expr)require([arr], cb)import()Via CJS or AMD path
Bundler supportWebpack, BrowserifyRequireJS, DojoWebpack, Rollup, ViteAll bundlers
File extension.js / .cjs.js.mjs / .js.js
Conditional exportsRuntime branchingPlugin-basedPackage.json exports mapRuntime branching
Use caseServer-side, legacyLegacy browser appsModern appsLibraries targeting both
Year introduced2009201120152012
Wrapper overheadNone~80 bytesNone~200 bytes

Frequently Asked Questions

The converter checks for the presence of a define( pattern using a regex scan before any transformation. If found, the file is returned unchanged. This prevents double-wrapping and matches the behavior of the RequireJS Optimizer's internal commonJs.convert function. The check is broad: any occurrence of define( in executable code (not inside a string or comment in trivial cases) will trigger the skip.
The wrapping itself works regardless of require() argument type - the code is wrapped verbatim. However, AMD's define() with the simplified CommonJS wrapper relies on RequireJS scanning for string literal require('name') calls to build the dependency array at build time. Dynamic require(variable) calls will not be resolved statically by r.js. They will work at runtime only if the module is already loaded. This is a fundamental AMD limitation, not a converter issue.
Circular dependencies behave differently across module systems. In CommonJS, require() returns a partially-constructed exports object during circular resolution. In AMD's simplified CommonJS wrapper format, RequireJS attempts similar behavior but timing differs due to asynchronous loading. If module A requires B and B requires A, you may get an empty object for the not-yet-initialized module. The recommended fix is to use exports.property = value assignment rather than module.exports = object replacement.
The indentation string (configurable as 2 spaces, 4 spaces, or a tab character) is prepended to every non-empty line of your original source code. Empty lines remain empty to keep the output clean. The define() and closing }); lines themselves are not indented. This produces readable, properly nested output that matches standard RequireJS project conventions.
No. This tool converts only CommonJS (require/module.exports) to AMD (define). ES Modules use a fundamentally different static syntax (import x from "y", export default z) that requires full AST parsing and rewriting, not simple wrapping. Converting ESM to AMD requires tools like Babel with the @babel/plugin-transform-modules-amd plugin. The two transformations are architecturally different.
Yes. The output format matches exactly what r.js produces internally when it encounters a CommonJS module during optimization. The define(function (require, exports, module) { ... }); pattern is the "simplified CommonJS wrapping" format documented in the RequireJS API. r.js will scan the wrapped code for require('string') calls and build the dependency array automatically during the build step.