babel-plugin-transform-dirname-filename

raw JSON →
1.1.0 verified Sat Apr 25 auth: no javascript

Babel plugin (v1.1.0) that rewrites __dirname and __filename to static values at compile time, preserving original source file paths in bundled output. Stable, no recent updates since 2022. Different from other solutions (e.g., webpack.DefinePlugin) as it works specifically with Babel for transpilation, ensuring that after bundling, __dirname and __filename reflect the source file location rather than the output directory. Suitable for Node.js packages distributed as compiled code.

error Error: Plugin/Preset files are not allowed to export objects, only functions. In /path/to/node_modules/babel-plugin-transform-dirname-filename/lib/index.js
cause The plugin exports a default object, but Babel 7 expects a function. This package is designed for Babel 6.
fix
Use Babel 6 or switch to @babel/plugin-transform-dirname-filename for Babel 7 compatibility.
error SyntaxError: Unexpected token / in JSON at position 0
cause Using plugin in .babelrc with typographical errors (e.g., missing quotes or trailing comma).
fix
Validate .babelrc with a JSON validator or run npx babel --version to check config.
gotcha Only works with Babel 6.x. For Babel 7+, use @babel/plugin-transform-dirname-filename (fork) or consider alternatives like babel-plugin-transform-dirname-filename (compatible with Babel 7 via wrapper).
fix For Babel 7, install @babel/plugin-transform-dirname-filename or use the community fork.
breaking Plugin rewrites __dirname and __filename at compile time to absolute paths of the source files. This may leak filesystem structure and break if the output is moved or used in a different environment.
fix Use relative paths or ensure the built output is consumed in an environment with the same source structure.
gotcha Does not transform require() calls. Only __dirname and __filename are replaced.
fix If you need to transform require paths, combine with other plugins like babel-plugin-module-resolver.
npm install babel-plugin-transform-dirname-filename
yarn add babel-plugin-transform-dirname-filename
pnpm add babel-plugin-transform-dirname-filename

Shows installation, Babel config, and expected behavior: __dirname/__filename are rewritten to source file paths.

// Install: npm install --save-dev babel-plugin-transform-dirname-filename
// .babelrc
{
  "plugins": ["transform-dirname-filename"]
}

// src/index.js
console.log(__dirname);
console.log(__filename);

// Run: npx babel src --out-dir build
// Output build/index.js will contain static paths from source