1

Consider the root index.js file in a React app that does the following:

console.log("INDEX.JS")
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
//Internal Dependencies
import Auth from './containers/Auth';
import store from './store/store';
import ErrorBoundary from './containers/ErrorBoundary';
//Highcharts config
import highchartsConfig from './globalChartConfig';
//Global styles
import './index.css';

highchartsConfig();

render(
  <Router>
    <Provider store={store}>
      <ErrorBoundary>
        <Auth />
      </ErrorBoundary>
    </Provider>
  </Router>,
  document.getElementById('root')
);

The import statements are executed BEFORE the console.log statement at the top of this file. a console.log at the top of the Auth.js file will be executed first. Why is that?

The following console.log() is the first thing that logs to the console.

// Auth.js
console.log('AUTH')
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
JohnSnow
  • 444
  • 4
  • 17

1 Answers1

2

You must scope all import statements at the top. This restriction allows webpack(not only webpack, any module loader actually) to analyze statically what modules are imported by a module and load them before executing its body.

console.log('first import then log')
import { foo } from 'foo'

Putting code above import throws an eslint warning (import/first)

Why inside index.js console.log fires after the imports and inside auth.js executes in the expected order?

When calling index.js (entry point which will render the entire application) webpack will bundle every module including those required for App and Auth and then call console.log. When you access Auth.js all modules are already bundled so the only thing left to do is to call console.log.

For a detailed explanation

Dupocas
  • 20,285
  • 6
  • 38
  • 56