es module to common js code helper
rollup.config.js
import commonjs from "@rollup/plugin-commonjs";
import cjsShim from "rollup-plugin-cjs-shim";
export default {
input: "index.js",
output: {
file: "index.cjs",
format: "cjs",
},
plugins: [cjsShim(), commonjs()],
};
-
import.meta.filename
=> __filename -
import.meta.dirname
=> __dirname -
const/var/let require = createRequire(import.meta.url)
=>-
import { createRequire } from "module"
=>
-
example input
import { createRequire } from "module";
export const filename = import.meta.filename;
export const dirname = import.meta.dirname;
const require = createRequire(import.meta.url);
require("./package.json");
output
"use strict";
const filename = __filename;
const dirname = __dirname;
require("./package.json");
exports.dirname = dirname;
exports.filename = filename;
add replacement
import cjsShim, { defaultReplacements } from "rollup-plugin-cjs-shim";
cjsShim({
replacements: [
...defaultReplacements,
{
// replacement
},
],
});