23
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

babelify v7.2.* で 'sourceType: module' エラーを回避

Last updated at Posted at 2015-11-18

現象

gulpでbabelify v7.2.0をinstallしてトランスパイルしたら以下の様なエラーが発生した。

$ gulp
[18:24:05] Using gulpfile ~/hoge/gulpfile.js
[18:24:05] Starting 'browserify'...
[18:24:05] Finished 'browserify' after 25 ms
[18:24:05] Starting 'default'...
[18:24:05] Finished 'default' after 11 μs
Error : 'import' and 'export' may appear only with 'sourceType: module'

gulpfileは以下のとおり。

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

gulp.task('browserify', function() {
  browserify('src/index.js', { debug: true })
    .transform(babelify)
    .bundle()
    .on("error", function(err) {
      console.log("Error : " + err.message);
    })
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('./'))
});

gulp.task('default', ['browserify']);

解決策

browserifyのtransformの第2引数にpresetsを指定する。

.transform(babelify, {presets: ['es2015']})

Babel6.0.0からの仕様でpresetsを指定する形式になったらしい。babelifyはBabelのラッパーみたいなもののようで。

これを踏まえてpresetsをinstallし、browserifyのタスクは以下のように書くと良い。

$ npm install --save-dev babel-preset-es2015
gulp.task('browserify', function() {
  browserify('src/index.js', { debug: true })
    .transform(babelify, {presets: ['es2015']})
    .bundle()
    .on("error", function (err) { console.log("Error : " + err.message); })

所感

最近はあるバージョンから突然トランスパイルなどが動かなくなる時があるが、だいたいGitHubかNPMパッケージとかに書いてあるので真っ先に見ると良さそう。

23
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?