This is a bit more of a complicated question than it might at first seem. JavaScript is a language that is used in various environments, and it has a number of module systems.
From the picture you posted it seems like you are trying to implement a standard webpage with JS files for each page. In this case you're not able to directly "import" variables from other files, instead you must load them all into the global context that all files are sharing in the browser.
Essentially you should have some data.js
script that is loaded in the index.html
. Then you can expose some data such as:
var myProducts = ['a', 'b'];
Any script loaded after data.js
will then be able to access myProducts
.
To further elaborate on JS modules: it is typical to use a packager such as webpack which will pre-compile your pages and JS files and allow you to do what your describing ie. importing modules from other files in your code. However, Webpack can be very complicated to setup, especially for a beginner, I would suggest trying out parcel which should get you up and running really quickly.
Once you have a packager setup then you would be able to import modules from other files like so:
# data.js
module.exports = {
myProducts: ['a', 'b'],
};
# page.js
const { myProducts } = require('path/to/data.js');
Note on ES modules:
ParcelJS actually comes with the latest standard (ES modules) pre-configured, so in this setup you would be able to use the following syntax:
# data.js
export const myProducts = ['a', 'b', 'c'];
# page.js
import { myProducts } from 'path/to/data.js';