如何解决router.js中‘Unexpected token import’的ESLint解析报错?
Let's work through this issue step by step—dynamic imports (() => import(...)) can trip up ESLint even with babel-eslint configured, so here are the most likely fixes:
1. Verify Required Dependencies Are Installed
First, make sure you have all the necessary packages installed. If you're using babel-eslint, you need both it and @babel/core in your dev dependencies:
npm install --save-dev babel-eslint @babel/core # or with yarn yarn add --dev babel-eslint @babel/core
Note: If you're using ESLint v8 or newer, babel-eslint is deprecated—you should use @babel/eslint-parser instead. Adjust the install command accordingly:
npm install --save-dev @babel/eslint-parser @babel/core
And update your parser in eslintConfig to "@babel/eslint-parser".
2. Set the Correct ECMAScript Version
ESLint needs to know it should handle ES2020+ syntax (since dynamic imports are part of ES2020). Add ecmaVersion to your parserOptions:
"parserOptions": { "parser": "babel-eslint", // or "@babel/eslint-parser" for ESLint v8+ "ecmaVersion": 2020, // or "latest" to cover all modern syntax "sourceType": "module" }
3. Enable Babel's Dynamic Import Syntax Plugin
Dynamic imports require a Babel plugin to be parsed correctly. Install @babel/plugin-syntax-dynamic-import:
npm install --save-dev @babel/plugin-syntax-dynamic-import
Then create or update your Babel config file (.babelrc or babel.config.js) to include the plugin:
{ "plugins": ["@babel/plugin-syntax-dynamic-import"] }
4. Double-Check ESLint Config Scope
Make sure your eslintConfig in package.json is correctly structured and that ESLint is picking it up. Sometimes, if you have a separate .eslintrc file, it might override the package.json config—delete any conflicting .eslintrc files if they exist.
5. Restart Your ESLint Server/Editor
Don't forget to restart your code editor or any running ESLint processes—changes to config files often require a restart to take effect.
Let me know if any of these steps resolve your issue!
内容的提问来源于stack exchange,提问作者user10747770

