conditional-compile-loader

A conditional compile loader for webpack. 条件编译 webpack loader。


Keywords
webpack, vue, js, less, jsx, conditional compile
License
MIT
Install
npm install conditional-compile-loader@1.0.8

Documentation

conditional-compile-loader

conditional-compile-loader 根据设定的参数对 vue、js、jsx 和 css(less, sass 等) 代码进行条件编译。

Getting Started

先安装 conditional-compile-loader

npm install -D conditional-compile-loader
# or
yarn add -D conditional-compile-loader

然后添加这个 loader 到 webpack 配置,例如:

example.vue

<template>
  <div>
    <!-- #ifdef FLAG -->
    <header>FLAG</header>
    <!-- #endif -->
    <!-- #ifdef FLAG-A || FLAG-B -->
    <header>FLAG-A OR FLAG-B</header>
    <!-- #endif -->
  </div>
</template>

example.js

// #ifdef FLAG
console.log('FLAG')
// #endif
// #ifdef FLAG-A || FLAG-B
console.log('FLAG-A OR FLAG-B')
// #endif

example.jsx

{/* #ifdef FLAG */}
<header>FLAG</header>
{/* #endif */}

{/* #ifdef FLAG-A || FLAG-B */}
<header>FLAG-A OR FLAG-B</header>
{/* #endif */}

example.less

body {
  /* #ifdef FLAG */
  background: cornflowerblue;
  /* #endif */
  /* #ifdef FLAG-A || FLAG-B */
  background: pink;
  /* #endif */
}

webpack.config.js

rules: [
  {
    test: /\.vue$/,
    use: [
      {
        loader: 'vue-loader',
      },
      {
        loader: 'conditional-compile-loader',
        options: {
          FLAG: true,
          'FLAG-A': true
        }
      }
    ]
  },
  {
    test: /\.jsx?$/,
    use: [
      {
        loader: 'babel-loader',
      },
      {
        loader: 'conditional-compile-loader',
        options: {
          FLAG: true,
          'FLAG-B': true
        }
      }
    ]
  },
  {
    test: /\.less$/,
    use: [
      {
        loader: 'less-loader',
      },
      {
        loader: 'conditional-compile-loader',
        options: {
          FLAG: true,
          'FLAG-A': true
        }
      }
    ]
  }
]

Options

Name Type Default 参数描述
reg {Regex} 自定义正则表达式
符合 /[A-Z-]+/ 的变量名 {Boolean} true 环境变量,为 true 的时候保留代码

错误使用情况

变量名必须严格符合正则 /[A-Z-]+/,否则不会进行条件编译,例如:

<template>
  <div>
    <!-- #ifdef flag -->
    <header>FLAG</header>
    <!-- #endif -->
    <!-- #ifdef FLAG-a || flag-B -->
    <header>FLAG-A OR FLAG-B</header>
    <!-- #endif -->
  </div>
</template>