1

Imagine two javascript files and one entry point file:

app.js:

require(a.js);
require(b.js);

a.js:

var a = 4;

b.js:

var b = a+1;
console.debug(b);

This unfortunately does not work because the context of file a is lost in file b, meaning b.js does not know of any variable called a.

How can I fix that using Webpack - I simply want get the same result as

<script src="a.js"></script>
<script src="b.js"></script>

with the added effect of bundling through Webpack.

nauti
  • 1,396
  • 3
  • 16
  • 37

1 Answers1

2

Using ES2015 modules (which may not be available for you, you can use require instead)

a.js:

export var a = 4;

b.js

import { a } from "./b.js";
var b = a+1;
console.debug(b);

Webpack is a module building/bundling system that works by creating UMD (universal modules) from javascript files. You have to import/export these modules in order for them to be in scope.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • 2
    The problem is that there are tons of variable dependencies which I cannot all export. Isn't there a different way to just concatenate them and minify in order (like gulp does for example) – nauti Aug 09 '16 at 14:46
  • @nauti Unfortunately I find it really hard that you'll find a way to do what you're thinking. The most you can do to minimize the number of exports is aggregating multiple variables into objects and exporting these objects instead. Otherwise, I'd say that Webpack just isn't for you. – Andre Pena Aug 09 '16 at 15:49
  • 3
    I was under the impression that it is good practice to split up huge javascript files into logical subfiles (components) when writing bigger applications - if Webpack does not have a way of simply concatenating files before bundling, I really do have to think twice before using it in the future. That is a disappointment. – nauti Aug 09 '16 at 18:23
  • how are you approaching this now? Finding myself in similar position with larger and larger js files. I use Webpack a lot but often with starter themes / react but not sure how to manage this with vanilla js. Thanks. – v3nt Oct 15 '20 at 08:34