简体   繁体   English

使用Babel的Yeeoman Webapp中的ES6模块

[英]ES6 Modules in yeoman webapp with Babel

I'm trying to write some ES6 code. 我正在尝试编写一些ES6代码。 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. 看到yeoman webapp生成器会自动通过Babel( https://github.com/yeoman/generator-webapp )为您转换ES6代码,因此我决定使用它。

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. 因此,babel为我进行了转换,据我了解,它实际上将模块默认更改为requirejs。 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 未捕获的ReferenceError:未定义导出@ game-engine.js:3

Uncaught ReferenceError: require is not defined @ main.js:1 未被捕获的ReferenceError:需求未定义@ main.js:1

I tried manually including requirejs but I still get errors. 我尝试手动包括requirejs,但仍然出现错误。

Has anyone gotten modules working with yeoman webapp? 是否有人获得了与yeoman webapp一起工作的模块? I'd love to get this working. 我很想让这个工作。

Thanks, Rob 谢谢,罗伯

Hopefully you found a solution for that. 希望您找到了解决方案。 If not, you could create a gulp task for this: 如果没有,您可以为此创建一个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'));
}); 

I recently had exactly the same problem. 我最近遇到了完全相同的问题。 Babel is not taking care of modules management. Babel并不负责模块管理。 You have to bundle all your JS files into one unique file. 您必须将所有JS文件捆绑到一个唯一的文件中。 For that I used browserify. 为此,我使用了browserify。

I found what I needed in this article: http://advantcomp.com/blog/ES6Modules/ (Archived Post) 我在本文中找到了我需要的东西: http : //advantcomp.com/blog/ES6Modules/ (已存档)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM