Vite: 是否有可能排除不需要构建的代码元素?

huangapple go评论84阅读模式
英文:

Vite: Is there a possibility to exclude code elements from being built?

问题

我在Vite中正在寻找一种“功能”,可以允许我排除某些代码不被构建。据我记得,在webpack中有一种功能,你可以创建一些注释,如下所示:

###SOMETHING
<code goes here>
###END_SOMETHING

在###SOMETHING和###END_SOMETHING之间的代码在构建过程中不会包含在输出文件中。在Vite中是否有类似的功能,或者是否有其他方法可以执行这样的操作?基本上,这些“标记”之间的代码需要在文件中存在并在vite dev期间工作,但需要在vite build期间被省略。

我已经找到了rollup的设置,但它只包括整个文件。

英文:

I'm looking for a "feature" in Vite which will allow me to exclude some code from being built. As far as I remember in webpack there was a feature when you could create some comments like:

###SOMETHING
<code goes here>
###END_SOMETHING

and this code between ###SOMETHING and ###END_SOMETHING wasn't included in output files during build process. Is there relative feature available in Vite or maybe there is another way to perform such a action? Basically code between these "tags" needs to be in file and working during vite dev, but it needs to be omitted by vite build.

I've found rollup settings but it only includes whole files.

答案1

得分: 0

可以使用 import.meta.env 变量根据执行模式(生产或开发)有条件地评估 JavaScript。

vite dev 默认情况下将以开发模式运行,vite build 将使用生产模式(尽管你可以通过 --mode 进行覆盖)。

请参见 https://vitejs.dev/guide/env-and-mode.html#modes

在你的情况下,你可以使用 import.meta.env.DEV 来查看是否处于开发模式,并有条件地运行一些代码,例如:

if (import.meta.env.DEV) {
    // 代码在 vite dev 模式下运行
}
英文:

It should be possible to conditionally evaluate Javascript according to the execution mode (production or development) by using the import.meta.env variable.

vite dev will run in development mode by default and vite build will use production mode (you can override though through --mode)

See https://vitejs.dev/guide/env-and-mode.html#modes

In your case you can use import.meta.env.DEV to see if you are in development mode and run conditionally some code, e.g.:

if (import.meta.env.DEV) {
    // code runs in vite dev
}

huangapple
  • 本文由 发表于 2023年7月28日 05:36:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定