7

I have a main.ts file, I want to declare a variable over there and use it across all the Vue files.

I have a sfc.d.ts with this content:

declare module '*.vue' {
   import Vue from 'vue'
   export default Vue
}

declare var foo: any;

I assigned a value to foo = "1234" in main.ts. How can I use this foo variable in all the Vue files? Or is there any other way, to create global variable and use it across?

6
  • 2
    (window as any).foo = "1234"; or (<any> window).foo = "1234";. Commented Aug 29, 2018 at 16:52
  • Possible duplicate of Declare Typescript global variable as "module" type Commented Aug 29, 2018 at 16:55
  • There may be few more global variable, is it correct to store all in window object? Commented Aug 29, 2018 at 16:55
  • That is the definition of a global variable in the browser - all of them exist as properties on the window object. If you need you're almost certainly doing something wrong, though. Commented Aug 29, 2018 at 16:56
  • yeah correct. i agree. is this the only way or is there any other way? Commented Aug 29, 2018 at 16:59

1 Answer 1

0
declare global {
    const foo: string;
}

but I must say, this is an anti-pattern and bad practice (for production)

Sign up to request clarification or add additional context in comments.

2 Comments

it's not if your use case requires it. this is ok as long as u know what you are doing.
the question is not "if you know what you are doing", it is "if you know what others are doing and if they know what you are doing". JavaScript global scope pollution is one of the most common and know anti-pattern. e.g. tutorialspoint.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.