0

I'm trying to port my JavaScript source code to JavaScript ES6. To acomplish this I have so far:

1) installed Babel to my project folder

2) created .babelrc file

3) defined the file watcher in my WebStorm to auto transpile JavaScript files.

Transpiling seems to work well, the "older" syntax JavaScript files get created in a dist folder. However, when I try to run my transpiled code (added in a .html file) the alert test doesn't show up when using import statement.

Here's the source code:

arquivo.js

let test = 'Alert from Arquivo.js';

export {test};

main.js

import {test} from "./arquivo";

alert(test);

After auto transpile:

arquivo.js

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
var test = 'Alert from Arquivo.js';

exports.test = test;
//# sourceMappingURL=arquivo.js.map

main.js

"use strict";

var _arquivo = require("./arquivo");

alert(_arquivo.test);
//# sourceMappingURL=main.js.map

This is my index.html file inside same transpiled JavaScript files folder:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>

    <!--
    main.js is the after
    transpiled code
    -->
    <script src="main.js"></script>
</head>
<body>
</body>
</html>

Browser console reports this:

Uncaught ReferenceError: require is not defined
    at main.js:3

How to avoid this problem?

Maciej21592
  • 114
  • 1
  • 13
Lucas Sousa
  • 192
  • 3
  • 14
  • Are you getting any errors in your console? – sliptype Feb 26 '18 at 22:58
  • Yes, I messed up it, sorry! Just added to question. – Lucas Sousa Feb 26 '18 at 23:25
  • 2
    Babel only transpiles individual files and assumes there's a CommonJS module framework in place. In other words, if your environment doesn't support `require` you need another tool to take care of the bundling, such as Webpack or Browserify. – Lennholm Feb 27 '18 at 00:07
  • @MikaelLennholm I searched a bit about both. In other words browserify or webpack works like Babel? I would say.. It converts the code to a new file with refactored sentences or works at background? Sorry, I'm newbie in Javascript/web development. – Lucas Sousa Feb 27 '18 at 00:55
  • @MikaelLennholm I'm asking this to know if I can use a file watcher like I used with babel. – Lucas Sousa Feb 27 '18 at 00:57
  • 1
    @LucasSousa Yes, in that sense they work the same way, they take the source code and produce a new JS file. The most common way to use them in conjunction with Babel is to have Babel as a plugin, which transpiles each individual file before the modules are bundled. Both Webpack and Browserify have utilities for watching the source files. – Lennholm Feb 27 '18 at 09:45

0 Answers0