U4EA
U4EA

Reputation: 912

Webpack - how can I merge/load .js files in specific order?

I've been looking everywhere for an answer to this and I just can't seem to find one.

It's a simple (it seems) issue. I want to be able to merge .js files in the order they are appear in i.e. if I have this in my index.js (JSX), I would like them to be loaded in the order listed: -

require('script1.js');
require('script2.js');
require('script3.js');

However, no matter what I try, webpack seems to just load them in whatever order it wants. The obvious example of this is so I can load jQuery first to expose $ to preceding scripts. However, I would just like to know how to do this in general as I am building a rather complex app.

I hope this has not been answer somewhere before and I have missed it... this is driving me INSANE. I am used to work with Gulp SASS, which was so much easier.

If it makes any difference, I am using this with ReactJS/ReactDOM.

Upvotes: 0

Views: 660

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

This is a fundamental misunderstanding of how require (and ES2015's import, which Webpack also partially supports) works.

Instead of manually maintaining the order of your scripts, the point of require/import is to free you from having to do this manual maintenance of script order.

Instead, each script (module) declares its dependencies via require/import, and then the environment (Webpack, in your case) works out the dependency graph and ensures the files are loaded in the correct order (and in the case of true import, does clever things around live bindings).

Your jQuery example would work like this: Any of your scripts (modules) that requires jQuery does this:

var $ = require("jquery");

or

import $ from "jquery";

or similar.

That makes jQuery's main function available as $ within that module. It also tells Webpack that that module requires jQuery. So it loads the scripts in the correct order to make that happen.

More in the Webpack Introduction.

Upvotes: 2

Related Questions