ArcGIS API for JavaScript version 4. X updated and the project startup error: Module parse failed: Unexpected token(… …

 

Question:

When using the project created by vue and webpack, after the ArcGIS API for JavaScript 4. X is upgraded from a lower version to a higher version, problems occur in building the project:

Module parse failed: Unexpected token. You may need an appropriate loader to handle this file type…

error  in ./node_modules/@arcgis/core/views/3d/layers/SceneLayerWorker.js
Module parse failed: Unexpected token (5:673)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| See https://js.arcgis.com/4.24/esri/copyright.txt for details.
| */

Reason:

The new version of the ArcGIS API references the new version of ES2020 optional chaining and nullish coalescing, resulting in parsing errors in the old version of Webpack, so you need to install the appropriate dependencies or upgrade the framework.

Solution:

1. Download Dependencies

Download the corresponding dependencies through the command

npm install -D @babel/core @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-optional-chaining babel-loader

Or add the following codes in package.json, and then initialize npm install

 "@babel/core": "^7.18.9",
 "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",
 "@babel/plugin-proposal-optional-chaining": "^7.18.9",
 "babel-loader": "^8.2.5",

2. Add Configuration

Find the webpack.config.js file and add the following codes below

   module: {
     rules: [
       {
         test: /\.m?js$/,
         exclude: {
           and: [/node_modules/],
           not: [/@arcgis[\\/]core/]
         },
         use: {
           loader: "babel-loader",
           options: {
             plugins: [
               ["@babel/plugin-proposal-nullish-coalescing-operator", { loose: true }],
               ["@babel/plugin-proposal-optional-chaining", { loose: true }]
             ]
           }
         }
       }
     ]
   }

Note: If your project is using the vue1 framework, i.e. you can’t find the webpack.config.js file, then you need to configure the configureWebpack configuration item in the vue.config.js file.

3. Restart the project

Read More: