ironhardchaw
ironhardchaw

Reputation: 169

Globals undefined in imported sources, but working in required sources

Thanks for your consideration in this matter! I've spent the last few days scouring SO, GH, and everywhere else I could think of for any leads on this issue. Hoping that it is, in fact, an issue.

Given my webpack entry source:

global.val = 'some-value';

// 1) Global variables work just fine when the source is require'd
require('./second');

// 2) Global variables don't seem to be available when the source is imported
//   Results in: ReferenceError: val is not defined
import './second';

And my second source file is simply logging that value:

console.log(val);

If second.js is imported, val is undefined. If it's required, val is set to 'some-value' as it should be. I've not been able to find any explanation for this behaviour.

webpack.config.js:

const webpack = require('webpack');

module.exports = {
  output: {
    filename: 'main.js',
    publicPath: '/'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel-loader',

      query: {
        presets: ['es2015','react']
      }
    }]
  },
  devtool: 'source-map'
};

Versions:

I run the exact same code through Babel server-side without issue, but when I run it through Webpack and server it client-side, I end up with this issue. I've been kicking myself over this one for several days now. Would be grateful for any assistance you can offer! Let me know if you need any more info!

Thanks!

Upvotes: 0

Views: 74

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161517

This is expected behavior and I'd expect Babel to do the same thing. import statements are processed before the body of the module is executed, so

global.val = 'some-value';
import './second';

will behave just like

import './second';
global.val = 'some-value';

If you really wanted to do this, you'd need to move the global assignment into its own module, e.g.

import './initialize-globals';
import './second';

Upvotes: 1

Related Questions