{"id":20623479,"url":"https://github.com/gxlmyacc/babel-plugin-define-variables","last_synced_at":"2026-05-01T22:35:06.964Z","repository":{"id":98837539,"uuid":"317482929","full_name":"gxlmyacc/babel-plugin-define-variables","owner":"gxlmyacc","description":"a babel define vars that like webpack.DefinePlugin","archived":false,"fork":false,"pushed_at":"2022-10-10T09:06:29.000Z","size":74,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-01T00:45:34.938Z","etag":null,"topics":["babel","babel-plugin","defineplugin","webpack"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gxlmyacc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-12-01T09:01:37.000Z","updated_at":"2022-10-09T08:25:29.000Z","dependencies_parsed_at":"2023-03-13T15:54:03.869Z","dependency_job_id":null,"html_url":"https://github.com/gxlmyacc/babel-plugin-define-variables","commit_stats":{"total_commits":8,"total_committers":1,"mean_commits":8.0,"dds":0.0,"last_synced_commit":"87aa06ebd12cd15255612226d1d8a7df5ed288b0"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fbabel-plugin-define-variables","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fbabel-plugin-define-variables/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fbabel-plugin-define-variables/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gxlmyacc%2Fbabel-plugin-define-variables/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gxlmyacc","download_url":"https://codeload.github.com/gxlmyacc/babel-plugin-define-variables/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242332579,"owners_count":20110345,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["babel","babel-plugin","defineplugin","webpack"],"created_at":"2024-11-16T12:27:19.436Z","updated_at":"2026-05-01T22:35:06.956Z","avatar_url":"https://github.com/gxlmyacc.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# babel-plugin-define-variables\n\nA Babel plugin that works like webpack.DefinePlugin for defining global variables and constants at compile time.\n\n[![NPM version](https://img.shields.io/npm/v/babel-plugin-define-variables.svg?style=flat)](https://npmjs.com/package/babel-plugin-define-variables)\n[![NPM downloads](https://img.shields.io/npm/dm/babel-plugin-define-variables.svg?style=flat)](https://npmjs.com/package/babel-plugin-define-variables)\n\n## 🌍 Language\n\n- [English](README.md) (Current)\n- [中文](README_CN.md)\n\n## 📖 Introduction\n\n`babel-plugin-define-variables` is a powerful Babel plugin that allows you to define global variables and constants at compile time, similar to webpack's DefinePlugin. This plugin is particularly useful for:\n\n- Injecting environment variables at build time\n- Defining build-time constant values\n- Getting file information (filename, path, hash, etc.)\n- Getting package information and version numbers\n- Injecting timestamps and build times\n\n## 🚀 Installation\n\n```bash\nnpm install --save-dev babel-plugin-define-variables\n# or\nyarn add -D babel-plugin-define-variables\n```\n\n## ⚙️ Configuration\n\n### Basic Configuration\n\n#### Minimal Configuration (All Built-ins Enabled)\n```js\n// babel.config.js\nmodule.exports = {\n  presets: [\n    '@babel/preset-env'\n  ],\n  plugins: [\n    [\n      'babel-plugin-define-variables',\n      {\n        defines: {\n          'process.env.BUILD_ENV': process.env.BUILD_ENV,\n          'process.env.NODE_ENV': process.env.NODE_ENV,\n          'VERSION': '1.0.0',\n          'IS_PRODUCTION': process.env.NODE_ENV === 'production'\n        }\n        // builtIns not specified - all variables enabled by default\n      }\n    ]\n  ]\n};\n```\n\n#### Explicit Configuration (Same as Minimal)\n```js\n// babel.config.js\nmodule.exports = {\n  presets: [\n    '@babel/preset-env'\n  ],\n  plugins: [\n    [\n      'babel-plugin-define-variables',\n      {\n        defines: {\n          'process.env.BUILD_ENV': process.env.BUILD_ENV,\n          'process.env.NODE_ENV': process.env.NODE_ENV,\n          'VERSION': '1.0.0',\n          'IS_PRODUCTION': process.env.NODE_ENV === 'production'\n        },\n        builtIns: {\n          filename: true,      // Enable __filename__ (default)\n          filehash: true,      // Enable __filehash__ (default)\n          dirname: true,       // Enable __dirname__ (default)\n          now: true,           // Enable __now__ (default)\n          timestamp: true,     // Enable __timestamp__ (default)\n          packagename: true,   // Enable __packagename__ (default)\n          packageversion: true // Enable __packageversion__ (default)\n        }\n      }\n    ]\n  ]\n};\n```\n\n### Configuration Options\n\n#### `defines` Object\nUsed to define custom global variables, supports the following value types:\n- String\n- Number\n- Boolean\n- Object (will be serialized to JSON string)\n\n#### `builtIns` Object\nControls the enable/disable state of built-in variables. **All built-in variables are enabled by default**. If you want to disable any of them, you need to explicitly set them to `false`.\n\n**Important Notes:**\n- You don't need to specify `builtIns` if you want all variables enabled (default behavior)\n- Only specify the variables you want to disable by setting them to `false`\n- Unspecified variables will remain enabled\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `filename` | `true` | Whether to enable `__filename__` variable |\n| `filehash` | `true` | Whether to enable `__filehash__` variable |\n| `dirname` | `true` | Whether to enable `__dirname__` variable |\n| `now` | `true` | Whether to enable `__now__` variable |\n| `timestamp` | `true` | Whether to enable `__timestamp__` variable |\n| `packagename` | `true` | Whether to enable `__packagename__` variable |\n| `packageversion` | `true` | Whether to enable `__packageversion__` variable |\n\n**Example of disabling specific built-ins:**\n```js\n{\n  builtIns: {\n    filename: false,    // Disable __filename__\n    filehash: false,   // Disable __filehash__\n    now: false         // Disable __now__\n    // Other variables remain enabled by default\n  }\n}\n```\n\n## 🔧 Built-in Variables\n\n### File Information Variables\n\n#### `__filename__`\nThe file path of the current code file relative to the project root directory (where `package.json` is located).\n\n**Example:**\n```js\nconsole.log(__filename__); // Output: \"/src/components/Button.js\"\n```\n\n#### `__dirname__`\nThe directory path of the current code file relative to the project root directory.\n\n**Example:**\n```js\nconsole.log(__dirname__); // Output: \"/src/components\"\n```\n\n#### `__filehash__`\nThe hash value of the current code file, generated based on the filename.\n\n**Example:**\n```js\nconsole.log(__filehash__); // Output: \"d7bfcc4a\"\n```\n\n### Time-related Variables\n\n#### `__now__`\nThe time at build moment, formatted as `'yyyy-MM-dd hh:mm:ss'`.\n\n**Example:**\n```js\nconsole.log(__now__); // Output: \"2024-01-15 14:30:25\"\n```\n\n#### `__timestamp__`\nThe timestamp at build moment (milliseconds).\n\n**Example:**\n```js\nconsole.log(__timestamp__); // Output: 1705312225000\n```\n\n### Package Information Variables\n\n#### `__packagename__`\nThe package name of the current project.\n\n**Example:**\n```js\nconsole.log(__packagename__); // Output: \"babel-plugin-define-variables\"\n```\n\n#### `__packageversion__`\nThe package version of the current project, or the version of a specified package.\n\n**Usage:**\n```js\n// Get current project version\nconsole.log(__packageversion__); // Output: \"0.0.4\"\n\n// Get version of specified package\nconsole.log(__packageversion__('react')); // Output: \"18.2.0\"\nconsole.log(__packageversion__('@babel/core')); // Output: \"7.5.4\"\n```\n\n## 💡 Use Cases\n\n### 1. Environment Variable Injection\n```js\n// Configuration\n{\n  defines: {\n    'process.env.API_URL': process.env.API_URL || 'http://localhost:3000',\n    'process.env.DEBUG': process.env.DEBUG || false\n  }\n}\n\n// Usage\nif (process.env.DEBUG) {\n  console.log('API URL:', process.env.API_URL);\n}\n```\n\n### 2. Build Information Injection\n```js\n// Configuration\n{\n  defines: {\n    'BUILD_TIME': new Date().toISOString(),\n    'GIT_COMMIT': process.env.GIT_COMMIT || 'unknown'\n  }\n}\n\n// Usage\nconsole.log('Build time:', BUILD_TIME);\nconsole.log('Git commit:', GIT_COMMIT);\n```\n\n### 3. File Path Processing\n```js\n// Using built-in variables\nconst configPath = __dirname__ + '/config.json';\nconst fileHash = __filehash__;\n```\n\n### 4. Version Information Management\n```js\n// Check version\nif (__packageversion__('react').startsWith('18.')) {\n  console.log('Using React 18');\n}\n\n// Display build information\nconsole.log(`Building ${__packagename__} v${__packageversion__} at ${__now__}`);\n```\n\n## 📝 Complete Example\n\n### Source Code (src/index.js)\n\n```js\nfunction test() {\n  console.log('__filename__', __filename__);\n  console.log('__filehash__', __filehash__);\n  console.log('__dirname__', __dirname__);\n  console.log('__now__', __now__);\n  console.log('__timestamp__', __timestamp__);\n  console.log('__packagename__', __packagename__);\n  console.log('__packageversion__', __packageversion__);\n  console.log('__packageversion__', __packageversion__(''));\n  console.log('__packageversion__', __packageversion__('@babel/cli'));\n  console.log('process.env.BUILD_ENV', process.env.BUILD_ENV);\n  __packageversion__.split('.');\n}\n\nexport default test;\n```\n\n### Compiled Output\n\n```js\nfunction test() {\n  console.log('__filename__', \"/demo/src/test1.js\");\n  console.log('__filehash__', \"d7bfcc4a\");\n  console.log('__dirname__', \"/demo/src\");\n  console.log('__now__', \"2020-12-03 18:43:46\");\n  console.log('__timestamp__', 1606992227198);\n  console.log('__packagename__', \"babel-plugin-define-variables\");\n  console.log('__packageversion__', \"0.0.2\");\n  console.log('__packageversion__', \"\");\n  console.log('__packageversion__', \"7.6.4\");\n  console.log('process.env.BUILD_ENV', \"test\");\n  \"0.0.2\".split('.');\n}\n```\n\n## 🔍 Notes\n\n1. **Performance**: Built-in variables are calculated at compile time and won't affect runtime performance\n2. **File Paths**: File path variables are calculated based on the project root directory (where `package.json` is located)\n3. **Version Retrieval**: `__packageversion__('packageName')` will try to resolve the version of the specified package, returning an empty string if the package doesn't exist\n4. **Time Variables**: `__now__` and `__timestamp__` are generated at each build, not calculated at runtime\n\n## 🤝 Contributing\n\nIssues and Pull Requests are welcome!\n\n## 📄 License\n\nMIT License\n\n## 🔗 Related Links\n\n- [Babel](https://babeljs.io/)\n- [webpack DefinePlugin](https://webpack.js.org/plugins/define-plugin/)\n- [hash-sum](https://github.com/bevacqua/hash-sum)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgxlmyacc%2Fbabel-plugin-define-variables","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgxlmyacc%2Fbabel-plugin-define-variables","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgxlmyacc%2Fbabel-plugin-define-variables/lists"}