cjs-esm-exports
A WASM module to parse commonjs exports for ESM, powered by swc in rust.
Installation
npm install cjs-esm-exports
for yarn
users:
yarn add cjs-esm-exports
Usage
Types:
export function parse(
specifier: string,
code: string,
node_env?: 'development' | 'production',
call_mode?: boolean,
): {
exports: string[],
reexports: string[],
};
Example:
const { parse } = require('cjs-esm-exports');
const { exports } = parse('index.cjs', `
/* exports.ignore = "not detected"; */
exports.a = "a";
module.exports.b = "b";
Object.defineProperty(exports, "c", { value: "c" });
Object.defineProperty(module.exports, "__esModule", { value: true })
const key = "foo"
Object.defineProperty(exports, key, { value: "e" });
`);
const { reexports } = parse('index.cjs', `
module.exports = require("./lib");
`);
const { reexports } = parse('index.cjs', `
const foo = 'bar'
const obj = { baz: 123 }
module.exports = { foo, ...obj, ...require("./lib") };
`);
const { exports } = parse('index.cjs', `
module.exports.a = "a";
if (true) {
exports.foo = "bar";
}
const mtype = "cjs";
if (mtype === "cjs") {
exports.cjs = true;
} else {
exports.esm = true;
}
if (false) {
exports.ignore = "ignore";
}
`);
const { exports } = parse('index.cjs', `
(function () {
exports.foo = "bar"
if (true) {
return
}
exports.ignore = '-'
})();
{
exports.baz = 123
}
exports.__esModule = true
`);
const { reexports } = parse('index.cjs', `
if (process.env.NODE_ENV === "development") {
module.exports = require("./index.development")
} else {
module.exports = require("./index.production")
}
`, 'development');
const { exports } = parse('index.cjs', `
function Fn() {
return { foo: "bar" }
}
module.exports = Fn()
`);
const { exports } = parse('index.cjs', `
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.MMDParser = global.MMDParser || {})));
}(this, function (exports) {
exports.foo = "bar";
}))
`);
const { reexports } = parse('index.cjs', `
module.exports = require("./lib")()
`);
const { reexports } = parse('lib.cjs', `
module.exports = function() {
return { foo: 'bar' }
}
`, 'production', true);
Development Setup
You will need rust 1.30+ and wasm-pack.
Build
wasm-pack build --target nodejs
Run tests
cargo test --all