Reputation: 1345
I'm writing a simple circular collision detection program in javascript and the project structure of the files is like so:
basically there's no problem in code and the html runs fine in a browser, all the scripts are loaded and executed well as I've made this hierarchy in the index.html
:
<script src="scripts/javascript/GLOBALS.js"></script>
<script src="scripts/javascript/utils.js"></script>
<script src="scripts/javascript/setup.js"></script>
<script src="scripts/javascript/Ball.js"></script>
<script src="scripts/javascript/main.js"></script>
but, when I access a function defined in utils.js in setup.js then, it says `function is undefined with a very disturbing red underline. How can I let vscode know of all the functions and variables up the hierarchy?
Upvotes: 2
Views: 743
Reputation: 901
As others have mentioned the correct way to do this is with modules. Modules have been part of JavaScript standard since ES2015.
If you still don't want to use modules for whatever reason, it would require two steps to do this:
index.js
:
/* global Test */
/// <reference path="Test.js" />
const t = new Test();
and in Test.js
:
class Test {}
The triple slash ///
indicates to VSCode where these references can be found (for its intellisense) and the /* global ... */
declarations tell eslint that there are globally defined variables that are being accessed.
Modules are definitely superior, but this should work as well.
Upvotes: 1
Reputation: 5004
In your package.json file you can set the key value pair "type": "module".
Then you can use ECMAScript Modules. This means you can use the export keyword to export functions, variables or constants from one file and use import to import them in another file.
export const name = 'square';
export function draw(ctx, length, x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, length, length);
return {
length: length,
x: x,
y: y,
color: color
};
}
Or at the end of the file export { name, draw, reportArea, reportPerimeter };
import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
Then you can use them in the file like this
let myCanvas = create('myCanvas', document.body, 480, 320);
let reportList = createReportList(myCanvas.id);
let square1 = draw(myCanvas.ctx, 50, 50, 100, 'blue');
reportArea(square1.length, reportList);
reportPerimeter(square1.length, reportList);
Here you can read more https://developer.mozilla.org/de/docs/Web/JavaScript/Guide/Modules
Upvotes: 1