"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
When incorporating the milsymbol.js library into your ArcGIS JSAPI project to display military symbols on your map, you may encounter errors like "Uncaught SyntaxError: Cannot use import statement outside a module" or "Uncaught ReferenceError: ms is not defined."
Understanding the Errors
The first error, "Uncaught SyntaxError: Cannot use import statement outside a module," indicates that the import syntax is not supported outside of a module context. To resolve this, you must add type="module" to the script element loading milsymbol.js.
The second error, "Uncaught ReferenceError: ms is not defined," occurs because the ms variable is not defined when using import syntax. This is because import statements resolve to the default export of the module. In milsymbol.js, the default export is { ms }, so you need to import it as such.
Fixing the Errors
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>
import { ms } from 'milsymbol-2.0.0/src/milsymbol.js';
Understanding the Official Documentation
In the official Spatial Illusions documentation, you may notice that the script element does not have type="module." This is because the documentation is targeted towards users who use a bundler like Webpack or Rollup to bundle their code. When using a bundler, the type="module" is not necessary as the bundler will automatically handle the module resolution.
Conclusion
By following the steps above, you can resolve the errors you encountered when importing ECMAScript 6 modules into your ArcGIS JSAPI project. Remember to consider using a bundler if you need to mix and match between require and import syntax.
The above is the detailed content of Why Am I Getting 'Uncaught SyntaxError: Cannot use import statement outside a module' When Importing milsymbol.js into ArcGIS JSAPI?. For more information, please follow other related articles on the PHP Chinese website!