Search code examples
webpackwebpack-2

Conditional variabel name with webpack


I'm building an app that will have the sourcecode available to everyone. Depending on what the end system will use (there will be a possibility to run it with electron and under C# WebBrowserControl) different global variable names need to apply.

For example.

<--! This should not be applied to the end product if I don't specify that -->
<script>
    const electron = require('electron');
    const currentWindow = electron.remote.getCurrentWindow();
</script>
<!-- This is the end of the conditional statement -->

And I also want to change name on the variable currentWindow to window in the whole app.

Can I do this in some way with a webpack plugin/loader or whatever?

I used a similair plugin to grunt a while back were I had these conditional statements in the code depending on that command I ran with grunt.


Solution

  • There's a Webpack plugin named DefinePlugin that may do what you need: https://webpack.js.org/plugins/define-plugin/

    // webpack.config.js
    const webpack = require('webpack');
    
    module.exports = {
    
        ...
    
        plugins: [
            new webpack.DefinePlugin({
                HOST: 'electron' // or 'WebBrowserControl', etc.
            })
        ]
    
    }
    

    You can then access HOST as a global variable from your application code:

    if (HOST === 'electron') {
        const electron = require('electron');
        const currentWindow = electron.remote.getCurrentWindow();
    } else if (HOST === 'WebBrowserControl') {
        // etc...
    }
    

    Depending on how you kick off your Webpack build, you should be able to swap out the value of HOST in webpack.config.js based on the type of build you're doing.