How do I move some code into another file?

With native JS imports:
test1.js:

const PI = 3.14159;
function print(...args) {
    return console.log(...args);
}
const message = "Hello world!";

export { PI, print, message };

test2.js:

const some_default = true;
export { some_default as default };

main.js

import { print, message, PI } from "./test1.js";
print(message, PI);
import default_value from "./test2.js";
print(default_value);
1 Like

This is the uppest to datest way.

Now I’m getting Cannot use import statement outside a module, this is what made me give up and cry into a pillow last time I tried imports

please help

In your <script> tag, you will have to add type="module" like this:

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

This might not be what you’re thinking but maybe if you are saying you need to import it somewhere else you can copy and paste. (This is probably not what you’re thinking.)

savardo is right, import statements are only allowed in module scripts. All you have to do is specify the script type as module exactly as savardo demonstrated and your script (as well as any others you import) is treated as a module. One thing to note is that modules are automatically always in strict mode and also that scope within a module is actually (kindof) local.

1 Like

I fixed that and forgot to respond whoops

anyway, now the * in import * as ... is throwing a syntax error

You will need to ensure that you typed it out correctly like this:

import * as newModule from "new.js";

If the error is not about the import, please show the full error, thanks!

Uncaught SyntaxError: Unexpected token '*' (at game.js:154:10)

code:

149 |    anchor('center'),
150 |  ]);
151 |
152 |  // helper spawn ui
153 |
154 |  import * as deploy from './_deployMenu.js';
155 |
156 |  // fighting functions
157 |
158 |  function spawnPerson(type, alignment, position) {

The fault may be in one of your codes above the import statement. Check if there is any trailing statements that you forgot to close.