12

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

Nate Beers
  • 1,355
  • 2
  • 13
  • 22

3 Answers3

15

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';
…
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • that's exactly what I should be doing. Had no idea this could be done. Need to brush up on newer javascript for sure – Nate Beers Sep 20 '18 at 14:35
  • I would use the wildcard importer here (`import * as config from './config.js'`). Then you can reference your variables as `config.apiRoot` which is more easily understandable :) – Fabian von Ellerts Mar 19 '19 at 17:14
  • 1
    @FabianvonEllerts Sure, which import style is considered simpler is a subjective choice. – Bergi Mar 19 '19 at 17:21
  • @Bergi Do you know if the code in the imported file will be reevaluated every time it is imported? I'm searching for a way to only run basic functions (like 'isMobile') once and only reference them later. Or maybe the function is cached anyway and the performance increase isn't worth it... – Fabian von Ellerts Mar 19 '19 at 17:37
  • 1
    @FabianvonEllerts Every module is instantiated and evaluated only once. – Bergi Mar 19 '19 at 17:40
6

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'
  • 1
    `window` is only available in browser scripts, but not in nodejs (or other server-side) applications. – Philipp Feb 03 '22 at 23:26
2

Can it not use window?

window.apiRoot = location.origin + '/wp-json/wp/v2/';
RyanA91
  • 913
  • 7
  • 9
  • @NateBeers only when the variable is accessed after the module loaded, not during the execution of the `autoPosts` module – Bergi Sep 20 '18 at 14:26