Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

'import' and 'export' may appear only with 'sourceType: module' #103

Closed
maiermic opened this issue Jul 15, 2015 · 37 comments
Closed

'import' and 'export' may appear only with 'sourceType: module' #103

maiermic opened this issue Jul 15, 2015 · 37 comments

Comments

@maiermic
Copy link

I switched from 6to5ify@3.1.2 to babelify@6.1.3 and at the same time upgraded browserify from 6.3.4 to 10.2.6, watchify from 2.3.0 to 3.2.3 and remapify from 1.4.3 to 2.0.3. Now I get several build errors: 'import' and 'export' may appear only with 'sourceType: module'

My build file looks more or less like this:

const browserify = require('browserify');
const babelify = require('babelify');
const remapify = require('remapify');
const watchify = require('watchify');

const b = browserify({
  cache: {},
  packageCache: {},
  fullPaths: false,
  debug: true
});
b.add(myFile);
b.transform(babelify);
b.plugin(remapify, [...]);
watchify(b).bundle(function(err, buf) { ... });
@jmm
Copy link
Member

jmm commented Jul 15, 2015

Do you have a stack trace or some more detailed error output? My money is on remapify causing it. Last I checked, v2 of it broke transforms, so my guess is it's preventing babelify from running, then browserify gets to the syntax phase and can't parse the input. (EDIT: or maybe it chokes as soon as it gets to deps and detective tries to parse it.)

@maiermic
Copy link
Author

I log err in watchify(b).bundle(function(err, buf) { ... }); and I get Error: Parsing file <my file>: 'import' and 'export' may appear only with 'sourceType: module' (<line>:<column>). This error message isn't really helpful. I could replace remapify with pathmodify to check, if remapify is causing these errors. My mappings look like this:

b.plugin(remapify, [{
  cwd: <directory>,
  src: '**/*.js',
  expose: <name>
}]);

What would be the equivalent in pathmodify? I tried

b.plugin(pathmodify(), {mods: [
  pathmodify.mod.dir(<name>, <directory>)
]});

but my modules are not found 😞

@jmm
Copy link
Member

jmm commented Jul 15, 2015

@maiermic Yeah, I would suggest trying one of the following:

  1. Give browserify just an entry file that require()s a single file with import|export that it can find without remapify, remove remapify and see what happens. Then if that works give it require() the same file, but in such a way that it needs remapify to find it, turn that back on and see what happens.

  2. Starting from where you left off in # 1, add my browserify-row-flow plugin to get more insight into what's happening. It should show what is the last browserify pipeline phase that's completed before the error, and possibly the source of the file in question, revealing if it was transformed or not.

  3. Try pathmodify instead as you suggested (disclaimer: I'm the author of this). Usage would look something like:

    var pathmod = require('pathmodify');
    
    .plugin(pathmod(), {mods: [
      pathmod.mod.dir('<name>', '<abs-path-to-directory>'),
    ]})

@maiermic
Copy link
Author

I tried pathmodify with absolute path and it works. Thank you very much. I will create an issue in remapify repository.

@jmm
Copy link
Member

jmm commented Jul 15, 2015

@maiermic Great! You're welcome.

@anshulguleria
Copy link

@maiermic In my case it happens only when I use extensions option.

This dosen't works:

let fs = require('fs'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    path = require('path');

console.log(__dirname)

browserify({
        debug: true,
        extensions: ['es6'],
        entries: ['src/test.es6']
    })
    .transform(babelify.configure({
        extensions: ['es6'],
        sourceMapRelative: path.resolve(__dirname, 'src')
    }))
    .bundle()
    .pipe(fs.createWriteStream("src/bundle.js"));

While this does works:

let fs = require('fs'),
    browserify = require('browserify'),
    babelify = require('babelify'),
    path = require('path');

console.log(__dirname)

browserify({
        debug: true,
        //extensions: ['es6'],
        //entries: ['src/test.es6']
        entries: ['src/test.js']
    })
    .transform(babelify.configure({
        //extensions: ['es6'],
        sourceMapRelative: path.resolve(__dirname, 'src')
    }))
    .bundle()
    .pipe(fs.createWriteStream("src/bundle.js"));

The only difference is with extensions nothing else.

@jmm
Copy link
Member

jmm commented Sep 15, 2015

@anshulguleria, @maiermic's problem was caused by the remapify plugin. Yours appears to be caused by the extensions values: prepend . to them.

@anshulguleria
Copy link

@jmm Thanks. That was exactly the problem. Didn't realizes it was this small.... wasted hours on it.

@jmm
Copy link
Member

jmm commented Sep 15, 2015

@anshulguleria You're welcome. Yeah, that's frustrating :( There was just a PR merged into Browserify to automatically prepend the .: browserify/browserify#1380. In this case I think you still would've had a problem if the value passed to Babelify didn't have it (although .es6 is currently configured for Babelify by default, so you didn't / don't necessarily need to set that option for Babelify at all.)

@anshulguleria
Copy link

I am getting same error again.

import stopwatch from "./stopwatch";
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

This time I was configuring browserify from package.json

  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "sourceMapRelative": "$PWD/src/js"
        }
      ]
    ]
  }

and trying to use npm scripts
"build:js": "browserify src/js/index.js --outfile build/js/index.js"
npm run build:js

Versions

"babelify": "^7.0.2",
"browserify": "^12.0.1",

@jmm Any idea why?

@jmm
Copy link
Member

jmm commented Oct 30, 2015

@anshulguleria It's because you're using babelify@7.x which depends on babel-core@6.x which doesn't transform anything by default. Look around for some info on Babel 6 presets and you'll see what you need to

@anshulguleria
Copy link

@jmm Thanks.
I do needed to provide preset es2015 for transform configuration.
And npm install --save-dev babel-preset-es2015
So my new configuration becomes

  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "sourceMapRelative": "$PWD/src/js",
          "presets": ["es2015"]
        }
      ]
    ]
  }

@genert
Copy link

genert commented Oct 30, 2015

I am getting same error after updating to latest version of babel & node.

import React from 'react'; ^ ParseError: 'import' and 'export' may appear only with 'sourceType: module'

I use gulp.

var appBundler = browserify({
    entries: [options.src],
    extension: [
      'jsx',
      'json',
      'js',
      'es6'
    ],
    transform: [
      [
        "babelify"
      ]
    ],
    debug: options.development,
    cache: {},
    packageCache: {},
    fullPaths: options.development
  });

.babelrc
{ "presets": [ "react", "es2016-stage1" ] }

@genert
Copy link

genert commented Oct 30, 2015

Ok, I added es2015 to babelrc before stage-1 and it does not throw that error, however things like es6 bind ::this.somefunc() throw syntaxerror...

@jmm
Copy link
Member

jmm commented Oct 30, 2015

@TheDeveloperXYZ Check out the support resources listed in the babel/babel README. Try to reproduce it with just Babel (not Babelify) and if it turns out to be a bug in Babel, file an issue on babel/babel.

@Thomas-P
Copy link

Thomas-P commented Nov 1, 2015

Hi,

i had the same problem, but switching back to version babelify@6.1.2 solved this problem. Could you try it out?

@christimiller
Copy link

@Thomas-P -- been fighting with this issue for a couple days now -- rolling back to 6.1.2 fixed it. (see: https://github.com/xirvr/xirvr.com)

@zertosh
Copy link
Member

zertosh commented Nov 1, 2015

@Thomas-P, @xirvr have you tried installing and using the presets?

@joseph-t-martin
Copy link

Hi,

I'm having a similar problem and getting the error:

Syntax error: 'import' and 'export' may appear only with 'sourceType: module'

My gulp.js file is as follows:

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

gulp.task('browserify', function() {
    return browserify()
        .require('js/app.js', { entry: true,  
            extensions: ['.js'], 
            debug: true 
        })
        .transform(babelify, {presets: ["stage-0", "react"]})
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('js'));
});

gulp.task('watch', function() {
    gulp.watch('**/*.js', ['browserify']);
});

@Thomas-P
Copy link

Thomas-P commented Nov 4, 2015

@zertosh yes, i tried, but it hasn't work for me. But I'm very happy, that the downgrade work.

@zertosh
Copy link
Member

zertosh commented Nov 4, 2015

@Thomas-P, can you provide me with a repo that I can use to reproduce the issue?

@sousk
Copy link

sousk commented Nov 5, 2015

Hi,
I got a same error, and here's reproduction code in my case.

@jmm
Copy link
Member

jmm commented Nov 5, 2015

@sousk you have no plugins or presets configured.

@jmm
Copy link
Member

jmm commented Nov 5, 2015

@sousk the name of your repro repo doesn't match the dep on babelify -- what version are you actually having a problem with?

@sousk
Copy link

sousk commented Nov 5, 2015

@jmm You're right. That's not a issue but just because I missed to set presets configuration.
The problem has gone after installing babel-preset-es2015 and giving 'es2015' to the option.
Thanks.

@sousk
Copy link

sousk commented Nov 5, 2015

@jmm I got an error at babelify@7.2.0 (without presets).
I guess people who get a same error with babel-core@6.x may forget to set the presets like me.

@zertosh
Copy link
Member

zertosh commented Nov 5, 2015

It's pretty clear that people aren't reading the README after doing a major version upgrade. I'm going to add a one-time warning if babel throws and there are no presets/plugins specified.

@sebmck Is there any use to running babel w/o any plugins? (besides to generate an AST)

@zertosh
Copy link
Member

zertosh commented Nov 5, 2015

Actually that's not going to work because it's not babel throwing an error, it's browserify.

@sebmck
Copy link

sebmck commented Nov 5, 2015

@zertosh You could just be cheap and do indexOf("import ") and output a warning.

@andrevinsky
Copy link

@anshulguleria, 👍

@swimtver
Copy link

$ npm install babel-preset-es2015

and in gulpfile set:
.transform(["babelify",{presets: ["es2015"]}])

It's work for me.
More info: http://babeljs.io/docs/plugins/#presets

@danehansen
Copy link

@joeyisking I had your same problem, and realized we need both stage-0 AND es2015:
.transform(babelify, {presets: ["es2015", "stage-0", "react"]})

@joseph-t-martin
Copy link

@danehansen It worked! You're a dead-set legend

@kmturley
Copy link

I managed to get this working using the following commands:

npm install gulp --save-dev
npm install babelify --save-dev
npm install browserify --save-dev
npm install vinyl-source-stream --save-dev
npm install babel-preset-es2015 --save-dev

And then in my gulpfile.js

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

gulp.task('dist', function () {
    browserify({entries: 'src/app.js', extensions: ['.js'], debug: true})
        .transform(babelify, { presets: ['es2015'] })
        .bundle()
        .pipe(source('all.min.js'))
        .pipe(gulp.dest('dist/modules'));
});

@nerijusgood
Copy link

I believe this is something to do with newer update of babelify. I had one project working just fine with

gulp.task('watchify', function () {
  var args = merge(watchify.args, { debug: true })
  var bundler = watchify(browserify('./src/js/main.js', args)).transform(babelify, {})
  bundle_js(bundler)

  bundler.on('update', function () {
    bundle_js(bundler)
  })
})

function bundle_js(bundler) {
  return bundler.bundle()
    .on('error', gutil.log)
    .pipe(source('main.js'))
    .pipe(buffer())
    .pipe(gulp.dest('js'))
    .pipe(sourcemaps.init({ loadMaps: true }))
      // capture sourcemaps from transforms
      .pipe(uglify())
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('js'))
}

And I used same code in new poject, and it always threw import' and 'export' may appear only with 'sourceType: module.

Then I realised that in the new project, it had babelify 7.2.0 and the old one 6.3.0. So I just downgraded to 6.3.0 and then everything worked just fine.

@nicola
Copy link

nicola commented Dec 21, 2015

news? (I also had to downgrade to 6.3.0)

@zertosh
Copy link
Member

zertosh commented Dec 21, 2015

If you're getting this error then you most certainly have a misconfigured Babel 6 setup. Babel 6 is very different from Babel 5. It's not a drop-in replacement. The readme has more information.

@babel babel locked and limited conversation to collaborators Dec 21, 2015
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests