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

Solution 1:

I got this error when I was missing a closing bracket.

Simplified recreation:

const foo = () => {
  return (
    'bar'
  );
}; <== this bracket was missing

export default foo;

Solution 2:

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

This means that webpack is bundling the non-transpiled ES6 code, which is why these import/export statements are being found. babel-loader must therefore not be transpiling what you expect.

If you simply remove the include and exclude rules from its loader config, the default behavior of transpiling everything besides what's in node_modules will kick in. For some reason or another, the current rules are causing some/all files to be skipped.

module.exports = {
  entry: './src/entry.js',
  output: {
    filename: './public/js/app.js'
  },
  devtool: 'source-map',
  plugins: [
    new ExtractTextPlugin('./public/css/style.css')
  ],
  module: {
    preLoaders: [{
      test: /\.js$/, 
      exclude: /node_modules/,
      loader: 'jshint-loader'
    }],
    loaders: [{
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract(
        'style',
        'css!sass'
      ),
    },
    {
      test: /\.vue$/,
      loader: 'vue'
    },
    {
      test: /\.js$/,
      loader: 'babel-loader',
      query: {
        presets: ['es2015']
      }
    }]
  }
};

Solution 3:

Make sure you have a .babelrc file that declares what Babel is supposed to be transpiling. I spent like 30 minutes trying to figure this exact error. After I copied a bunch of files over to a new folder and found out I didn't copy the .babelrc file because it was hidden.

{
  "presets": "es2015"
}

or something along those lines is what you are looking for inside your .babelrc file

Solution 4:

I had the same issue using webpack4, i was missing the file .babelrc in the root folder:

{
    "presets":["env", "react"],
    "plugins": [
        "syntax-dynamic-import"
    ]
}

From package.json :

"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",

Solution 5:

I got this error when I was missing a closing brace in a component method:

const Whoops = props => {
  const wonk = () => {props.wonk();      // <- note missing } brace!
  return (
    <View onPress={wonk} />
  )
}