babel-file

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

Utility to easily construct a Babel File object with code, AST, and path. v3.0.0 (latest) – stable, low maintenance. Provides a convenient wrapper around Babel core's File object, parsing code with Babel and returning the full file structure. Key differentiator: simplifies setup for Babel plugins/tools by handling File creation and error formatting. Requires Babel 7+ and babylon-options for parser options.

error Cannot find module 'babel-file'
cause Package not installed or not in node_modules
fix
Run npm install babel-file
error createFile is not a function
cause Tried named import instead of default import
fix
Use import createFile from 'babel-file'
error The 'parserOpts' option is not supported
cause Passed incorrect options format
fix
Ensure parserOpts matches Babel's parser options
error Cannot read property 'code' of undefined
cause File creation failed due to invalid code
fix
Check that code string is valid JavaScript
breaking Version 3.0.0 dropped support for Node.js < 10 and Babel < 7.
fix Upgrade Node.js and Babel to required versions.
deprecated babylon-options package is deprecated; use Babel's parser options directly.
fix Replace with inline parser options obj.
gotcha File object properties (code, ast, path) are not updated if you mutate the parsed code.
fix Re-create File object after modifications.
gotcha Missing or invalid parser options may cause crashes without informative error messages.
fix Validate parser options same as in Babel core.
npm install babel-file
yarn add babel-file
pnpm add babel-file

Creates a Babel File object from source code, parsing with given options.

import createFile from 'babel-file';
import createBabylonOptions from 'babylon-options';

const code = 'const x = 1;';
const parserOpts = createBabylonOptions({ stage: 2 });
const file = createFile(code, { filename: 'example.js', parserOpts });

console.log(file.code);
console.log(file.ast);
console.log(file.path);