[webpack] 'import' and 'export' may only appear at the top level

I'm using webpack with vuejs. Webpack does its thing, but when I look at the outputted app.js file, it gives me this error.

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

I'm assuming it's a problem with babel not converting the code? Because I'm getting this in the browser when viewing the application.

Unexpected token import

Here's my entry.js for my vuejs application:

/*jshint esversion: 6 */
import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
require('./css/style.scss');

// Export the vue router
export var router = new VueRouter({
  hashbang: false,
  root: '/'
  // history: true
});

// Set up routing and match routes to components
router.map({
  '/': {
    component: require('./components/home/Home.vue')
  }
});

// Redirect to the home route if any routes are unmatched
router.redirect({
  '*': '/'
});

// Start the app on the #app div
router.start(App, '#app');

Here's my webpack.config.js:

var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');

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$/,
        exclude: /node_modules/,
        include: [
          path.resolve(__dirname, "src/services"),
        ],
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        }
    }]
  }
};

Here's my packages.json file:

{
  "name": "test-webpack",
  "version": "1.0.0",
  "description": "Myapp",
  "main": "entry.js",
  "scripts": {
    "watch": "webpack-dev-server  --host $IP --port $PORT  --hot --inline --config webpack.config.js",
    "dev": "webpack",
    "build": ""
  },
  "author": "Dev",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.9.1",
    "babel-loader": "^6.2.4",
    "babel-plugin-transform-class-properties": "^6.10.2",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-es2015": "^6.9.0",
    "babel-runtime": "^6.9.2",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "jshint": "^2.9.2",
    "jshint-loader": "^0.8.3",
    "node-sass": "^3.8.0",
    "path": "^0.12.7",
    "sass-loader": "^3.2.0",
    "style-loader": "^0.13.1",
    "vue-hot-reload-api": "^1.3.2",
    "vue-html-loader": "^1.2.2",
    "vue-loader": "^8.5.2",
    "vue-style-loader": "^1.0.0",
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1"
  },
  "dependencies": {
    "vue": "^1.0.25",
    "vue-router": "^0.7.13"
  }
}

This question is related to webpack vue.js babeljs

The answer is


Look out for a double opening bracket syntax error as well {{ which can cause this error message to appear


For me, this was caused by a reference to module in a hot module replacement implementation:

constructor() {
  if (module && module.hot) {
    module.hot.status(status => {
      if (status === 'dispose') {
        this.webSocket.close();
      }
    });
  }
}

Maybe you're missing some plugins, try:

npm i --save-dev babel-plugin-transform-vue-jsx

npm i --save-dev babel-plugin-transform-runtime

npm i --save-dev babel-plugin-syntax-dynamic-import
  • If using "Webpack.config.js":

Missing Plugins

  • If using ".babelrc", see answer in this link.

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",

My error is caused by a System.import('xxx.js') statment. After replacing it with import xxx from 'xxx.js', the error solved.

I think it is because require('xxx.scss') also caused a dynamic import.

For the case in the question description, in my opinion, dynamic imports is not necessary, so the problem should be solved by just replacing all requires with import ... from ....

For some case which dynamic imports are necessary, you may need @babel/plugin-syntax-dynamic-import as other answers in this question.


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


I am using Webpack 2.2.0 to bundle my React JS modules.

Encountered a similar issue while importing modules in my main app.js file.

After 30 minutes of headbanging I updated the RegEx for testing the file types in my webpack.config.js.

Carefully notice the ? symbol in test RegEx query.

{
    test: /\.js?$/,
    exclude: /(node_modules)/,
    loader: 'react-hot-loader'
}

It worked for me !!


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} />
  )
}

Using webpack 4.14.0 and babel-cli 6.26 I had to install this Babel plugin to fix the SyntaxError: 'import' and 'export' may only appear at the top level error: babel-plugin-syntax-dynamic-import

It was linked through from the Webpack Code Splitting Docs.


I do not know how to solve this problem differently, but this is solved simply. The loader babel should be placed at the beginning of the array and everything works.


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

Simplified recreation:

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

export default foo;

Vue supports async components:

Source : https://vueschool.io/articles/vuejs-tutorials/async-vuejs-components/

<script>
export default {
  data: () => ({ show: false }),
  components: {
    Tooltip: () => import("./Tooltip")
  }
};
</script>

Good Luck...


This is not direct answer to the original question but I hope this suggestion helps someones with similar error:

When using a newer web-api with Webpack+Babel for transpiling and you get

Module parse failed: 'import' and 'export' may only appear at the top level

then you probably forgot to import a polyfill.

For example:
when using fetch() api and targeting for es2015, you should

  1. add whatwg-fetch polyfill to package.json
  2. add import {fetch} from 'whatwg-fetch'

I got this error after upgrading to webpack 4.29.x. It turned out that webpack 4.29.x triggered npm's peerDependency bug. And according to them, the bug is not going to get fixed soon. Here's the workaround from sokra

  • add "acorn": "^6.0.5" to your application package.json.
  • Switch to yarn. It doesn't have this bug.
  • npm update acorn --depth 20 npm dedupe (works only in some cases)
  • rm package-lock.json npm i (works only in some cases)
  • update all other packages that depend on an older version for acorn (works only in some cases)
  • lock webpack at 4.28.4 in your package.json

Update

According to comment below, this bug doesn't exist anymore after 4.36.0


Examples related to webpack

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 Support for the experimental syntax 'classProperties' isn't currently enabled npx command not found where is create-react-app webpack config and files? How can I go back/route-back on vue-router? webpack: Module not found: Error: Can't resolve (with relative path) Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' The create-react-app imports restriction outside of src directory How to import image (.svg, .png ) in a React Component How to include css files in Vue 2

Examples related to vue.js

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Center content vertically on Vuetify Vue.js get selected option on @change Using Environment Variables with Vue.js did you register the component correctly? For recursive components, make sure to provide the "name" option Vue 'export default' vs 'new Vue' How can I go back/route-back on vue-router? Change the default base url for axios How to reference static assets within vue javascript How to change port number in vue-cli project

Examples related to babeljs

Support for the experimental syntax 'classProperties' isn't currently enabled Export multiple classes in ES6 modules Getting Unexpected Token Export 'import' and 'export' may only appear at the top level Dynamically add child components in React Call async/await functions in parallel Correct way to import lodash Babel command not found ES6 exporting/importing in index file "unexpected token import" in Nodejs5 and babel?