0

Given the following code I started my bootstrap.js file with:

import jQuery from 'jquery';

// jQuery
window.$ = window.jQuery = jQuery;

// Twitter bootstrap
import 'bootstrap-sass/assets/javascripts/bootstrap';

// Initialize theme
import './theme/bootstrap';

When I compiled this (using webpack) and ran it in my browser I got the following complaint from bootstrap: 'I need jQuery to work...'

I didn't (and still don't) understand why jQuery wasn't imported, I'm setting it to the global window object 1 rule above bootstrap.

However when I change my code and remove all imports:

// jQuery
window.$ = window.jQuery = require('jquery');

// Twitter bootstrap
require('bootstrap-sass/assets/javascripts/bootstrap');

// Initialize theme
require('./theme/bootstrap');

This code is working perfectly fine and everything is working as expected, but what I always thought was that import and require are basically the same thing and that import was just getting transpiled to a require call. This is apparently not the case, can someone explain to me what exactly is happening here and why require is working while import is not?

Wouter Rutgers
  • 541
  • 5
  • 14

1 Answers1

0

import statements are processed before a file begins executing, meaning that the ordering of import statements relative to code in the file itself will have no effect. require calls on the other hand are just function calls, so the ordering has an effect.

In your first example, all of the imports will have executed before the window.$ = window.jQuery = jQuery; line runs.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251