EugeneDeWaal
EugeneDeWaal

Reputation: 228

How to export a module

I started learning from https://egghead.io/technologies/es6 the ECMAScript 6 way, knowing there is still a lot that might change, but wanted to get a early start.

However, when I follow the tutorial instructions on (https://egghead.io/lessons/ecmascript-6-es6-modules-es2015-import-and-export) exactly the same, I get an error which I have no idea what I might have done wrong.

Uncaught ReferenceError: require is not defined

Code on that line after Babel converted to ES5

"use strict";

var _distExporter = require("dist/exporter");

console.log("2 + 3=", (0, _distExporter.sumTwo)(2, 3));
//# sourceMappingURL=importer.js.map

Developers are mentioning CommonJS and WebPack as a solution some even mentioned RequireJS, but nowhere in the tutorial did it state I should should code or use alternative libraries.

My HTML is this

<html>
<head>
  <script src="dist/importer.js"></script>
</head>
<body>

</body>
</html>

My importer.js is

import { sumTwo } from "dist/exporter";

console.log( "2 + 3=", sumTwo(2,3))

And my exporter.js is

function sumTwo(a, b){
  return a + b;
}

export { sumTwo };

I have no idea where I'm going wrong. I'm using BabelJS (https://babeljs.io/)

Upvotes: 1

Views: 1394

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

If you run this code under Node, rather than in a browser, you should see the results you are expecting. Node understands CommonJS require calls and will go away and grab that other file for you.

The browser has no idea that require is anything special. But we can use a tool to make the browser understand. Here's an example with Browserify, as some other people have mentioned you can also use WebPack, but I think the learning curve for WebPack is a lot steeper.

First you'll need a couple of modules.

npm install -g browserify
npm install --save-dev babelify

Then we can use these modules together like this.

browserify main-file.js -o output-file.js -t babelify

This will walk your source files checking calls to require in each one and adding the other files that it requires to the bundle. Then it runs the Babel transform over it, to convert ES6 to ES5. Finally it wraps it all up in some code that lets require work in a browser.

Upvotes: 1

Related Questions