vite-plugin-html-env icon indicating copy to clipboard operation
vite-plugin-html-env copied to clipboard

Can i also use conditional logic?

Open wouter-muller opened this issue 2 years ago • 4 comments

From the README.md i understand you can use this package to add variables that you declare in your .env files, so you can have different files being loaded in dev mode than on production.

Is it also possible to use an if statement for example to only include a script on production? For example something like this:

<% if (process.env.VITE_USE_GOOGLE_ANALYTICS === 'true') { %>
    <script>
        ...
    </script>
<% } %> 

wouter-muller avatar Jun 28 '22 07:06 wouter-muller

I found a ticket that seems related: https://github.com/lxs24sxl/vite-plugin-html-env/issues/9

But it does not answer the question. It merely explains something general about .env files.

So my question remains: can i use conditional logic?

wouter-muller avatar Jun 28 '22 07:06 wouter-muller

I'm already planning to implement this feature. ⛽️

lxs24sxl avatar Jun 29 '22 01:06 lxs24sxl

@lxs24sxl That's awesome!

wouter-muller avatar Jun 29 '22 06:06 wouter-muller

Version 1.2.0 already supports conditional logic.

How to use

    <!-- compiler: true -->
    <!-- Example 1 -->
    <!-- VITE_APP_ENV = dev -->
    <script vite-if="import.meta.env.VITE_APP_ENV === dev">
      console.log('vite-if')
    </script>
    <script vite-else>console.log('vite-else')</script>

    <!-- Example 2 -->
    <script vite-if="<{ VITE_APP_ENV }> !== dev">
      console.log('vite-if')
    </script>
    <script vite-else>
      console.log('vite-else')
    </script>

    <!-- Example 3 -->
    <!-- VITE_APP_NUM_9 = 9 -->
    <script vite-if="import.meta.env.VITE_APP_NUM_9 < 10">
      console.log('9 < 10')
    </script>

If you encounter any problems, you can return to the old mode and give me feedback on the problem by raising an issue.

vite.config.js

VitePluginHtmlEnv({
    compiler: true
    // compiler: false // old
})

lxs24sxl avatar Jul 02 '22 16:07 lxs24sxl