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

后端 未结 15 1553
耶瑟儿~
耶瑟儿~ 2020-12-08 18:00

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\

相关标签:
15条回答
  • 2020-12-08 18:44

    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

    0 讨论(0)
  • 2020-12-08 18:45

    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'
    0 讨论(0)
  • 2020-12-08 18:45

    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.

    0 讨论(0)
  • 2020-12-08 18:46

    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...

    0 讨论(0)
  • 2020-12-08 18:47

    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 !!

    0 讨论(0)
  • 2020-12-08 18:47

    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();
          }
        });
      }
    }
    
    0 讨论(0)
提交回复
热议问题