Babel paths.macro
raw JSON → 3.0.1 verified Sat Apr 25 auth: no javascript
A Babel macro that provides compile-time access to file path information like __dirname and __filename, returning static values rather than runtime variables. Current version 3.0.1. It uses babel-plugin-macros for integration. Key differentiators: no need for __filename polyfills in Node ESM, works with bundlers that support macros, and supports multiple path forms (base, file, extension, filename, npmRoot, gitRoot). Commonly used in tooling and build-time code generation.
Common errors
error Error: Cannot find module 'paths.macro' ↓
cause Missing macro dependency or babel not configured to transform macros.
fix
Install paths.macro, babel-plugin-macros, and add 'macros' to babel plugins array.
error SyntaxError: Unexpected token export ↓
cause Trying to use ESM import syntax without a bundler/transpiler like Babel.
fix
Ensure your project uses Babel with babel-plugin-macros configured to transform the macro imports.
error TypeError: (0 , _pathsMacro.default) is not a function ↓
cause CommonJS require syntax used for a macro import, which is not supported.
fix
Change const base = require('paths.macro') to import base from 'paths.macro'.
Warnings
gotcha paths.macro only works with babel-plugin-macros. Without it, imports will not be transformed and will likely cause runtime errors. ↓
fix Install and configure babel-plugin-macros according to the README.
gotcha The macro transforms source files at build time; the values are hardcoded strings, not runtime variables. ↓
fix Understand that these values cannot be changed programmatically. Use environment variables or dynamic resolution if runtime flexibility is needed.
gotcha In versions prior to 3.0.0, the default export was 'fileAbsolute' instead of 'base'. This is a breaking change. ↓
fix Update imports to use 'base' for the directory path, or import 'fileAbsolute' explicitly if needed.
deprecated The 'wd' export (working directory) is deprecated in v3. Use 'base' or 'npmRoot' instead. ↓
fix Replace 'wd' with the appropriate path export.
Install
npm install paths.macro yarn add paths.macro pnpm add paths.macro Imports
- default (base) wrong
const base = require('paths.macro')correctimport base from 'paths.macro' - filename wrong
import filename from 'paths.macro'correctimport { filename } from 'paths.macro' - file
import { file } from 'paths.macro' - fileAbsolute
import { fileAbsolute } from 'paths.macro' - npmRoot
import { npmRoot } from 'paths.macro' - gitRoot
import { gitRoot } from 'paths.macro'
Quickstart
// input.js
import base, { filename, file, extension } from 'paths.macro';
console.log('base:', base); // "/src/"
console.log('file:', file); // "input.js"
console.log('filename:', filename); // "input"
console.log('ext:', extension); // ".js"