Helper functions in external file

Hi, I am super new to Three.js … loving it so far, it helps me a lot buidling my little virtiual planetarium.

So, it already works. However, I patch my file together from one of the examples and in its current state everything is in the index.html file.

there is an import map and than a code block with type module and everything happens in the module block.

Now I want to have a bit order in that chaos so i created some helper functions for loading models, creating materials and all that. It works fine.

I also can use some helper functions, that are not referencing THREE from external files or other, non module code blocks.

The Problem is, when I have a helper function that references THREE, like the load_model() function I created, it only works, when I define it inside the “Module” Block… Because if I define it outside, the console gives me an error, that THREE is not defined.

So… how, and where? I Really want to have this functions somewhere else and a clean init() function…

Can someone please point me in the right direction?

Here is my file:

		<script type="importmap">
			{
				"imports": {
					"three": "./build/three.module.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three';

          
.... Here is all the stuff, scene initialisation, THREE referencing Helper Functions... animate() function... everything. And that is Stuffed... too stuffed...
            </script>

Forfeit the chaos of import maps, embrace the love of vite :relieved::pray:

But, regardless of which bundling / resolving solution you’d go with - don’t keep js in your html files, 1990 was 30 years ago :man_bowing: Split JS into separate smaller files, create an index.js, initialise the code there, and only import that index.js in html. Otherwise you’re building a single-file monstrosity that’ll eventually force you to either rewrite the entire thing from scratch or just get you so lost you’ll give up entirely :skull:

1 Like

Don’t worry… I am in a Work in Porghress situation right now.
And one of the reasons for my qeustion was, that I want to avoid a chaotic file structure.
This is why I want helper function in seperate files and not everything in the index.js file.

But I still have not found a solution.

I can use all the helper functions in the module (or index.js) file, but they just dont know what THREE and all the imported stuff are…

Are you importing the THREE namespace and all other necessary dependencies in the helpers file too? You have to import dependencies for each file separately.

I see… so it is like in Python, right?

In every file where I reference certain function, classes etc. that are inherited from THREE and its addons … I have to do that.

I hoped to avoid that, however… lets go for it.

1 Like

Ok, I am breaking my self in to it.
Pretty cool so far, it starts to work or I start to understand it!