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

报错

今天給项目装上 eslint 后出现报错 Parsing error: 'import' and 'export' may only appear at the top level.

复现

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 模块语法是允许这样写的, eslint 却把它当成错误来处理, 如果如上头部的几个 import 写在下面的话的确应该报此错误.

原因

eslint 默认解析器可能不支持动态导入.

解决

使用 babel-eslint 解决.

npm i babel-eslint -D

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

最后附上链接

posted @ 2020-03-11 23:34  guangzan  阅读(9936)  评论(2编辑  收藏  举报