Skip to content

Using __func__ like C++, this plugin will repace it with the current function name(ignores arrow function context)

License

Notifications You must be signed in to change notification settings

baendlorel/rollup-plugin-func-macro

Repository files navigation

rollup-plugin-func-macro

Using __func__ and __file__ like C++ to get current function name and file name (ignores arrow function context) ✨

npm version npm downloads License: MIT Codacy Badge

🎉 Stable Release v1 - Production ready with comprehensive bug fixes and enhanced features!

🦋 More Rollup Plugins you might be interested in:

For more awesome packages, check out my homepage💛

Node version ≥ v14.18.0

Features ✅

  • 🎯 Dynamic Method Names: Supports computed property methods like ['dynamicMethod'](){ ... }
  • 🔀 Variable Embedding: Replace __func__ and __file__ anywhere in expressions and assignments
    • __func__ provides current function name
    • __file__ provides current file name
  • 📝 String Replacement: Automatically replaces identifiers inside string literals and template strings
  • 🔧 Selective Disabling: Set identifiers to null to disable replacements
  • 🎯 TypeScript Support: After installation, you can add import 'rollup-plugin-func-macro' in your global.d.ts file. Then __func__ and __file__ will be available in your projects with full type support! ✨
  • 🛡️ Robust Error Handling: Gracefully handles edge cases and syntax errors

Installation 📦

pnpm add -D rollup-plugin-func-macro

Usage 🛠️

Basic Setup

Options are introduced in comments blow:

// rollup.config.js
import funcMacro from 'rollup-plugin-func-macro';

export default {
  plugins: [
    funcMacro({
      // Function name identifier
      // default: '__func__', set to null to disable
      identifier: '__func__',

      // File name identifier
      // default: '__file__', set to null to disable
      fileIdentifier: '__file__',

      // Files to transform (default)
      include: ['**/*.js', '**/*.ts'],

      // Files to exclude (default)
      exclude: ['node_modules/**'],

      // Fallback when no function found
      // default is equal to identifier
      fallback: identifier,

      // Whether to replace inside string literals
      // default: true
      stringReplace: true,
    }),
  ],
};

Why Ignore Arrow Functions ? 🤷‍♀️

Arrow functions are often anonymous or used as short callbacks. This plugin focuses on meaningful, debuggable function names that you'd actually want to see in logs! (。◕‿◕。)

Examples 💡

Function Declarations

Input:

function myAwesomeFunction() {
  console.log('Current function: __func__');
}

Output:

function myAwesomeFunction() {
  console.log('Current function:', 'myAwesomeFunction');
}

Class Methods

Input:

class Logger {
  logMessage() {
    console.log(`[__func__] Hello world!`);
  }
}

Output:

class Logger {
  logMessage() {
    console.log(`[logMessage] Hello world!`);
  }
}

Dynamic Method Names 🆕

Input:

class ApiHandler {
  ['handleUserRequest']() {
    console.log('Executing:', __func__);
    return `Processing in ${__func__}`;
  }

  ['process' + 'Data']() {
    const methodName = __func__;
    console.log(`Method: ${methodName}`);
  }
}

Output:

class ApiHandler {
  ['handleUserRequest']() {
    console.log('Executing:', 'handleUserRequest');
    return `Processing in handleUserRequest`;
  }

  ['process' + 'Data']() {
    const methodName = 'processData';
    console.log(`Method: processData`);
  }
}

Variable Embedding in Expressions 🆕

Input:

function debugFunction(param) {
  const name = __func__ + '_v2';
  const message = 'Function ' + __func__ + ' called';
  const result = { method: __func__, param };

  if (__func__ === 'debugFunction') {
    console.log(`Confirmed: ${__func__}`);
  }
}

Output:

function debugFunction(param) {
  const name = 'debugFunction' + '_v2';
  const message = 'Function debugFunction called';
  const result = { method: 'debugFunction', param };

  if ('debugFunction' === 'debugFunction') {
    console.log(`Confirmed: debugFunction`);
  }
}

Edge Cases

Edge cases are also taken good care of! like:

  • When using __func__ inside the dynamic method name: replaced by [Invalid] and a warning message is logged to the console.

  • nested functions are supported

  • complex expressions inside dynamic method names e.g. ['get' + 'Data' + getName()](){ ... } are handled too. It will replace the identifier with the string literal of the expression(Since evaluating them might be risky for side effects).

Contributing 🤝

Contributions are welcome! Please feel free to submit a Pull Request.

License 📄

MIT © Kasukabe Tsumugi


Made with ❤️

About

Using __func__ like C++, this plugin will repace it with the current function name(ignores arrow function context)

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published