Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 235
Nate Beers Avatar asked Sep 20 '18 14:09

Nate Beers


3 Answers

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';
…
like image 122
Bergi Avatar answered Sep 21 '22 10:09

Bergi


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'
like image 25
Georgios Dimitriadis Avatar answered Sep 22 '22 10:09

Georgios Dimitriadis


Can it not use window?

window.apiRoot = location.origin + '/wp-json/wp/v2/';
like image 30
RyanA91 Avatar answered Sep 22 '22 10:09

RyanA91