T
T
Taras Labiak2016-11-09 14:54:37
JavaScript
Taras Labiak, 2016-11-09 14:54:37

How to define global variables in webpack?

I have a file that defines some global variables

let isClient = !!('undefined' !== typeof window && window.document)

if (isClient) {
  window.global = window
}

global.isClient = isClient
global.isServer = !isClient
global.isChrome = isClient && !!self.chrome && !!window.chrome.webstore;
global.isBlink = isClient && isChrome && !!window.CSS;
global.isFirefox = isClient && self.InstallTrigger;

global.DEBUG = true
Object.defineProperty(global, 'DEBUG', {
  writable: false,
  value: !!('undefined' !== typeof localStorage && +localStorage.getItem('debug'))
})

global.debug = console.log.bind(console)

global.announce = function announce(objects) {
  for (let name in objects) {
    Object.defineProperty(global, name, {
      writable: true,
      value: objects[name]
    })
  }
}

And the webpack setup
const isProduction = 'prod' === process.env.MODE

const config = {
  entry: [
    __dirname + '/globals.js',
    __dirname + '/entry.jsx'
  ],
  watch: !isProduction,
  output: {
    path: __dirname + '/public',
    filename: 'gay.js',
    comments: false
  },
  module: {
    loaders: [
      {test: /\.css$/, loaders: ['style']},
      {test: /\.scss$/, loaders: ['style', 'css', 'sass']},
      {test: /\.less$/, loaders: ['less']},
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url-loader?limit=10000&minetype=application/font-woff"
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "file-loader"
      },
      {
        test: /\.jsx$/,
        exclude: /(node_modules)/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'react'],
          plugins: ['transform-class-properties']
        }
      }
    ]
  },
  resolve: {
    modulesDirectories: [__dirname + '/node_modules']
  },
  plugins: []
}

if (isProduction) {
  config.plugins.push(
    new (require('webpack-uglify-js-plugin'))({
      cacheFolder: '/tmp',
      debug: false,
      minimize: false,
      sourceMap: false,
      compress: {
        warnings: true
      }
    })
  )
}
else {
  config.devtool = 'source-map'
}

module.exports = config

If uglify is enabled, does it throw an error that isClient (and other globals defined in globals.js) does not exist?
Is there a way to define global variables, or is it mandatory to use require/import?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
timfcsm, 2016-11-09
@timfcsm

just import globals.js into entry.jsx ... otherwise you put globals.js in a separate bundle, where there is nothing else,
but in general there are a lot of different ways, for different cases

_
_ _, 2016-11-09
@AMar4enko

An example from the Webpack documentation:

new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true),
    VERSION: JSON.stringify("5fa3b9")
    TWO: "1+1"
})

RTFM
At once I will make a reservation how it works. It works by replacing the keys with their string values. For example for
if (TEST == true) {
}

the output after applying the plugin with { TEST: JSON.stringify(false) } will be
if (false == true) {
}

after applying UglifyJS to such code, such a branch will be completely removed from the resulting code.
Why JSON.stringify - DefinePlugin treats key values ​​as strings containing JavaScript. So the boolean value is { TEST: "false" } and the string value
is { TEST: "\"false\"" }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question