lxs24sxl / vite-plugin-html-env

A vite plugin for rewriting html
82 stars 10 forks source link

Can i also use conditional logic? #11

Open wouter-muller opened 2 years ago

wouter-muller commented 2 years ago

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 commented 2 years ago

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?

lxs24sxl commented 2 years ago

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

wouter-muller commented 2 years ago

@lxs24sxl That's awesome!

lxs24sxl commented 2 years ago

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
})