Search code examples
vue.jsglobal-variablesvuejs3vite

defining global variables with vite development


Now I am using vite build tool for my vue SFC app. I read the documentation of vite with the link below:

vite config link

If I am not wrong, the define option in config could be used for defining global constants. What I want to do is to define for example the name of my App in a variable inside this option and then use it in my Vue components. But unfortunately there is no example of code in the documentation about this option.

I tried this code in my vite.config.js file:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  define: {
      global: {
        appName: "my-custom-name"
      }
  },
  plugins: [vue()]
})

I am not sure that the syntax and code is correct! And also if it is correct I don't know how to call (use) this constant in my vue app components (.vue files). For example I want to use it in template or script part of this component:

<template>
    <div class="bgNow">

    <p class="color1">
{{ use here }}
    </p>

</template>

<script>

    export default {
        data() {
            return {
              name: use here
            };
        },
        
        methods: {
            nameMethod() {
                
                
                console.log(use here);
                
            }

        } // end of method

    } // end of export
</script>

<style scoped></style>

I declared the places that want with "use here" in the code. And also if there is any other way that I could define some global constants and variables in my vite vue app, I very much appreciate your help to tell me about that.


Solution

  • define is a config that tells Vite how to perform a search-and-replace. It can only replace one string for another (objects cannot be used as a replacement).

    For example, to replace all instances of appName with "my-custom-name", use the following config. Note JSON.stringify() is used (per the recommendation in the docs) to ensure the literal string replacement is properly quoted.

    export default defineConfig({
      define: {
        appName: JSON.stringify('my-custom-name')
      }
    })
    

    If App.vue contained:

    <script setup>
    console.log('appName', appName)
    </script>
    

    It would be transformed to:

    <script setup>
    console.log("appName", "my-custom-name")
    </script>
    

    demo