iasei-cond-compile
v1.0.0
Published
Babel condition compile plugin, remove code at compile time, support TS/ES6/Vue
Maintainers
Readme
iasei-cond-compile
编译期条件编译 Babel 插件。通过 #ifdef / #endif 注释标记代码块,在构建时按配置保留或删除,支持 TypeScript、ES6+ 与 Vue SFC。
特性
- 编译期移除未命中条件的代码,不进入最终产物
- 支持
#ifdef KEY=VALUE条件语法(大小写不敏感) - 支持
.ts/.js/.tsx/.jsx及 Vue 单文件组件 - 提供 Vite 插件,在
@vitejs/plugin-vue处理 SFC 之前介入,避免条件注释被提前剥离
安装
pnpm add -D iasei-cond-compile
# 或
npm install -D iasei-cond-compile对等依赖
| 包 | 是否必需 | 说明 |
|---|---|---|
| @babel/core | 是 | Babel 核心 |
| vite | 否 | 使用 Vite 插件时需要 |
| @vue/compiler-sfc | 否 | 处理 .vue 文件时需要 |
条件语法
使用行注释标记条件块。注释需写在被控制语句的前一行(leading comment):
// #ifdef ENV=DEV
const devLog = '开发环境代码';
console.log(devLog);
// #endif
// #ifdef ENV=PROD
const prodLog = '生产环境代码';
console.log(prodLog);
// #endif
// 普通代码,始终保留
const normal = '正常代码';#ifdef KEY=VALUE:当插件选项中KEY的值等于VALUE时保留该块内代码,否则删除#endif:结束当前条件块- 选项值会转为字符串后比较(
String(condition[key]) !== val)
Babel 用法
// babel.config.js
module.exports = {
plugins: [
['iasei-cond-compile', { ENV: 'DEV' }],
],
};import { transform } from '@babel/core';
import condCompilePlugin from 'iasei-cond-compile';
const result = transform(sourceCode, {
plugins: [[condCompilePlugin, { ENV: 'DEV' }]],
});Vite 用法
将 condCompilePreVue 放在 @vitejs/plugin-vue 之前,并设置 enforce: 'pre'(插件内部已配置):
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { condCompilePreVue } from 'iasei-cond-compile/vite';
export default defineConfig({
plugins: [
condCompilePreVue({ ENV: 'DEV' }),
vue(),
],
});Vite 插件会处理:
.vue:替换<script>/<script setup>中的条件代码(template不受影响).ts/.js/.tsx/.jsx:直接对源码做条件编译
自动跳过 node_modules 与 .d.ts 文件。
Vue SFC 示例
<script setup lang="ts">
// #ifdef ENV=DEV
const devLog = '开发环境';
console.log(devLog);
// #endif
// #ifdef ENV=PROD
const prodLog = '生产环境';
console.log(prodLog);
// #endif
const normal = '普通代码';
</script>
<template>
<div>{{ normal }}</div>
</template>构建时传入 { ENV: 'DEV' } 会保留开发分支、移除生产分支;template 区块保持不变。
配置选项
type CondCompileOptions = Record<string, string | number | boolean>;示例:
{ ENV: 'DEV' }
{ PLATFORM: 'WEB', DEBUG: true }使用.env变量
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
return {
plugins: [
condCompilePreVue({ ENV_DEV: env.ENV_DEV }),
vue(),
],
};
});注意事项
- 条件注释必须作为下一行语句的前导注释,插件在
Program与BlockStatement层级处理 - 同一文件中可存在多个独立的
#ifdef…#endif块 - 未匹配条件的代码块会在编译阶段被完全移除,不会出现在输出中
- Vue 外部 script(
src属性引用)不会被内联处理
开发
pnpm install
pnpm run build # 构建 dist
pnpm run dev # 监听构建
pnpm test # 运行测试License
MIT
