nauti nauti - 4 months ago 12
Node.js Question

Webpack: single scope for multiple js files?

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.

Answer

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.