Webpack and Global Variables


#1

I’m trying to use global variables with nativescript + angular. The issue is that even after setting global variables, Axios throws error saying “navigator is undefined” Axios is a node_module, and there are seleral others that use such global variables in my project so I can’t go and import global variables in each of these files.

How do I use global variables with webpack?

NOTE: it is important that variables are global as I can’t import them in each of the node_module they are used.


#2

Which flavour you are using for development?


#3

nativescript + angular (now edited into the question)


#4

Config

           new webpack.DefinePlugin({
                "global.TNS_WEBPACK": "true",
                "global.YOUR_VAR_NAME": JSON.stringify(env.param_from_cli),
                "process": undefined,
            }),

Anywhere in app

console.log(global.ENV_NAME)

#5

@manojdcoder what if I need to set a plugin global?

like

let localstorage = require('nativescript-localstorage')
global.localstorage = localstorage;

#6

The same is already set by the plugin itself, you don’t have to do it explicitly.


#7

@manojdcoder this replaces all the instances of that variable so I get

{} = {
        setTimeout: setTimeout,
        clearTimeout: clearTimeout,
        WebSocket: global.WebSocket,
        ArrayBuffer: global.ArrayBuffer,
        addEventListener: function () { },
        navigator: { onLine: true },
        location: {
            href: ''
        }
    };

in vendor.js which is obviously incorrent. This then throws unexpected = error