简体   繁体   English

Browserify和Babel gulp任务

[英]Browserify and Babel gulp tasks

I want to use both Browserify and Babel with my JavaScript. 我想用我的JavaScript同时使用Browserify和Babel。 For this I created a gulp task 为此,我创建了一个gulp任务

gulp.task('babel', function() {
    return gulp.src('_babel/*.js')
        .pipe(browserify({ insertGlobals : true }))
        .pipe(babel({ presets: ['es2015'] }))
        .pipe(gulp.dest('_dev/js'));
});

Unfortunately, when I want to use import within my code, I am getting an error: 不幸的是,当我想在我的代码中使用import ,我收到一个错误:

ParseError: 'import' and 'export' may only appear at the top level

My main js file is very simple: 我的主要js文件非常简单:

import 'directives/toggleClass';

I'm guessing that it is because of Babel (and it's use strict addition), but what can I do? 我猜这是因为Babel(并且use strict添加),但我该怎么办?

Babel maintains an official transform for Browserify called babelify and it should be used wherever possible if using babel and browserify. Babel为Browserify维护了一个名为babelify的官方转换,如果使用babel和browserify ,应尽可能使用它。

Drop the use of babel directly and place babelify as a transform plugin for browserify. 直接放弃使用babel并将babelify作为browserify的转换插件。 There are many ways to configure browserify but specifying config in your package.json would probably be easiest. 有许多方法可以配置browserify,但在package.json指定config可能是最简单的。

"browserify": { 
  "transform": [["babelify", { "presets": ["es2015"] }]]
}

Your gulp task will then be simplified 然后,您的gulp任务将被简化

gulp.task('babel', function() {
    return gulp.src('_babel/*.js')
        .pipe(browserify({ insertGlobals : true }))
        .pipe(gulp.dest('_dev/js'));
});

Browserify also exposes methods to do this programmatically so you will be able to configure the bundler from inside your gulp task (dropping the package config, although using the package is perfectly fine for this), check their documentation and experiment, I've done it before but its been a long time since I used gulp (using gulp here is just a complication you dont need, but I expect you are using it elsewhere in your build pipeline where it might be more helpful). Browserify还公开了以编程方式执行此操作的方法,因此您可以从gulp任务内部配置bundler(删除包配置,尽管使用该包非常好),检查他们的文档和实验,我已经完成了以前,但是自从我使用gulp已经很久了(在这里使用gulp只是一个你不需要的复杂功能,但我希望你在构建管道的其他地方使用它可能会更有帮助)。

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

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