Ian Pollak
Ian Pollak

Reputation: 103

Webpack bundling simple JS files

I realize this might prove a total misunderstanding of what Webpack is for but I've not been able to find a straight answer anywhere.

Basically I have two files:

hello.js

function hello() {
    console.log('Hello, world!');
}

entry.js

require('./hello.js');

hello(); // should log 'Hello, world!'

I wanted to pack them into a single file for faster loading using Webpack. My condition was that I should not have to modify hello.js in any way (let's say it is a big, obfuscated library that I don't have the right to modify).

I expected that running

webpack entry.js result.js

will give me a usable bundle in result.js but instead result.js gives me this error:

Uncaught ReferenceError: hello is not defined

Is there a way to achieve what I want? Just simply bundle scripts together to make them available in the global namespace without having to add anything to them ?

Upvotes: 0

Views: 119

Answers (1)

Vikramaditya
Vikramaditya

Reputation: 5574

File hello.js is not exporting anything, you have to export hello function from hello.js file like this,

module.exports = function () {
  console.log('Hello, world!');
}

and then in your entry file.

var hello = require('./hello.js');
hello();

Upvotes: 1

Related Questions