Coder Social home page Coder Social logo

hzsrc / js-conditional-compile-loader Goto Github PK

View Code? Open in Web Editor NEW
56.0 1.0 6.0 1.37 MB

A javascript conditional compile loader for webpack. 一个javascript条件编译的webpack loader。

License: MIT License

JavaScript 87.33% Vue 12.67%
javascript webpack webpack-loader conditional compile compilation js

js-conditional-compile-loader's Introduction

js-conditional-compile-loader

A conditional compiling loader for webpack, support any source files like js, ts, vue, css, scss, html.
Conditional compiling means that we can use the same codes and compiling process, to build different applications with different environment conditions.

  • For example: we can output two different program for debug or release environment with a same source code project.
  • Another sample: Use same codes and compiling process to supply different customers, just by using different building command args, like this: npm run build --ali for alibaba, npm run build --tencent for tencent。 image

Usage

This loader provides two directives: IFDEBUG and IFTRUE. Just use them anywhere in js code like this: Start with /*IFDEBUG or /*IFTRUE_xxx, end with FIDEBUG*/ or FITRUE_xxx*/, place js code in the center. The xxx is any condition property of the options in webpack, such like myFlag.

  • Mode 1 - comment all
    Since it is designed by a js comment style, the code can run normaly even though the js-conditional-compile-loader is not used.
/* IFDEBUG Any js here FIDEBUG */
/* IFTRUE_yourFlagName ...js code... FITRUE_yourFlagName */
  • Mode 2 -- head and foot
    In this mode, you can use eslint to check your code.
/* IFDEBUG */
var anyJsHere = 'Any js here'
/*FIDEBUG */
/* IFTRUE_yourFlagName*/ 
function anyJsHere(){
}
/*FITRUE_yourFlagName */

Build result with source code

Source code:

/* IFTRUE_forAlibaba */
var aliCode = require('./ali/alibaba-business.js')
aliCode.doSomething()
/* FITRUE_forAlibaba */
$state.go('win', {dir: menu.winId /*IFDEBUG , reload: true FIDEBUG*/})

Compiled output by options: {isDebug: true, forAlibaba: true}:

var aliCode = require('./ali/alibaba-business.js')
aliCode.doSomething()
$state.go('win', {dir: menu.winId, reload: true })

Compiled output by options: {isDebug: false, forAlibaba: false}:

$state.go('win', {dir: menu.winId})

Setup

    npm i -D js-conditional-compile-loader

Config in webpack

Change webpack config like this:
See this sample: vue-element-ui-scaffold-webpack4(https://github.com/hzsrc/vue-element-ui-scaffold-webpack4)
js-conditional-compile-loader needs to be added as step 1 for a rule, means it is set as the last item of the use array.
This sample is a config for vue and js files, ts file is alike. For config of css、scss, See this sample

const conditionalCompiler = {
    loader: 'js-conditional-compile-loader',
    options: {
        isDebug: process.env.NODE_ENV === 'development', // optional, this expression is default
        envTest: process.env.ENV_CONFIG === 'test', // any prop name you want, used for /* IFTRUE_evnTest ...js code... FITRUE_evnTest */
        myFlag: process.env.npm_config_myflag, // enabled by `npm run build --myflag`
    }
}

module.exports = {
    // others...
    module: {
        rules: [
            {
                test: /\.vue$/,
                use: ['vue-loader', conditionalCompiler],
            },
            {
                test: /\.js$/,
                include: [resolve('src'), resolve('test')],
                use: [
                    //step-2
                    'babel-loader?cacheDirectory',
                    //step-1
                    conditionalCompiler,
                ],
            },
            // others...
        ]
    }
}

options

  • isDebug: boolean

If isDebug === false, all the codes between /\*IFDEBUG and FIDEBUG\*/ will be removed, otherwise the codes will be remained.
Defualt value of isDebug is set by: process.env.NODE_ENV === 'development'

  • changeSource: Function(source, options)

Custom function to change source code. Optional. Sample: change .aspx to .do for java backend:

var options = {
    changeSource: process.env.npm_config_java ? source => source.replace(/\.aspx\b/i, '.do') : null
}
  • [any propertyName]:{bool} if [propertyValue] === false, all codes between /\* IFTRUE_propertyName and FITRUE_propertyName \*/ will be removed, otherwise the codes will be remained.

Samples -- Any file, Anywhere!

Conditional compiling directives can be used anywhere in any source files.
Like these:

  • 1:
const tx = "This is app /* IFTRUE_Ali of debug FITRUE_Ali */ here";


/*IFDEBUG
let tsFunc = function(arr: number[]) : string {
    alert('Hi~');
    return arr.length.toString()
}
FIDEBUG*/
  • 2:
/* IFTRUE_myFlag */
div > ul > li {
    a {
        color: red;
    }
}
/*FITRUE_myFlag */


h2{
    background: red;
    /* IFTRUE_myFlag 
    color: blue;
    FITRUE_myFlag */
}
  • 3
Vue.component('debugInfo', {
    template: ''
    /* IFDEBUG
        + '<pre style="font-size:13px;font-family:\'Courier\',\'Courier New\';z-index:9999;line-height: 1.1;position: fixed;top:0;right:0; pointer-events: none">{{JSON.stringify($attrs.info || "", null, 4).replace(/"(\\w+)":/g, "$1:")}}</pre>'
    FIDEBUG */
    ,
    watch: {
      /* IFTRUE_myFlag */
      curRule (v){
          this.ruleData = v
      },
      /*FITRUE_myFlag */
    },
});
  • 4
<temeplate>
    <div>
        /* IFTRUE_myFlag
        <h2>This is a test! For HTML. vue模板内也可以使用!</h2>
        <pre>
            {{$attrs.info || ''}}
        </pre>
        FITRUE_myFlag */
    </div>
</temeplate>

<script>
    var vueComponent = {
        data: {
            /* IFTRUE_myFlag
            falgData: 'Flag Data',
            FITRUE_myFlag */
        },
    };
</script>

/* IFTRUE_myFlag*/
<style scoped>
    .any-where-test {
        color: red;
    }
</style>
/* FITRUE_myFlag*/


<style id="a" scoped>
    /* IFTRUE_myFlag*/
    .test-for-css {
        color: red;
    }
    /*FITRUE_myFlag */
</style>

js-conditional-compile-loader's People

Contributors

dependabot[bot] avatar hzsrc avatar wenlz123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

js-conditional-compile-loader's Issues

配置项目遇到很多错误,请帮忙看看

    module: {
      rules: [
        { test: /\.m4a$/, use: 'raw-loader' },
        {
          test: /\.vue$/,
          use: ['vue-loader', conditionalCompiler],
        },
        {
          test: /\.js$/,
          include: [resolve('src'), resolve('test')],
          use: [
            //step-2
            'babel-loader?cacheDirectory',
            //step-1
            conditionalCompiler,
          ],
        },
      ],
    },
  },

image

希望可以支持嵌套

/* IFDEBUG */

/* IFTRUE_envTest */
import xx from 'test.debug.js'
/* FITRUE_envTest */

/* IFTRUE_envBeta */
import xx from 'beta.debug.js'
/* FITRUE_envBeta */

/* FIDEBUG */

options object is not refreshed upon multiple calls

Hi, I'm trying to get compiled different versions depending on some runtime values and I found this plugin very usefull, but I think I have found a bug.
When using this plugin on several webpack config objects, the output bundles always match the first of the passed objects.

For example this config object was always creating bundles matching the first of the objects in the array (page1):

module.exports = [
  {
    entry: {
      page1: "./src/index.js",
    },
    ...
    module: {
      rules: [       
        {
          loader: "js-conditional-compile-loader",
          options: {
            gallery: false,
            hero: true,
            slider: false,
          },
        },
      ],
    },
  },
  {
    entry: {
      page2: "./src/index.js",
    },
    ...
    module: {
      rules: [
        {
          loader: "js-conditional-compile-loader",
          options: {
            gallery: false,
            hero: true,
            slider: true,
          },
        },
      ],
    },
  },
  {
    entry: {
      page3: "./src/index.js",
    },
    ...
    module: {
      rules: [
        {
          loader: "js-conditional-compile-loader",
          options: {
            gallery: true,
            hero: false,
            slider: false,
          },
        },
      ],
    },
  },
];

After debugging a little the code of the loader, I found that in the index.js file, the options variable is defined outside of the exported function, it's always taking the value of the first call done to it, and not taking the passed config on succesive executions. This gets solved by removing the if on line #7.

Hope you find this useful.

Cheers!

对SourceMap的影响

先谢谢作者提供的插件,解决了我的一些实际问题。

今天在调试时发现,启用之后,SourceMap定位错误的问题,因为插件具体技术细节不了解,所以请作者判断下,如果有影响,又是否有解决的办法,谢谢!

The conditions do not work "automatically"

Hello,

Thanks for the tool that is a great way to deal with conditional rendering.
We use the conditional rendering in a Vue project to conditionally generate some parts in Vue components and in javascript files.

We have an issue though to generate the conditional rendering "automatically": when we want to switch from one condition to the other, compiling the code again (using npm run serve --optionX) will not make a difference. To apply the condition, we have to make a change in each files containing the directive /*IFTRUE_XXX (a space after the directive for example), then save. The next compilation will produce the code as expected.

I'm not sure if that's a bug or a problem from our setup?

Here is the extract our vue.config.json

module.exports = {
    /* IFTRUE_isMicrobit */
    configureWebpack: {
        devtool: "source-map",
        plugins: [
            new MoveAssetsPlugin({
                clean: true,
                patterns: [
                    {
                        from: "dist/pythonLib",
                        to: "dist/",
                    },
                ],
            }),
        ],
    },
    /* FITRUE_isMicrobit */   
    chainWebpack: (config) => {
        config.module
            .rule("conditionalCompilerVue")
            .test(/\.vue$/)
            .use("vue-loader")
            .loader("js-conditional-compile-loader")
            .options( {
                isPurePython: process.env.npm_config_python,
                isMicrobit: process.env.npm_config_microbit,
            });
        config.module
            .rule("conditionalCompilerTS")
            .test(/\.ts$/)
            .use("vue-loader")
            .loader("js-conditional-compile-loader")
            .options( {
                isPurePython: process.env.npm_config_python,
                isMicrobit: process.env.npm_config_microbit,
            });
    },
    publicPath: (process.env.npm_config_python)?"/editor/":"/microbit/",
    pluginOptions: {
        i18n: {
            locale: "en",
            fallbackLocale: "en",
            localeDir: "localisation",
            enableInSFC: false,
        },
    },
}

Thank you so much for your help - if any other file is needed to explore this issue, please let me know

属性名的方式可以使用多个属性吗

option如下配置的话,可以在代码里设置多个条件编译吗

{
ALI:true,
TENCENT: true
}


/* IFTRUE_ALI */
console.log('ali')
/* FITRUE_ALI */


/* IFTRUE_TENCENT */
console.log('TENCENT')
/* FITRUE_TENCENT*/

JSON支持

请问json的条件编译是不支持吗?

路由单独拆分后如何合并的问题

你好,有个问题请教一下,比如页面有20个路由,我设置了默认打包只打15个,另外5个单独打包(单独的没有入口所以无法独立运行),如果我在部署的时候另一个环境需要修改这五个路由里面的某处(全部打包太麻烦,所以修改具体地方,打包那五个路由模块即可),如何将两个打包后的文件组装起来了?因为生成后的哈希值不可控,默认没有那五个路由,打完之后需要手动去修改路由以及那五个模块,尝试了很多方案目前还没有解决

Not working on index.html

Hi,

I am developing something in Vue and I want conditional complilation at the entry point for my application - i.e. index.html.
However, js-conditional-compile-loader does not seem to be working there.

Can you help me please?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.