# Import class other file syntax error

**URL:** https://discourse.processing.org/t/import-class-other-file-syntax-error/45358
**Category:** Beginners
**Created:** [November 19, 2024, 2:42pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358 "2024-11-19T14:42:10Z")
**Posts on this page:** 19
**Page:** 1

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 19, 2024, 2:42pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/1 "2024-11-19T14:42:10Z")

</div>

Im facing this error:

> SyntaxError: import declarations may only appear at top level of a module  
> in Webstorm.

When i have:

```javascript
sketch.js
import Animal from "path to animal.js";

function setup() {
const dog = new Animal("dog");
dog.sayName();
  createCanvas(400, 400);
}

function draw() {
  background(220);
}

```

And **Animal.js**

```auto
class Animal {
   name;
 constructor(name) {
    this.name = name;
  }
  //Print Animal
  sayName() {
    console.log(this.name);
  }
}

export default Animal;

```

Any ideas please ?  
Can someone explain how to import/export modules if its somekind different as JS ?

Thanks

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [November 19, 2024, 5:22pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/2 "2024-11-19T17:22:55Z")

</div>

I must admit I don’t fully understand how to use modules from the Processing IDE but I managed to get this to work

**AnimalDemo.js**

```auto
import Animal from "./animal.js";

function setup() {
    createCanvas(200, 200);
    const dog = new Animal("dog");
    // console.log(dog)
    dog.sayName();
}

function draw() {
    background(220);
}

window.setup = setup;
window.draw = draw;

```

**animal.js**

```auto
class Animal {
    constructor(name) {
        this.name = name;
    }
    //Print Animal
    sayName() {
        console.log(this.name);
    }
}

export default Animal;

```

Both these need to be loaded as modules so in the html file change the ‘type’ to ‘module’

```auto
  <!-- PLEASE NO CHANGES BELOW THIS LINE (UNTIL I SAY SO) -->
  <script language="javascript" type="text/javascript" src="libraries/p5.min.js"></script>
  <script language="javascript" type="module" src="animal.js"></script>
  <script language="javascript" type="module" src="AnimalDemo.js"></script>
  <!-- OK, YOU CAN MAKE CHANGES BELOW THIS LINE AGAIN -->

```

This was based on a reply by @GoToLoop in this [discussion](https://discourse.processing.org/t/correct-way-to-use-es6-modules-and-import-classes/21386/5)

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 19, 2024, 5:31pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/3 "2024-11-19T17:31:22Z")

</div>

> [@quark](#):
>
> Both these need to be loaded as modules…

Only the “main” module file requires to be loaded as `<script type=module>`.  
The other modules are loaded via the `import` keyword.

In this case, “AnimalDemo.js” is the main module JS file, which loads “animal.js” via:  
`import Animal from "./animal.js";`

P.S.: It’s advisable to use the extension “.mjs” in order to let others know it’s not a regular JS file, but a Module JS file (MJS).

---

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [November 19, 2024, 5:50pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/4 "2024-11-19T17:50:00Z")

</div>

@GoToLoop thanks for that answer it worked perfectly in VSC. 👍

The Processing IDE doesn’t seem to able to handle user files with the extension `.mjs` files but your solution still works if you leave the extensions as `.js` 😁

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 19, 2024, 7:25pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/5 "2024-11-19T19:25:11Z")

</div>

> [@quark](#):
>
> The Processing IDE…

I’ve tried p5js’s mode for the PDE twice or thrice and gave up!

Either i use a simple text editor (like [Notepad3](https://rizonesoft.com/downloads/notepad3/) or [Kate](https://kate-editor.org/get-it/)) for small stuff or [VSCode](https://code.visualstudio.com)/[VSCodium](https://vscodium.com) for larger stuff.

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 20, 2024, 11:45am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/6 "2024-11-20T11:45:11Z")

</div>

But if its a class…whats the correcte name of file ???

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 20, 2024, 11:57am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/7 "2024-11-20T11:57:48Z")

</div>

In Webstorm it doesnt work for me… now appears: Se bloqueó la carga de un módulo de “[http://localhost:63342/libraries/classes/Animal.js”](http://localhost:63342/libraries/classes/Animal.js%E2%80%9D) debido a un tipo MIME no permitido (“text/html”)

In index.html i have only:

If theres any dev here, should fix this in a near future…is bad to have this problems to import and export, so common thing, and so standarized…Its weird that p.js works different and lack of documetnation about it…( at least i didnt found any)

Thank for your job and help

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 20, 2024, 12:01pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/8 "2024-11-20T12:01:07Z")

</div>

In your original question, your class Animal is defined inside file " Animal.js".

B/c that class is exported as `export default Animal;`, you can import it inside your file “sketch.js” as:  
`import Animal from "./Animal.js";`  
Assuming both are located in the same folder.

Also, b/c it’s a “default export”, you can use any other name in place of Animal:  
`import Pet from "./Animal.js";`

As I’ve mentioned before, it’s advisable to use the extension “.mjs” for files that should be loaded as a module.

So, I’d rename “Animal.js” to “Animal.mjs” and “sketch.js” to “sketch.mjs”.

This way, it’s clearer they require special loading strategy:  
`import Animal from "./Animal.mjs";`

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 20, 2024, 12:09pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/9 "2024-11-20T12:09:30Z")

</div>

> [@edufissure](#):
>
> In index.html i have only:

Can you post your “index.html” file?

> [@edufissure](#):
>
> It’s weird that p5.js works different and lacks documentation about it…

p5.js itself is a regular .js library file, not a module 1.

Indeed they’ve never yet cared about using ECMA module (.mjs) files in the browser!

But weirdly, they do care about Node.JS’ Common module (.cjs) files, even though p5.js isn’t a backend library, but a frontend 1!

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 20, 2024, 2:10pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/10 "2024-11-20T14:10:14Z")

</div>

sure you can download the project ( dont be afraid is where im doing some tests…its almost empty)…Im teacher of vocational education in Computer Science…and im teaching JS…another thing as Animal is a class…should i use export class Animal ???

Error: Se bloqueó la carga de un módulo de “[http://localhost:63342/libraries/classes/PointCoord.js”](http://localhost:63342/libraries/classes/PointCoord.js%E2%80%9D) debido a un tipo MIME no permitido (“text/html”).

In english: Page blocked because of a disallowed MIME type (“text/html”)

> **[Calculadora.zip](https://drive.google.com/file/d/1J_BBQANpS7U7OEIRlrfx-UCeveXPhDUG/view?usp=sharing)**
>
> Google Drive file.

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 20, 2024, 8:28pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/11 "2024-11-20T20:28:43Z")

</div>

Seems very strange: in the head of the index.html i write:

```auto
    <script src="/src/scriptindex.js"></script>
    <script src="/libraries/p5.min.js"></script>

```

Note the / at the beginning of the path…in this case.working fine…

But in the div of the canvas:

```auto
<div id="sketch-holder">
        <script src="src/sketch.js" type="module"></script>
    </div>

```

Works but

```auto
<div id="sketch-holder">
        <script src="/src/sketch.js" type="module"></script>
    </div>

```

With the / doesn’t work, also i have to write type=“module” in other tutorials don’t appear this type only:

`<script src="sketch.js"></script>`

Also i still think that window.setup = setup and window.draw=draw at the end of sketch.js should no be there…if you export and import a js file, just it, don’t know why window is doing here…

Any dev could fix this ?

Also seem that it has gone the tutorial were you setup your environment, linking html file with sketch.js…by now only appear the p5js web editor…but not any explanation about what to write in html file, and how to link to a sketch.js

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 20, 2024, 11:52pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/12 "2024-11-20T23:52:25Z")

</div>

Your “Calculadora.zip” file had to many things in it.  
I’ve removed most of it and edited the rest.  
Also, I’ve created a GitHub repo for it here:

> **[GitHub - GoToLoop/P5-JS-ECMA-Module-Demo: Shows how to integrate ECMA module files (.mjs) w/...](https://github.com/GoToLoop/P5-JS-ECMA-Module-Demo)**
>
> Shows how to integrate ECMA module files (.mjs) w/ library p5\*js

You can also check it running online on this link:

> **[Calculator del Dr. Einstein](https://gotoloop.github.io/P5-JS-ECMA-Module-Demo/)**
>
> ECMA module files (.mjs) + library p5\*js

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 21, 2024, 9:17am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/13 "2024-11-21T09:17:29Z")

</div>

1 - Your “Calculadora.zip” file had to many things in it.  
I’ve removed most of it and edited the rest.  
Thanks for your effort, i told you, dont be afraid, most things were from HTML Boilerplate project template in Webstorm.

2 - Why async ? Ive never seen this, if i delete async is working fine in my computer

```auto
script async src="src/scriptindex.js"></script>

```

I prefer to use

```auto
 <script defer src="src/libraries/p5.min.js"></script>

```

instead of

```auto
<script defer src="//cdn.JsDelivr.net/npm/p5"></script>

```

I prefer to have it downloaded in the project,also Webstorm pop up a warning if library is not downloaded.  
The defer also is not necessary no ?

4 - You renamed all to .mjs but according to @quark

> The Processing IDE doesn’t seem to able to handle user files with the extension `.mjs` files but your solution still works if you leave the extensions as `.js`

5 - @GoToLoop are you a dev of processing ??

Ive to simplify as much as i can the code to my students (…and me)

Thanks

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 21, 2024, 11:09am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/14 "2024-11-21T11:09:12Z")

</div>

> [@edufissure](#):
>
> 2 - Why async ? I’ve never seen this,

[async](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#async)  
It makes a `<script>` tag to load in parallel while the page is still being processed & immediately run it as soon as its loading is finished.

The reason I’ve used the attribute `async` for “scriptindex.js” is b/c it doesn’t depend on any other file and no other file depends on it.

Actually, I could’ve used `async` for the p5.js loading as well in this particular case, given no p5.js library addon is present which would depend on it.

> [@edufissure](#):
>
> , if i delete `async` it’s working fine in my computer.

Both `async` & `defer` attributes are optional.  
They’re used to lower the total loading time of the page.

> [@edufissure](#):
>
> I prefer to have it downloaded in the project,

I use a CDN link so I don’t need to have a copy of “p5.min.js” library on every single folder locally.

> [@edufissure](#):
>
> also Webstorm pops up a warning if library is not downloaded.

Well, never used that. I had no complaints from my text editor. 😉

> [@edufissure](#):
>
> The `defer` also is not necessary, no?

[defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)

- Like `async` attribute, `defer` also loads a `<script>` in parallel w/ other `async` & `defer` scripts.
- However, it defers its execution until the whole page is parsed & ready.
- That’s the same default behavior as a “type=module” `<script>` btW.
- But as you know by now, it’s totally optional. It’s merely for decreasing page loading time.

> [@edufissure](#):
>
> 4 - You renamed all to “.mjs”

Not all: I’ve kept “scriptindex.js” as “.js”, b/c it’s the only non-module classic script type, besides the p5.js library.

The files “sketch.mjs”, “Animal.mjs” and “point\_coord.mjs” can’t be loaded w/ a regular `<script>` w/o adding the attribute “type=module”.

The reason is b/c they contain the keywords `import` and/or `export`; thus turning them into an ECMA Script Module (ESM) instead:

> **[Explicit ESM in Node.js with .mjs](https://dev.to/bnb/explicit-esm-in-node-js-with-mjs-3ooh)**
>
> A brief explainer on the usage of .mjs and .cjs in Node.js.

Although renaming them to “.mjs” is optional, it’s a good practice of letting others know they aren’t classical non-module JS files, that they have different running behaviors.

Also, runtime servers like NodeJS, Deno, Bun, etc., recognize the “.mjs” extension name and change their import/export behavior accordingly.

The original, and now deprecated, NodeJS module is called CommonJS, and its official extension is “.cjs”:

> **[CommonJS](https://en.wikipedia.org/wiki/CommonJS)**
>
> CommonJS is a project to standardize the module ecosystem for JavaScript outside of web browsers (e.g. on web servers or native desktop applications).
> CommonJS's specification of how modules should work is widely used today for server-side JavaScript with Node.js. It is also used for browser-side JavaScript, but that code must be packaged with a transpiler since browsers don't support CommonJS. The other major module specification in use is the ECMAScript (ES) modules specification (ES6 modules ...

> [@edufissure](#):
>
> 5 - @GoToLoop, are you a dev of Processing??

Nope! Actually it’s very rare to see any Processing devs here in this forum!

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 21, 2024, 11:21am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/15 "2024-11-21T11:21:45Z")

</div>

You are helping me a lot

@GoToLoop

This weekend i had to make some kind of document with your teaching… 😉

1 - p5.js could use defer or async which is better ? as far as i know we dont have here any promise to use await/async…

2 - Do you know any way to contact any dev ?

3 - Seems mjs is more node.js, as you can see im developing in browser environmen…still need or better said is recommended to use .mjs in modules( i understand modules as any .js with import or export in their code)

4 - Do you have any explanation about the / … why in most cases workd fine in p5 but in the loading of sketch.js you have to delete it ? perhaps a bug ?

Thanks… for now 😉

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 21, 2024, 2:59pm UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/16 "2024-11-21T14:59:34Z")

</div>

> [@edufissure](#):
>
> 1 - p5.js could use `defer` or `async`; which is better?

- Both attributes `async` & `defer` load a `<script>` w/o waiting for the page to be parsed.
- The diff. is that `async` runs the script right after it’s finished loading.
- While `defer` postpones its execution until the page is fully parsed.
- If you don’t have other addons which can’t be run before p5.js has run, use `defer` for all of them; otherwise you’re free to use `async` for p5.js instead.

> [@edufissure](#):
>
> As far as I know we don’t have here any Promise to use `await`/`async`…

Those `<script>` tag attributes `async` & `defer` are used inside an HTML file. They’ve got nothing to do w/ JS files and its syntax.

> [@edufissure](#):
>
> 2 - Do you know any way to contact any dev?

All I know is their p5.js repo:

> **[GitHub - processing/p5.js: p5.js is a client-side JS platform that empowers...](https://github.com/processing/p5.js)**
>
> p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —

> [@edufissure](#):
>
> 3 - Seems “.mjs” is more Node.js,

Although it’s true it’s more useful for Node.JS as a way to differentiate a CommonJS module from an ESM 1, “.mjs” is ECMA’s official extension name for a JS script that acts as a ESM module.

> [@edufissure](#):
>
> (I understand modules as any JS with `import` or `export` in their code)

Indeed those 2 keywords make a JS script become an ESM module file.

> [@edufissure](#):
>
> 4 - Do you have any explanation about the `"/"`…

I dunno all the rules regarding the requirement or not to place a `"/"` for a filename path.  
But for HTML files, I don’t start the path w/ `"/"` for local files:

```auto
    <link rel="icon" href="img/p5-sq-reverse32.png">
    <link rel="stylesheet" href="styles/styles.css">

    <script async src="src/scriptindex.js"></script>
    <script type="module" src="src/sketch.mjs"></script>

```

But for remote files, I start w/ a double `"//"`:  
`<script async src="//cdn.JsDelivr.net/npm/p5"></script>`

For the `import` keyword in a JS file, I generally don’t start a path w/ `"/"`, but either `"./"` or `"../"`:

```auto
import Animal from './classes/Animal.mjs';
import { pointCoord } from './functions/point_coord.mjs';

```

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 22, 2024, 8:57am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/17 "2024-11-22T08:57:25Z")

</div>

Another thing:

```auto
<div id="sketch-holder">
        <script src="/src/sketch.js" type="module"></script>
    </div>

```

Which is preferred or any good practices…put the inside the div or html tag in which the sketch is gonna be… or as you do at the head of the HTML file ? pros and cons ?

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [November 22, 2024, 9:15am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/18 "2024-11-22T09:15:49Z")

</div>

- Placing a `<script>` tag inside another tag doesn’t do anything visually!
- For a p5.js sketch, what we actually want is its `<canvas>` element.
- In my “sketch.mjs” version, I call method [**parent()**](https://p5js.org/reference/p5.Element/parent/) over the [p5.Renderer](https://p5js.org/reference/p5/p5.Renderer/) object returned by [**createCanvas()**](https://p5js.org/reference/p5/createCanvas/), passing the `<div id="sketch-holder">`'s _id_ attribute as its string argument:

> <https://github.com/GoToLoop/P5-JS-ECMA-Module-Demo/blob/v1.0.0/src/sketch.mjs#L7-L9>

This way, the p5.js’s `<canvas>` becomes a child tag of that `<div>`.

---

<div class="post-metadata">

### Author: ![edufissure](https://avatars.discourse-cdn.com/v4/letter/e/e56c9b/32.png) [@edufissure](https://discourse.processing.org/u/edufissure)
#### Post date: [November 22, 2024, 10:43am UTC](https://discourse.processing.org/t/import-class-other-file-syntax-error/45358/19 "2024-11-22T10:43:15Z")

</div>

I knew it…😉  
I was asking which way is better…as your comment is more smart and “best practices” put it in the head of the HTML file
