Hi sorry if this is a stupid question but I cant find the answer anywhere.
I have a js file in which I draw on canvases and I have just removed a function from it as I would like to use it in another js file I have. I have then imported the getPosition function into the drawBalls.js file as so:
import {getPosition} from "../Useful_Scripts/divPosition.js";
And that seems to work alright (as in it gives me no errors). However, right underneath that I have a function draw which starts off like this:
function draw(canvas){
const maxRadius = 10;
const minRadius = 5;
etc;
Which is no longer works given the error ''draw' is declared but its value is never read.'. It does work though if I remove the import code and paste the getPosition function into drawBalls.js and remove type="module" from the script tag.
I have this in my html file where I try to draw on my canvas:
<script type="module" src="../Scripts/Project_1/drawBalls.js"></script>
<script>
window.addEventListener('load', (event) => {
draw(canvas1);
});
</script>
Can someone please explain as to why it no longer works as soon as the file is turned into a module?
Update I have changed my html file to
<script type="module" >
import {draw} from "../Scripts/Project_1/drawBalls.js"
window.addEventListener('load', (event) => {
draw(canvas1);
});
This works!
CodePudding user response:
The default scope of a module is that module and not the global scope.
The draw
method only exists inside that module.
Either:
- Put the
addEventListener
code insidedrawBalls.js
export
thedraw
function and thenimport
it into your other script instead of loadingdrawBall.js
with a<script>
element.
You can also explicitly assign draw
to be a property of window
, but that is a dirty hack and I do not recommend it.
CodePudding user response:
You include your drawBalls.js as a module, but you don't export the draw function from your module – derpirscher
You're using the script as a module. Pretend you're making an NPMjs package, and you build index.js. How would you require that module and use it?
Before requiring your package, in index.js you'll need to export it to import / include it.
It's very basic syntax with module.exports
:
drawBalls.js
module.exports = draw;
EDIT: The above code is for CommonJS modules. Use export
instead (just like you would import
):
export draw;