ironhardchaw ironhardchaw - 1 year ago 53
Javascript Question

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

// 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:


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


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'


  • Webpack: 1.12.9

  • Babel: 6.0.0

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!


Answer Source

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';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download