ES6 Modules in yeoman webapp with Babel

时间:2015-07-31 20:48:09

标签: javascript web-applications yeoman babeljs

I'm trying to write some ES6 code. Seeing that the yeoman webapp generator automatically transpiles ES6 code for you with Babel (https://github.com/yeoman/generator-webapp), I decided to use that.

It was working fine until I tried to use modules.

My import looks like this:

import {GameEngine} from './game-engine.js';

My export looks like this:

export class GameEngine {

So, babel transpiles this for me, and from what I understand it actually changes the modules to requirejs by default. When I look at my transpiled code I see this:

Import:

var _gameEngine = require('game-engine');

Export:

Object.defineProperty(exports, '__esModule', {
    value: true
});

I get console errors with this:

Uncaught ReferenceError: exports is not defined @ game-engine.js:3

Uncaught ReferenceError: require is not defined @ main.js:1

I tried manually including requirejs but I still get errors.

Has anyone gotten modules working with yeoman webapp? I'd love to get this working.

Thanks, Rob

2 个答案:

答案 0 :(得分:2)

希望你找到了解决方案。如果没有,您可以为此创建一个gulp任务:

var gulp = require('gulp'),
    browserify = require("browserify"),
    babelify = require("babelify"),
    buffer = require('vinyl-buffer'),
    source = require('vinyl-source-stream'),
    sourcemaps = require('gulp-sourcemaps');

gulp.task('buildJs', function() {
    return browserify({
        entries: './app/src/app.js',
        debug: true
    })
    .transform(babelify)
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(DEST+'/src'));
}); 

答案 1 :(得分:0)

我最近遇到了完全相同的问题。 Babel没有负责模块管理。您必须将所有JS文件捆绑到一个唯一文件中。为此,我使用了browserify。

我在本文中找到了我需要的内容:http://advantcomp.com/blog/ES6Modules/(已存档的帖子)