Babel 中文文档 Babel 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • 指南
    • Babel 是什么?
    • 使用指南
    • 配置 Babel
    • 学习 ES2015
    • 升级到 Babel 7
  • 配置

  • 预设环境

  • 杂项

  • 集成

  • 工具

  • 辅助

undefined

  Compile time code replacement for babel similar to Webpack's DefinePlugin

Quick Start


  1. ``` shell
  2. $ npm install --save-dev babel-plugin-transform-define
  3. ```

.babelrc

  1. ``` json
  2. {
  3.   "plugins": [
  4.     ["transform-define", {
  5.       "process.env.NODE_ENV": "production",
  6.       "typeof window": "object"
  7.     }]
  8.   ]
  9. }
  10. ```

.babelrc.js

  1. ``` js
  2. // E.g., any dynamic logic with JS, environment variables, etc.
  3. const overrides = require("./another-path.js");

  4. module.exports = {
  5.   plugins: [
  6.     ["transform-define", {
  7.       "process.env.NODE_ENV": "production",
  8.       "typeof window": "object",
  9.       ...overrides
  10.     }]
  11.   ]
  12. };
  13. ```

Reference Documentation


babel-plugin-transform-define can transform certain types of code as a babel transformation.

Identifiers

.babelrc

  1. ``` json
  2. {
  3.   "plugins": [
  4.     ["transform-define", {
  5.       "VERSION": "1.0.0",
  6.     }]
  7.   ]
  8. }
  9. ```

Source Code

  1. ``` js
  2. VERSION;

  3. window.__MY_COMPANY__ = {
  4.   version: VERSION
  5. };
  6. ```

Output Code

  1. ``` js
  2. "1.0.0";

  3. window.__MY_COMPANY__ = {
  4.   version: "1.0.0"
  5. };
  6. ```

Member Expressions

.babelrc

  1. ``` json
  2. {
  3.   "plugins": [
  4.     ["transform-define", {
  5.       "process.env.NODE_ENV": "production"
  6.     }]
  7.   ]
  8. }
  9. ```

Source Code

  1. ``` js
  2. if (process.env.NODE_ENV === "production") {
  3.   console.log(true);
  4. }
  5. ```

Output Code

  1. ``` js
  2. if (true) {
  3.   console.log(true);
  4. }
  5. ```

Unary Expressions

.babelrc

  1. ``` json
  2. {
  3.   "plugins": [
  4.     ["transform-define", {
  5.       "typeof window": "object"
  6.     }]
  7.   ]
  8. }
  9. ```

Source Code

  1. ``` js
  2. typeof window;
  3. typeof window === "object";
  4. ```

Output Code

  1. ``` js
  2. 'object';
  3. true;
  4. ```

License


MIT License

Maintenance Status


Stable:Formidable is not planning to develop any new features for this project. We are still responding to bug reports and security concerns. We are still welcoming PRs for this project, but PRs that include new features should be small and easy to integrate and should not include breaking changes.
Last Updated: 2023-09-03 17:10:52