or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

ast-operations.mdbrowser-integration.mdindex.mdplugin-system.mdtransformation.mdutilities.md
tile.json

utilities.mddocs/

Utilities

Helper functions for file type checking, option processing, external helper generation, and build tool integration with Babel Core.

Capabilities

File Type Utilities

Functions for determining whether files can be compiled by Babel based on their extensions.

/**
 * Test if a filename ends with a compilable extension
 * @param {string} filename - Filename to test
 * @param {Array<string>} altExts - Alternative extensions (optional)
 * @returns {boolean} True if file can be compiled
 */
function canCompile(filename, altExts);

// Default compilable extensions
canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];

Usage Examples:

const babel = require("babel-core");

// Check if files can be compiled
console.log(babel.util.canCompile("script.js"));     // true
console.log(babel.util.canCompile("component.jsx")); // true  
console.log(babel.util.canCompile("style.css"));     // false
console.log(babel.util.canCompile("module.es6"));    // true

// Custom extensions
console.log(babel.util.canCompile("script.ts", [".ts", ".tsx"])); // true
console.log(babel.util.canCompile("vue.component", [".vue"]));     // false (not .vue)

// Check default extensions
console.log(babel.util.canCompile.EXTENSIONS); // [".js", ".jsx", ".es6", ".es"]

Data Processing Utilities

Functions for converting and processing various data types commonly used in Babel configuration.

/**
 * Create an array from any value, splitting strings by comma
 * @param {any} val - Value to convert to array
 * @returns {Array<string>} Array of strings
 */
function list(val);

/**
 * Create a RegExp from a string, array, or existing regexp
 * @param {any} val - Value to convert to RegExp
 * @returns {RegExp} Regular expression for matching
 */
function regexify(val);

/**
 * Create an array from various types with optional mapping function
 * @param {any} val - Value to convert to array
 * @param {Function} mapFn - Optional mapping function
 * @returns {Array<any>} Processed array
 */
function arrayify(val, mapFn);

/**
 * Convert boolean-like strings to actual booleans
 * @param {any} val - Value to convert
 * @returns {boolean|any} Boolean value or original value if not boolean-like
 */
function booleanify(val);

Usage Examples:

const babel = require("babel-core");
const util = babel.util;

// List function - convert to array
console.log(util.list("a,b,c"));        // ["a", "b", "c"]
console.log(util.list(["x", "y"]));     // ["x", "y"]
console.log(util.list("single"));       // ["single"]
console.log(util.list(null));           // []

// Regexify function - convert to RegExp
console.log(util.regexify("*.js"));     // RegExp for glob pattern
console.log(util.regexify(["*.js", "*.jsx"])); // RegExp matching both
console.log(util.regexify(/test/));     // /test/ (unchanged)

// Arrayify function - convert with optional mapping
console.log(util.arrayify("a,b,c"));    // ["a", "b", "c"]
console.log(util.arrayify(true));       // [true]
console.log(util.arrayify("x,y", s => s.toUpperCase())); // ["X", "Y"]

// Booleanify function - convert to boolean
console.log(util.booleanify("true"));   // true
console.log(util.booleanify("false"));  // false
console.log(util.booleanify("1"));      // true
console.log(util.booleanify("0"));      // false
console.log(util.booleanify("other"));  // "other" (unchanged)

File Filtering

Functions for determining whether files should be ignored based on patterns.

/**
 * Test if a filename should be ignored based on ignore and only options
 * @param {string} filename - Filename to test
 * @param {Array<RegExp|Function>} ignore - Patterns to ignore (optional, defaults to [])
 * @param {Array<RegExp|Function>} only - Only process these patterns (optional)
 * @returns {boolean} True if file should be ignored
 */
function shouldIgnore(filename, ignore, only);

Usage Examples:

const babel = require("babel-core");
const util = babel.util;

// Test file filtering
const ignorePatterns = [/node_modules/, /\.test\.js$/];
const onlyPatterns = [/src\/.*\.js$/];

console.log(util.shouldIgnore("src/index.js", ignorePatterns));           // false
console.log(util.shouldIgnore("node_modules/lib.js", ignorePatterns));   // true  
console.log(util.shouldIgnore("src/test.test.js", ignorePatterns));      // true

// With "only" patterns (exclusive)
console.log(util.shouldIgnore("src/index.js", [], onlyPatterns));        // false
console.log(util.shouldIgnore("lib/index.js", [], onlyPatterns));        // true (not in src/)

// Function patterns
const ignoreFunc = filename => filename.includes('vendor');
console.log(util.shouldIgnore("vendor/lib.js", [ignoreFunc]));           // true
console.log(util.shouldIgnore("src/main.js", [ignoreFunc]));             // false

External Helper Generation

Function for building external helper modules for Babel runtime functions.

/**
 * Build external helpers for Babel runtime functions
 * @param {Array<string>} whitelist - Helper names to include (optional, includes all if not specified)
 * @param {string} outputType - Output format: "global" | "umd" | "var" (defaults to "global")
 * @returns {string} Generated helper code
 */
function buildExternalHelpers(whitelist, outputType);

Usage Examples:

const babel = require("babel-core");

// Build all helpers as global
const globalHelpers = babel.buildExternalHelpers();
console.log(globalHelpers); // Global babelHelpers object

// Build specific helpers as UMD
const umdHelpers = babel.buildExternalHelpers([
  "classCallCheck",
  "createClass", 
  "inherits"
], "umd");
console.log(umdHelpers); // UMD wrapper with specific helpers

// Build as var declaration
const varHelpers = babel.buildExternalHelpers([
  "extends",
  "objectWithoutProperties"
], "var");
console.log(varHelpers); // var babelHelpers = { ... }

// Save to file for external use
const fs = require("fs");
const helpers = babel.buildExternalHelpers(null, "umd");
fs.writeFileSync("babel-helpers.js", helpers);

Node.js Utilities

Re-exported Node.js utility functions for compatibility and convenience.

/**
 * Node.js utility functions (re-exported from 'util' module)
 */
const inherits;  // util.inherits function
const inspect;   // util.inspect function

Usage Examples:

const babel = require("babel-core");
const { inherits, inspect } = babel.util;

// Use inherits for prototype inheritance
function MyClass() {}
function MySubClass() {
  MyClass.call(this);
}
inherits(MySubClass, MyClass);

// Use inspect for debugging
const obj = { a: 1, b: { c: 2 } };
console.log(inspect(obj, { depth: null, colors: true }));

Configuration Processing

Option Validation and Normalization

Utilities used internally for processing Babel configuration options.

// Internal option processing (available through OptionManager)
const babel = require("babel-core");

// Process and validate options
function processOptions(rawOptions) {
  const OptionManager = babel.OptionManager;
  const manager = new OptionManager();
  
  try {
    const normalized = manager.init(rawOptions);
    return normalized;
  } catch (err) {
    console.error("Option processing error:", err.message);
    
    // Use default fallback
    return OptionManager.createBareOptions();
  }
}

// Example usage
const processedOptions = processOptions({
  presets: ["es2015"],
  plugins: "transform-runtime", // Will be normalized to array
  sourceMaps: "true",           // Will be normalized to boolean
  ignore: "node_modules/**"     // Will be converted to regex
});

File Extension Processing

Advanced file extension and pattern matching utilities.

// Build comprehensive file matching logic
function createFileFilter(options = {}) {
  const {
    extensions = babel.util.canCompile.EXTENSIONS,
    ignore = [],
    only = null
  } = options;
  
  return function shouldTransformFile(filename) {
    // Check extension
    if (!babel.util.canCompile(filename, extensions)) {
      return false;
    }
    
    // Check ignore/only patterns
    if (babel.util.shouldIgnore(filename, ignore, only)) {
      return false;
    }
    
    return true;
  };
}

// Usage
const filter = createFileFilter({
  extensions: ['.js', '.jsx', '.ts', '.tsx'],
  ignore: [/node_modules/, /\.test\./],
  only: [/src\//]
});

console.log(filter('src/component.jsx'));      // true
console.log(filter('src/test.test.js'));       // false (ignored)
console.log(filter('lib/utils.js'));           // false (not in 'only')
console.log(filter('src/styles.css'));         // false (wrong extension)

Build Tool Integration

Webpack Integration Helpers

// Helper for webpack babel-loader configuration
function createWebpackBabelConfig(env = 'development') {
  const isDev = env === 'development';
  
  return {
    test: /\.(js|jsx)$/,
    exclude: function(filename) {
      // Use Babel's shouldIgnore for consistent filtering
      return babel.util.shouldIgnore(filename, [/node_modules/], [/src/]);
    },
    use: {
      loader: 'babel-loader',
      options: {
        presets: [
          ['@babel/preset-env', {
            modules: false, // Keep ES6 modules for webpack
            debug: isDev
          }],
          '@babel/preset-react'
        ],
        plugins: isDev ? [
          'react-hot-loader/babel'
        ] : [
          'transform-remove-console'
        ],
        cacheDirectory: isDev // Cache in development
      }
    }
  };
}

Gulp Integration Helpers

// Helper for gulp-babel configuration
function createGulpBabelTask(src, dest, env = 'production') {
  const gulp = require('gulp');
  const babel = require('gulp-babel');
  const sourcemaps = require('gulp-sourcemaps');
  
  return function babelTask() {
    let stream = gulp.src(src)
      .pipe(sourcemaps.init());
    
    // Filter files using Babel utilities
    stream = stream.pipe(require('gulp-filter')(file => {
      return babel.util.canCompile(file.path) && 
             !babel.util.shouldIgnore(file.path, [/node_modules/]);
    }));
    
    return stream
      .pipe(babel({
        presets: [['@babel/preset-env', { 
          targets: env === 'production' ? '> 1%' : 'current node'
        }]]
      }))
      .pipe(sourcemaps.write('.'))
      .pipe(gulp.dest(dest));
  };
}

CLI Tool Helpers

// Helper for building CLI tools with Babel
function createCLITransformer(options = {}) {
  const {
    configFile = '.babelrc',
    extensions = babel.util.canCompile.EXTENSIONS,
    verbose = false
  } = options;
  
  return {
    transformFile(inputPath, outputPath) {
      // Check if file should be transformed
      if (!babel.util.canCompile(inputPath, extensions)) {
        if (verbose) console.log(`Skipping ${inputPath} (unsupported extension)`);
        return Promise.resolve();
      }
      
      return new Promise((resolve, reject) => {
        babel.transformFile(inputPath, {
          babelrc: true,
          filename: inputPath
        }, (err, result) => {
          if (err) {
            reject(err);
          } else {
            require('fs').writeFile(outputPath, result.code, resolve);
            if (verbose) console.log(`Transformed ${inputPath} -> ${outputPath}`);
          }
        });
      });
    },
    
    shouldIgnoreFile(filename) {
      return babel.util.shouldIgnore(filename, [/node_modules/, /\.min\.js$/]);
    }
  };
}

Performance Utilities

Caching Helpers

// Simple cache for transformation results
function createTransformCache() {
  const cache = new Map();
  
  return {
    transform(code, options) {
      const key = JSON.stringify({ code, options });
      
      if (cache.has(key)) {
        return cache.get(key);
      }
      
      const result = babel.transform(code, options);
      cache.set(key, result);
      return result;
    },
    
    clear() {
      cache.clear();
    },
    
    size() {
      return cache.size;
    }
  };
}

// Usage
const cachedTransform = createTransformCache();
const result1 = cachedTransform.transform(code, options); // Transforms
const result2 = cachedTransform.transform(code, options); // Uses cache

Batch Processing

// Batch transform multiple files
async function batchTransform(filePaths, options = {}) {
  const results = [];
  const errors = [];
  
  for (const filePath of filePaths) {
    try {
      // Skip non-compilable files
      if (!babel.util.canCompile(filePath)) {
        continue;
      }
      
      const result = await new Promise((resolve, reject) => {
        babel.transformFile(filePath, options, (err, result) => {
          err ? reject(err) : resolve(result);
        });
      });
      
      results.push({ filePath, result });
    } catch (err) {
      errors.push({ filePath, error: err });
    }
  }
  
  return { results, errors };
}

// Usage
const { results, errors } = await batchTransform([
  'src/index.js',
  'src/utils.js', 
  'src/component.jsx'
], {
  presets: ['@babel/preset-env', '@babel/preset-react']
});

console.log(`Transformed ${results.length} files, ${errors.length} errors`);