I'm doing a javascript course with FCC and use VSCode as my code editor. But to date, all my js code was contained in a single file. Obviously for any meaningful js development I need to create a collection of js files that work as a single unit.
To start exploring this I have a very simple setup of two js files, test-01.js and test-02.js, where test-01.js contains a call to a function which is defined in test-02.js. I first want to do this without any HTML or CSS files. Although that will also be a future requirement.
The first file test-01.js:
//test-01.js
let returnStr = "";
console.log("This is the calling program");
// Now call the function in test-02.js
returnStr = Display(10);
With future project complexity in mind, the second file test-02.js is in a sub-folder from the first file. .\folder-02\test-02.js:
//test-02.js
function Display(param = 0) {
console.log("This is the program called with parameter: ", param);
return "Back from Display";
};
I've unsuccessfully tried importing the function Display() from test-01.js into test-02.js.
I've unsuccessfully tried finding ways to modify files like:
- package.json
- jsconfig.json
- setting.json
- launch.json
I've unsuccessfully tried looking for sample projects on github and elsewhere.
I've unsuccessfully looked for answers in StackOverflow.
All to no avail. This should be a no brainer which should have been described in the vscode documentation but I cannot find it there. By now I have tried so many things that I've probably screwed up my development environment. I hope someone can help me out and point me in the right direction to resolve this.
Many thanks, Thomas.
CodePudding user response:
JavaScript modules are the way to go when importing methods from one .js file and calling them in another .js file. There are many different ways to import and use modules in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
Here is an example for your situation:
First, lets import the main JavaScript file into the html document:
<head>
<!-- type="module" is necessary -->
<script type='module' src="test-01.js" defer></script>
</head>
Next, lets define the 'Display' function in folder-02/test-02.js:
function Display(param = 0) {
console.log("This is the program called with parameter: ", param);
return "Back from Display";
};
export default Display //exporting it to be imported into another js file
Lastly, lets set up test-01.js to import and call the previously defined function:
import Display from './folder-02/test-02.js';
let returnStr = "";
console.log("This is the calling program");
// Now call the function in test-02.js
returnStr = Display(10);