Looking to implement a global property in a Vue 3 application as advised here
Unfortunately, the prototype approach doesn't work with TypeScript.
I came across an example that I converted into the following code as config.d.ts
import Vue from 'vue'
import base from '@/config/config.json'
import dev from '@/config/config.dev.json'
import prod from '@/config/config.prod.json'
let config
if (process.env.NODE_ENV === 'production') {
config = Object.freeze(Object.assign(base, prod))
} else {
config = Object.freeze(Object.assign(base, dev))
}
declare module 'vue/types/vue' {
interface Vue {
$config: config
}
}
Trying to load local configuration files with dev or prod scope without checking them into GIT repository.
The main.ts now looks like this...
import Vue from 'vue'
import {createApp} from 'vue'
import App from './App.vue'
import Config from '@/plugins/config.d.ts'
Vue.use(Config)
createApp(App).mount('#app')
The issue:
ERROR in src/main.ts:6:5
TS2339: Property 'use' does not exist on type 'typeof import("d:/Martin/Entwicklung/2020/STA-Electron/node_modules/vue/dist/vue")'.
4 | import Config from '@/plugins/config.d.ts'
5 |
> 6 | Vue.use(Config)
| ^^^
7 | createApp(App).mount('#app')
8 |
My goal is to have a global config
or $config
property that can be accessed in the setup method of Vue 3
export default defineComponent({
name: 'App',
components: {},
setup(props, context) {
const elem = ref(context.$config.prop1)
const doSth = () => {
console.log('Config', context.$config)
}
return {doSth, elem}
},
})
How can I resolve this?
Update
Following danielv's answer, the new plugin looks like this
import {App} from 'vue'
export interface ConfigOptions {
base: any
dev: any
prod: any
}
export default {
install: (app: App, options: ConfigOptions) => {
app.config.globalProperties.$config =
process.env.NODE_ENV === 'production'
? Object.freeze(Object.assign({}, options.base, options.prod))
: Object.freeze(Object.assign({}, options.base, options.dev))
},
}
The update to main.ts has transformed it into this
import {createApp} from 'vue'
import App from '@/App.vue'
import ConfigPlugin from '@/plugins/config'
import base from '@/config/config.json'
import dev from '@/config/config.dev.json'
import prod from '@/config/config.prod.json'
createApp(App).use(ConfigPlugin, {base, dev, prod}).mount('#app')
This straightforward plugin can now be utilized in the template
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<p>{{ $config.prop1 }}</p>
</template>
IntelliJ may complain about unknown variable prop1, but it functions correctly.
I've looked extensively, yet haven't found a way to integrate my $config into the setup method used in the composition api.