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

Nate Beers picture Nate Beers · Sep 20, 2018 · Viewed 13.9k times · Source

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

Answer

Bergi picture Bergi · Sep 20, 2018

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';
…