714

I'm using ArcGIS JSAPI 4.12 and wish to use Spatial Illusions to draw military symbols on a map.

When I add milsymbol.js to the script, the console returns error

Uncaught SyntaxError: Cannot use import statement outside a module`

so I add type="module" to the script, and then it returns

Uncaught ReferenceError: ms is not defined

Here's my code:

<link rel="stylesheet" href="https://js.arcgis.com/4.12/esri/css/main.css">
<script src="https://js.arcgis.com/4.12/"></script>
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

<script>
    require([
        "esri/Map",
        "esri/views/MapView",
        "esri/layers/MapImageLayer",
        "esri/layers/FeatureLayer"
    ], function (Map, MapView, MapImageLayer, FeatureLayer) {

        var symbol = new ms.Symbol("SFG-UCI----D", { size: 30 }).asCanvas(3);
        var map = new Map({
            basemap: "topo-vector"
        });

        var view = new MapView({
            container: "viewDiv",
            map: map,
            center: [121, 23],
            zoom: 7
        });
    });
</script>

So, whether I add type="module" or not, there are always errors. However, in the official document of Spatial Illusions, there isn't any type="module" in the script. I'm now really confused. How do they manage to get it work without adding the type?

File milsymbol.js

import { ms } from "./ms.js";

import Symbol from "./ms/symbol.js";
ms.Symbol = Symbol;

export { ms };
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Jerry Chen
  • 7,649
  • 4
  • 10
  • 16
  • 8
    I am getting the same error while trying to import a module! Do you get any solution? – Zeeshan Ahmad Khalil Oct 29 '19 at 05:17
  • 2
    I am now using browserify through which i can include any module by using `require()`. Check out this [video](https://youtu.be/CTAa8IcQh1U) – Zeeshan Ahmad Khalil Oct 29 '19 at 06:54
  • 1
    This question is in the top 10 of all [21,642,537 questions](https://stackoverflow.com/questions) on Stack Overflow in terms of [***view rate***](https://data.stackexchange.com/stackoverflow/query/120907/highest-view-rate-questions-non-community-wiki-4) (presumably from search engine hits). It has got about 1800 views per day over its lifetime. – Peter Mortensen Sep 05 '21 at 11:14
  • `npm install node-fetch@2.0` as example, because why TF breaking the API with a 3.0 version. Never break API's of modular components, extend it, **or just do nothing**, thanks. – NVRM Mar 31 '22 at 17:40

28 Answers28

384

I got this error because I forgot the type="module" inside the script tag:

<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>
Manas Khandelwal
  • 3,515
  • 2
  • 10
  • 22
Emmanuel
  • 5,538
  • 2
  • 22
  • 22
297

Update For Node.js / NPM

Add "type": "module" to your package.json file.

{
  // ...
  "type": "module",
  // ...
}

Note: When using modules, if you get ReferenceError: require is not defined, you'll need to use the import syntax instead of require. You can't natively mix and match between them, so you'll need to pick one or use a bundler if you need to use both.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
KyleMit
  • 35,223
  • 60
  • 418
  • 600
172

It looks like the cause of the errors are:

  1. You're currently loading the source file in the src directory instead of the built file in the dist directory (you can see what the intended distributed file is here). This means that you're using the native source code in an unaltered/unbundled state, leading to the following error: Uncaught SyntaxError: Cannot use import statement outside a module. This should be fixed by using the bundled version since the package is using rollup to create a bundle.

  2. The reason you're getting the Uncaught ReferenceError: ms is not defined error is because modules are scoped, and since you're loading the library using native modules, ms is not in the global scope and is therefore not accessible in the following script tag.

It looks like you should be able to load the dist version of this file to have ms defined on the window. Check out this example from the library author to see an example of how this can be done.

Evan Carroll
  • 71,692
  • 44
  • 234
  • 400
Kai
  • 2,221
  • 1
  • 10
  • 7
  • Thank you for your reply, now I know I have the wrong file. I've been looking for the dist version of the file but with no result. Do you know any way to get the dist version? Thanks so much! – Jerry Chen Oct 03 '19 at 05:58
  • It's available for download on npm (https://www.npmjs.com/package/milsymbol). Alternatively, you could build it yourself by cloning the repo and running one of the build scripts. It looks like there's an AMD build script (https://github.com/spatialillusions/milsymbol/blob/master/package.json#L14) that should allow you to `require` the built package directly into your code. – Kai Oct 03 '19 at 06:15
  • 3
    I've downloaded through npm, now I have script : ``, but the console still returns `Uncaught ReferenceError: ms is not defined`. The issue is `ms` is not defined in the `dist/milsymbol.js`, it's defined in `src/milsymbol.js`, but it requires `type="module"` and will cause scope problem. Is there any solution for this. Thanks so much! – Jerry Chen Oct 03 '19 at 06:33
  • 1
    What if thats the actual intention, referencing it from /src. As the author is not planning to expose a property of a class for example.. – Cristian E. Jan 18 '21 at 17:20
53

I resolved my case by replacing "import" by "require".

// import { parse } from 'node-html-parser';
const parse = require('node-html-parser');
Melroy van den Berg
  • 2,368
  • 25
  • 27
nik s
  • 581
  • 4
  • 2
52

I was also facing the same issue until I added the type="module" to the script.

Before it was like this

<script src="../src/main.js"></script>

And after changing it to

<script type="module" src="../src/main.js"></script>

It worked perfectly.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Desire Kaleba
  • 1,118
  • 10
  • 11
  • 28
    Getting CORS on doing this – Shreyan Mehta Jun 20 '20 at 22:18
  • 4
    Meaning you're requesting from another domain. You can fix that by adding ```Access-Control-Allow-Origin: *``` in your headers. You can check the MDN docs about CORS at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests. – Desire Kaleba Jun 21 '20 at 08:26
  • 3
    no i know about cors , the thing is these are my local files – Shreyan Mehta Jun 23 '20 at 19:10
  • 4
    You need to serve your script in an http server, browsers use an http request to load es6 modules, the server needs to respond in the header a CORS allowing your origin. – danilo Jul 08 '20 at 01:22
  • 2
    the simplest way: you can use http-server: https://stackoverflow.com/a/23122981/935330 – danilo Jul 08 '20 at 01:39
  • This answer was already given: https://stackoverflow.com/a/58679392/5468463 – Vega Dec 31 '21 at 10:04
51

I solved this issue by doing the following:

When using ECMAScript 6 modules from the browser, use the .js extension in your files, and in the script tag add type = "module".

When using ECMAScript 6 modules from a Node.js environment, use the extension .mjs in your files and use this command to run the file:

node --experimental-modules filename.mjs

Edit: This was written when node12 was the latest LTS, this does not apply to node 14 LTS.

Sarthak Raval
  • 618
  • 1
  • 5
  • 21
Anurag Phadnis
  • 729
  • 5
  • 12
31

I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module" to both external as well as internal js scripts.

Say, you have a file 'module.js':

var a = 10;
export {a};

You can use it in an external script, in which you do the import, eg.:

<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>

test.js:

import {a} from "./module.js";
alert(a);

You can also use it in an internal script, eg.:

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
    alert(a);
</script>
</body></html>

It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:

import {a} from "module.js";     // this won't work
Fury
  • 4,395
  • 4
  • 43
  • 77
Chong Lip Phang
  • 7,739
  • 5
  • 56
  • 83
22

There are three ways to solve this:

1. The first: In the script, include type=module

    <script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

2. The second: In node.js, into your package.json file

    {
        // ...
        "type": "module",
        // ...
    }

3. The third: replace import by required

Try this

import { parse } from 'node-html-parser';
parse = require('node-html-parser');

Else try this

//import { parse } from 'node-html-parser';
parse = require('node-html-parser');
Loop Assembly
  • 846
  • 7
  • 16
  • 1
    What if all 3 of those don't work. I want a simple api.js file with tons of reusable global functions that I don't want to have to import one at a time ever. ie: – NeoTechni Mar 28 '22 at 15:31
18

For me, it was caused by not referencing a library (specifically typeORM, using the ormconfig.js file, under the entities key) to the src folder, instead of the dist folder...

   "entities": [
      "src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
   ],

instead of

   "entities": [
      "dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
   ],
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
A-S
  • 1,937
  • 1
  • 20
  • 31
13

I got this error in React and fixed it with the following steps:

  1. Go to the project root directory, and open the Package.json file for editing.

  2. Add "type":"module";

  3. Save it and restart the server.

Sarthak Raval
  • 618
  • 1
  • 5
  • 21
11

If you want to use import instead of require() for modules, change or add the value of type to module in package.json file

Example:

package.json file

{
  "name": "appsample",
  "version": "1.0.0",
  "type": "module",
  "description": "Learning Node",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Chikeluba Anusionwu",
  "license": "ISC"
}
import http from 'http';

var host = '127.0.0.1',
    port = 1992,
    server = http.createServer();

server.on('request', (req, res) => {
  res.writeHead(200, {"Content-Type": "text/plain"});
  res.end("I am using type module in package.json file in this application.");
});

server.listen(port, () => console.log(
    'Listening to server ${port}. Connection has been established.'));
zwessels
  • 569
  • 1
  • 9
  • 24
8

Add "type": "module", to your package.json file.

And restart your application:

npm start

Then your problem is solved.

Zaartha
  • 1,096
  • 9
  • 24
7

I'm coding on vanilla JavaScript. If you're doing same, simply add a type="module" to your script tag.

That is, previous code:

<script src="./index.js"></script>

Updated code:

<script type="module" src="./index.js"></script>`
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Alalade Samuel
  • 447
  • 4
  • 3
6

Why this occurs and more possible causes:

A lot of interfaces still do not understand ES6 JavaScript syntax/features. Hence there is need for ES6 to be compiled to ES5 whenever it is used in any file or project.

The possible reasons for the SyntaxError: Cannot use import statement outside a module error is you are trying to run the file independently. You are yet to install and set up an ES6 compiler such as Babel or the path of the file in your runscript is wrong/not the compiled file.

If you will want to continue without a compiler, the best possible solution is to use ES5 syntax, which in your case would be var ms = require(./ms.js);. This can later be updated as appropriate or better still set up your compiler and ensure your file/project is compiled before running and also ensure your run script is running the compiled file usually named dist, build or whatever you named it and the path to the compiled file in your runscript is correct.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Elizabeth
  • 126
  • 2
  • 9
6

For me this helped:

  1. In the .ts file I used: import prompts from "prompts";
  2. And used "module": "commonjs" in file tsconfig.json
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Goaul
  • 161
  • 4
  • 8
3

The error is triggered because the file you're linking to in your HTML file is the unbundled version of the file. To get the full bundled version you'll have to install it with npm:

npm install --save milsymbol

This downloads the full package to your node_modules folder.

You can then access the standalone minified JavaScript file at node_modules/milsymbol/dist/milsymbol.js

You can do this in any directory, and then just copy the below file to your /src directory.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
rootr
  • 382
  • 1
  • 9
  • 3
    `--save`'s been default since `npm 5` & `node 8` (2017): https://stackoverflow.com/q/36022926/1821548, https://nodejs.dev/npm-dependencies-and-devdependencies, https://github.com/benmosher/eslint-plugin-import/issues/884, https://auth0.com/blog/whats-new-in-node8-and-npm5/ – Det Nov 08 '19 at 21:30
3

Use this code. It worked well for me:

Add this script tag to file index.html:

<script type="module">
    import { ms } from "./ms.js";
    import Symbol from "./ms/symbol.js";
</script>
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
HamidReza
  • 1,410
  • 18
  • 15
2

In my case, I updated

"lib": [
      "es2020",
      "dom"
    ]

with

"lib": [
  "es2016",
  "dom"
]

in my tsconfig.json file.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ISS
  • 406
  • 5
  • 23
  • 1
    Thank you, your comment lead me to install: @babel/preset-env, and with that npm install, I am able to use the import statement. – Thuy Aug 26 '21 at 01:31
  • @Thuy nice. I am glad you sorted that out – ISS Aug 26 '21 at 06:56
2

I ran into this error while trying to use import Express.js.

Instead of   import express from 'express';

I used   const express = require('express');

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Alalade Samuel
  • 447
  • 4
  • 3
2

I have faced the same error by EXPO.

Mainly the solution is that to add "type": "module", in the package.json file.

my files, you can find two package.json

Code Image

However, you have to check that which is your correct package.json.

In my case, there are two package.json files, then you should add that to the server file.

To identify which is correct package.json, find "scripts": { "test": "echo \"Error: no test specified\" && exit 1" },

Below ↑ this line, add "type": "module",

K Lee
  • 383
  • 2
  • 13
1

I just added "type": "module" to my Package.json file and it worked for me.

1

I had to import some data from an external file (js file), to my script.js present in my html file.

data.js

const data = {a: 1, b: 2}

By adding type=module I got cors error.

I found out that I can import data.js into my script.js just by including data.js inside my html file.

For example, Previously my html file consists of

<script src="assets/script.js"></script>

As I required some data from data.js, I just changed my html file to

<script src="assets/data.js"></script>
<script src="assets/script.js"></script>

i.e include data.js before script.js, giving access to my data variable inside script.js

gg-dev-05
  • 189
  • 5
  • 10
  • Could you show how you use `data.js` inside `script.js`? The `script.js` contains no import statements? – parsecer Mar 02 '22 at 14:46
  • @parsecer, Yes there are no import statements inside `script.js` file. For example. `data.js` can have `const data_js_variable = 1` and we can use this variable inside `script.js` without the need of any import statements. We just have to include the js files in order inside our html file like``` ``` – gg-dev-05 May 06 '22 at 13:40
0

It's because you haven't exported. The .ts file requires an export class format, whereas in a .js file we would use the exports function.

So, we have to use var_name = require("<pathfile>") to use those file functions.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
  • Hello... Inspect // Watch ... Your answer is poorly elaborated. It is useful to insert an effective response, with codes and references. Concluding a practical and efficient solution. This platform is not just any forum. We are the largest help and support center for other programmers and developers in the world. Review the terms of the community and learn how to post; – Paulo Boaventura Mar 24 '21 at 19:35
0

Well, in my case, I didn't want to update my package.json file and change the file type to mjs.

So I was looking around and found out that changing the module in file tsconfig.json affected the result. My ts.config file was:

{
  "compilerOptions": {
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2020",
    ],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "."
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*.ts"
  ]
}

Like this and changing the module from "module": "es2020" to "module" : "commonjs" solved my issue.

I was using MikroORM and thought maybe it doesn't support any module above CommonJS.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
skele
  • 55
  • 7
0

None of the provided answers worked for me, but I found a different solution from: How to enable ECMAScript 6 imports in Node.js

Install ESM:

npm install --save esm

Run with ESM:

node -r esm server.js
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Maya McKela
  • 136
  • 2
  • 5
-3

In node JS when we use import statement instead of require it gives this type of error ex. Use const express = require('express');

Instead of import express from 'express';

Ganesh Udmale
  • 167
  • 3
  • 8
-4

Just add .pack between the name and the extension in the <script> tag in src.

I.e.:

<script src="name.pack.js">
    // Code here
</script>
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
-6

This error occurs when it fails in Babel transpile.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
somil007
  • 11
  • 1
  • 2
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30304177) – Mario Petrovic Nov 10 '21 at 15:14
  • 2
    This issue has nothing to do with bable transpile – Jamal Kaksouri Dec 18 '21 at 18:14