🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

babel-plugin-define-variables

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

babel-plugin-define-variables - npm Package Compare versions

Comparing version
0.0.3
to
0.0.4
+56
types/index.d.ts
/**
* babel-plugin-define-variables 插件的类型定义
*/
/** 当前代码文件相对于项目根目录的文件路径 */
declare const __filename__: string;
/** 当前代码文件的哈希值 */
declare const __filehash__: string;
/** 当前代码文件相对于项目根目录的目录路径 */
declare const __dirname__: string;
/** 构建时刻的时间,格式为 'yyyy-MM-dd hh:mm:ss' */
declare const __now__: string;
/** 构建时刻的时间戳(毫秒) */
declare const __timestamp__: number;
/** 当前项目的包名 */
declare const __packagename__: string;
/**
* 当前项目的包版本号,或者指定包的版本号
* @param packageName 可选的包名,如果不提供则返回当前项目版本
* @returns 版本号字符串
*/
declare const __packageversion__: {
(): string;
(packageName: string): string;
};
/**
* 插件配置选项接口
*/
export interface PluginOptions {
/** 自定义定义的全局变量 */
defines?: Record<string, any>;
/** 内置变量的启用/禁用配置 */
builtIns?: {
/** 是否启用 __filename__ 变量 */
filename?: boolean;
/** 是否启用 __filehash__ 变量 */
filehash?: boolean;
/** 是否启用 __dirname__ 变量 */
dirname?: boolean;
/** 是否启用 __now__ 变量 */
now?: boolean;
/** 是否启用 __timestamp__ 变量 */
timestamp?: boolean;
/** 是否启用 __packagename__ 变量 */
packagename?: boolean;
/** 是否启用 __packageversion__ 变量 */
packageversion?: boolean;
};
}
+3
-2

@@ -10,3 +10,4 @@ "use strict";

getPackage = _require.getPackage,
mergeObject = _require.mergeObject;
mergeObject = _require.mergeObject,
hasOwnProp = _require.hasOwnProp;

@@ -74,3 +75,3 @@ function createHash(filename, pkg) {

path.replaceWith(t.stringLiteral(createHash(cache.filename, cache.pkg)));
} else if (defines[identifier] !== undefined) {
} else if (hasOwnProp(defines, identifier)) {
path.replaceWith(var2Expression(defines[identifier]));

@@ -77,0 +78,0 @@ } else if (cache.pkg) {

+13
-1

@@ -327,2 +327,13 @@ "use strict";

var _hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @param {object} obj
* @param {string} key
* @returns {boolean}
*/
function hasOwnProp(obj, key) {
return Boolean(obj) && _hasOwnProperty.call(obj, key);
}
module.exports = {

@@ -336,3 +347,4 @@ getConstCache: getConstCache,

getPackage: getPackage,
mergeObject: mergeObject
mergeObject: mergeObject,
hasOwnProp: hasOwnProp
};
{
"name": "babel-plugin-define-variables",
"version": "0.0.3",
"description": "a babel define vars that like webpack.DefinePlugin",
"version": "0.0.4",
"description": "一个类似 webpack.DefinePlugin 的 Babel 插件,用于在编译时定义全局变量和常量",
"keywords": [
"babel",
"plugin",
"define"
"define",
"variables",
"constants",
"environment",
"build-time",
"webpack-define",
"chinese",
"中文"
],

@@ -13,2 +20,3 @@ "sideEffects": false,

"module": "esm/index.js",
"typings": "types/index.d.ts",
"engines": {

@@ -19,3 +27,4 @@ "node": "> 6.9.1"

"src",
"esm"
"esm",
"types"
],

@@ -22,0 +31,0 @@ "scripts": {

+232
-39
# babel-plugin-define-variables
a babel plugin that like webpack.DefinePlugin
## installtion
A Babel plugin that works like webpack.DefinePlugin for defining global variables and constants at compile time.
[![NPM version](https://img.shields.io/npm/v/babel-plugin-define-variables.svg?style=flat)](https://npmjs.com/package/babel-plugin-define-variables)
[![NPM downloads](https://img.shields.io/npm/dm/babel-plugin-define-variables.svg?style=flat)](https://npmjs.com/package/babel-plugin-define-variables)
## 🌍 Language
- [English](README.md) (Current)
- [中文](README_CN.md)
## 📖 Introduction
`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:
- Injecting environment variables at build time
- Defining build-time constant values
- Getting file information (filename, path, hash, etc.)
- Getting package information and version numbers
- Injecting timestamps and build times
## 🚀 Installation
```bash
npm install --save-dev babel-plugin-define-variables
// or
yarn add -D babel-plugin-define-variables
npm install --save-dev babel-plugin-define-variables
# or
yarn add -D babel-plugin-define-variables
```
## config
## ⚙️ Configuration
### Basic Configuration
#### Minimal Configuration (All Built-ins Enabled)
```js

@@ -19,3 +40,3 @@ // babel.config.js

presets: [
...
'@babel/preset-env'
],

@@ -29,15 +50,40 @@ plugins: [

'process.env.NODE_ENV': process.env.NODE_ENV,
'VERSION': '1.0.0',
'IS_PRODUCTION': process.env.NODE_ENV === 'production'
}
// builtIns not specified - all variables enabled by default
}
]
]
};
```
#### Explicit Configuration (Same as Minimal)
```js
// babel.config.js
module.exports = {
presets: [
'@babel/preset-env'
],
plugins: [
[
'babel-plugin-define-variables',
{
defines: {
'process.env.BUILD_ENV': process.env.BUILD_ENV,
'process.env.NODE_ENV': process.env.NODE_ENV,
'VERSION': '1.0.0',
'IS_PRODUCTION': process.env.NODE_ENV === 'production'
},
builtIns: {
// filename: false,
// filehash: false,
// dirname: false,
// now: false,
// timestamp: false,
// packagename: false,
// packageversion: false
filename: true, // Enable __filename__ (default)
filehash: true, // Enable __filehash__ (default)
dirname: true, // Enable __dirname__ (default)
now: true, // Enable __now__ (default)
timestamp: true, // Enable __timestamp__ (default)
packagename: true, // Enable __packagename__ (default)
packageversion: true // Enable __packageversion__ (default)
}
}
],
...
]
]

@@ -47,42 +93,166 @@ };

## built-in define
### Configuration Options
- __filename__
#### `defines` Object
Used to define custom global variables, supports the following value types:
- String
- Number
- Boolean
- Object (will be serialized to JSON string)
the filename of code file that relative of `package.json` path that current project.
#### `builtIns` Object
Controls 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`.
- __filehash__
the filename of code file
**Important Notes:**
- You don't need to specify `builtIns` if you want all variables enabled (default behavior)
- Only specify the variables you want to disable by setting them to `false`
- Unspecified variables will remain enabled
- __dirname__
| Option | Default | Description |
|--------|---------|-------------|
| `filename` | `true` | Whether to enable `__filename__` variable |
| `filehash` | `true` | Whether to enable `__filehash__` variable |
| `dirname` | `true` | Whether to enable `__dirname__` variable |
| `now` | `true` | Whether to enable `__now__` variable |
| `timestamp` | `true` | Whether to enable `__timestamp__` variable |
| `packagename` | `true` | Whether to enable `__packagename__` variable |
| `packageversion` | `true` | Whether to enable `__packageversion__` variable |
the dirname of code file that relative of `package.json` path that current project.
**Example of disabling specific built-ins:**
```js
{
builtIns: {
filename: false, // Disable __filename__
filehash: false, // Disable __filehash__
now: false // Disable __now__
// Other variables remain enabled by default
}
}
```
- __now__
## 🔧 Built-in Variables
the time that build moment. format: 'yyyy-MM-dd hh:mm:ss'
### File Information Variables
- __timestamp__
#### `__filename__`
The file path of the current code file relative to the project root directory (where `package.json` is located).
the timestamp that build moment.
**Example:**
```js
console.log(__filename__); // Output: "/src/components/Button.js"
```
- __packagename__
#### `__dirname__`
The directory path of the current code file relative to the project root directory.
the package name of this project.
**Example:**
```js
console.log(__dirname__); // Output: "/src/components"
```
- __packageversion__
#### `__filehash__`
The hash value of the current code file, generated based on the filename.
the package version of this project. you can also use like this:
**Example:**
```js
console.log(__filehash__); // Output: "d7bfcc4a"
```
```js
__packageversion__('react');
```
that you will get version of react;
### Time-related Variables
## demo
#### `__now__`
The time at build moment, formatted as `'yyyy-MM-dd hh:mm:ss'`.
src/index.js:
**Example:**
```js
console.log(__now__); // Output: "2024-01-15 14:30:25"
```
#### `__timestamp__`
The timestamp at build moment (milliseconds).
**Example:**
```js
console.log(__timestamp__); // Output: 1705312225000
```
### Package Information Variables
#### `__packagename__`
The package name of the current project.
**Example:**
```js
console.log(__packagename__); // Output: "babel-plugin-define-variables"
```
#### `__packageversion__`
The package version of the current project, or the version of a specified package.
**Usage:**
```js
// Get current project version
console.log(__packageversion__); // Output: "0.0.4"
// Get version of specified package
console.log(__packageversion__('react')); // Output: "18.2.0"
console.log(__packageversion__('@babel/core')); // Output: "7.5.4"
```
## 💡 Use Cases
### 1. Environment Variable Injection
```js
// Configuration
{
defines: {
'process.env.API_URL': process.env.API_URL || 'http://localhost:3000',
'process.env.DEBUG': process.env.DEBUG || false
}
}
// Usage
if (process.env.DEBUG) {
console.log('API URL:', process.env.API_URL);
}
```
### 2. Build Information Injection
```js
// Configuration
{
defines: {
'BUILD_TIME': new Date().toISOString(),
'GIT_COMMIT': process.env.GIT_COMMIT || 'unknown'
}
}
// Usage
console.log('Build time:', BUILD_TIME);
console.log('Git commit:', GIT_COMMIT);
```
### 3. File Path Processing
```js
// Using built-in variables
const configPath = __dirname__ + '/config.json';
const fileHash = __filehash__;
```
### 4. Version Information Management
```js
// Check version
if (__packageversion__('react').startsWith('18.')) {
console.log('Using React 18');
}
// Display build information
console.log(`Building ${__packagename__} v${__packageversion__} at ${__now__}`);
```
## 📝 Complete Example
### Source Code (src/index.js)
```js
function test() {

@@ -101,5 +271,7 @@ console.log('__filename__', __filename__);

}
export default test;
```
output/index.js:
### Compiled Output

@@ -121,1 +293,22 @@ ```js

```
## 🔍 Notes
1. **Performance**: Built-in variables are calculated at compile time and won't affect runtime performance
2. **File Paths**: File path variables are calculated based on the project root directory (where `package.json` is located)
3. **Version Retrieval**: `__packageversion__('packageName')` will try to resolve the version of the specified package, returning an empty string if the package doesn't exist
4. **Time Variables**: `__now__` and `__timestamp__` are generated at each build, not calculated at runtime
## 🤝 Contributing
Issues and Pull Requests are welcome!
## 📄 License
MIT License
## 🔗 Related Links
- [Babel](https://babeljs.io/)
- [webpack DefinePlugin](https://webpack.js.org/plugins/define-plugin/)
- [hash-sum](https://github.com/bevacqua/hash-sum)

@@ -8,3 +8,4 @@

getPackage,
mergeObject
mergeObject,
hasOwnProp
} = require('./utils');

@@ -46,4 +47,4 @@

} else if (parent.type === 'CallExpression' && expr2str(parent.callee) === identifier) {
if (identifier !== '__packageversion__'
|| !parent.arguments.length
if (identifier !== '__packageversion__'
|| !parent.arguments.length
|| !t.isStringLiteral(parent.arguments[0])) return;

@@ -69,3 +70,3 @@ path = path.parentPath;

path.replaceWith(t.stringLiteral(createHash(cache.filename, cache.pkg)));
} else if (defines[identifier] !== undefined) {
} else if (hasOwnProp(defines, identifier)) {
path.replaceWith(var2Expression(defines[identifier]));

@@ -105,2 +106,2 @@ } else if (cache.pkg) {

};
};
};

@@ -247,2 +247,13 @@ const t = require('@babel/types');

const _hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @param {object} obj
* @param {string} key
* @returns {boolean}
*/
function hasOwnProp(obj, key) {
return Boolean(obj) && _hasOwnProperty.call(obj, key);
}
module.exports = {

@@ -256,3 +267,4 @@ getConstCache,

getPackage,
mergeObject
};
mergeObject,
hasOwnProp
};