I'm still a beginner, i try to to export and import one class into a main file, the other class in the others class file and use them.
And then gulp ES5 code with 6to5 (now Babel).
// file a.js
import B from 'b.js';
class A {
constructor() {
B.methodB();
}
}
export default A;
// file b.js
class B {
methodB() {
console.log('hi from b');
}
}
export default B;
// file main.js
import A from 'a.js';
new A();
My gulpfile:
var gulp = require('gulp');
var to5 = require('gulp-6to5');
gulp.task('default', function () {
return gulp.src('main.js')
.pipe(to5())
.pipe(gulp.dest('dist'));
});
And this is my dist/main.js
file:
"use strict";
var _interopRequire = function (obj) {
return obj && (obj["default"] || obj);
};
var A = _interopRequire(require("a.js"));
new A();
The error in console: ReferenceError: require is not defined
Which of course does not work ... what am I doing wrong or what lack I yet? I do not get it exactly.
I was having the exact same problem before myself... As Qantas mentioned in the comments, Babel (formerly 6to5) will convert syntax, but it won't do module loading or polyfills.
I've found the easiest workflow is using browserify with gulp. This takes care of transpiling, adding polyfills, bundling, minification, and source map generation in one hit. This question has a pretty nice example: Gulp + browserify + 6to5 + source maps.
This version adds minification and polyfills. An example for your case would look like this:
It's important that uglify has mangle set to false; it really doesn't seem to play nice with the transformed code.
If you don't have all the dependencies installed, you may want to create a
package.json
file, and ensure that following packages are defined in the dependencies object:Most of these won't work if installed with
-g
, so consider yourself warned :PThen, just run
npm install
to install all the dependencies, andgulp
to run the default task and transpile all of your code.Your other files look good, you have the right idea with importing at the beginning of each file and exporting your defaults :) If you want some examples of babelified ES6 in the wild, I have a couple of projects on GitHub that might help.
It's seems you need to import the requirejs fond in your HTML like that:
And your files need to be something like that:
Note that you need to put the module's directory
./a
and./b
on theimport
.And your gulpfile need to be:
Note that you need to transform all of your file with
src/*.js
on thegulp.src