Converts source RequireJS modules from AMD to ESM format.
If you enabled usage of ESM modules in your RequireJS project (using requirejs-babel7, requirejs-esm or requirejs-esm-preprocessor, for example), you might want to convert all your code base to the ESM format to follow the same consistent coding standard and use the same set of tools to build, test and analyse your sources.
Convert all JavaScript sources in the project's subdirectories:
❯ requirejs-to-esm '*/**/*.js' '!node_modules'
lib/impl/analyse.js: converted
lib/impl/convert.js: converted
lib/index.js: multiple statements
test/index.js: converted
The file lib/index.js
wasn't an AMD module. (It didn't contain a single define
or require
statement.) It will need an inspection and manual conversion.
This module can be installed globally using NPM, PNPM or Yarn. Make sure, that you use Node.js version 14 or newer.
npm i -g requirejs-esm-converter
pnpm i -g requirejs-esm-converter
yarn add --global requirejs-esm-converter
requirejs-to-esm [option...] [<pattern> ...]
You can use BASH patterns for including and excluding files (only files). Patterns are case-sensitive and have to use slashes as directory separators. A pattern to exclude from processing starts with "!".
-d|--[no-]dry-run only log results, no writing to files
-p|--[no-]print write to stdout instead of overwriting files
-V|--version print version number
-h|--help print usage instructions
Files will overwritten with the converted output, if they are recognised as AMD modules and if the dry-run mode is not enabled.
requirejs-to-esm '**/*.js' '!node_modules'
requirejs-to-esm -d "lib/*.js"
echo "define({})" | requirejs-to-esm"
convert(source: string): { code: string, warnings: string[] }
The function convert
converts the source
in AMD to code
in ESM, optionally returning warnings
. If the conversion is impossible because the input is not an AMD module, it will throw ConvertError
. If the source file cannot be parsed, it will throw SyntaxError
.
import { convert } from 'requirejs-to-esm'
const input =`define(["test"], function (test) {
"use strict";
console.log('imported:', test);
return 42; // ultimate answer
});`
const { code } = convert(input)
console.log(code)
// Result:
//
// import test from "test";
//
// console.log('imported:', test);
// export default 42; // ultimate answer
In lieu of a formal styleguide, take care to maintain the existing coding style. Lint and test your code.
Copyright (c) 2022-2024 Ferdinand Prantl
Licensed under the MIT license.