Parsing error: 'import' and 'export' may only appear at the top level

An error

Today, after being given to the project fitted eslint Parsing error: 'import' and 'export' may only appear at the top level.

recurrent

import "lib-flexible/flexible.js";
import userOptions from "@/assets/js/merge";
import { loadFiles } from "@/assets/js/tools";
import env from "@/constants/env";

window.userOptions = userOptions;

const assets = 123;

if (env === "dev") {
  import("@/assets/css/blog-common.min.css"); // 这一行import报错
} else {
  loadFiles([
    {
      name: `${userOptions.theme.name}`,
      type: "js"
    }
  ]);
}

es6 modules allow this syntax is written, eslint treat it as a mistake to deal with, as if the head of several importwritten the following words should indeed report this error.

the reason

eslint default parser may not support dynamic import.

solve

Use babel-eslint resolved.

npm i babel-eslint -D

  ...
+ parser: "babel-eslint",
  parserOptions: {
    sourceType: 'module',
  }
  ...

Finally, attach links

to sum up

Baidu search results is really out of the Macabre. A small problem a lot of wasted time.

Guess you like

Origin www.cnblogs.com/guangzan/p/12466467.html
Recommended