Access a Global Variable in Main File with an Imported Javascript Function ES6

19.5k Views Asked by At

I am using Vue.js but with simply JS files and not vue files and I am importing a component into my main app.js like so:

import autoPosts from './components/autoPosts.js';

It imports it just fine, but I am trying to access these globals. Before people destroy me for using global variables, can you just tell me if this is possible.

const apiRoot    = location.origin + '/wp-json/wp/v2/';
const acfApiRoot = location.origin + '/wp-json/acf/v3/';

import autoPosts from './components/autoPosts.js';

It doesn't read apiRoot or acfApiRoot within that component whether I include it before or after the variables.

The only way it works is if I declare the variables inside my component file autoPosts.js

3

There are 3 best solutions below

5
Bergi On BEST ANSWER

Just because app.js is the main module doesn't mean that variables declared in it become global. But you should not use global variables anyway. Instead, create another module

// config.js
export const apiRoot    = location.origin + '/wp-json/wp/v2/';
export const acfApiRoot = location.origin + '/wp-json/acf/v3/';

that you can import where you need the constants:

// components/autoPosts.js
import { apiRoot, acfApiRoot } from '/config.js';
…
1
RyanA91 On

Can it not use window?

window.apiRoot = location.origin + '/wp-json/wp/v2/';
1
Georgios Dimitriadis On

just using

const apiRoot = 'whatever';

doesn't make it a global variable and is not accesible since it isn't exported.

To use a global variable, add it to window;

window.apiRoot = 'whatever';

and it will be accessible from any other classes with simple the variable name

console.log(apiRoot); // outputs 'whatever'