svelte +汇总中的环境变量 [英] Environment variables in svelte + rollup

查看:79
本文介绍了svelte +汇总中的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法来设置环境.IE.如果我可以运行 npm run dev:local npm run dev:staging 会很棒,它们会加载不同的环境文件,这些文件可以在运行时通过 process.env访问.为了理解它是经过编译的,所以我可能不得不以其他方式访问变量.我正在直接从sveltejs/template使用svelte进行汇总.它应该很简单,但我认为没有办法.这很麻烦,但可以与webpack一起使用.有没有简单的方法可以做到这一点?

I'm looking for a straightforward way to set up environments. I.E. It would be great if I could run npm run dev:local and npm run dev:staging which load different environment files which are accessible at runtime via process.env. In understand it's compiled so I may have to access the variables in a different way. I'm using svelte with rollup straight from sveltejs/template. It should be simple but I see no way of doing it. It's cumbersome, but possible to do with webpack. Is there a simple way to do this?

推荐答案

您可以使用 @ rollup/plugin-replace .

类似这样的东西:

rollup.config.js

import replace from '@rollup/plugin-replace'
...

const production = !process.env.ROLLUP_WATCH

export default {
  ...
  plugins: [
    replace({
      'process.env': production ? '"production"' : '"dev"',
    }),
    ...
  ]
}

请注意值的双引号:'"production"'.该插件将按代码中的原样插入字符串,因此,如果要使用字符串,则需要在引号中加上引号.

Note the double quotes of the value: '"production"'. The plugin injects the string as is in the code so, if you want a string, you need quotes in the quotes.

此外,如插件文档中所述,应将其放在插件数组的开头,以进行优化,例如通过跟随其后的其他插件删除死代码.

Also, as mentioned in the plugin's docs, it should be put at the beginning of your plugins array to enable optimizations like shaking out dead code by other plugins that follows it.

这篇关于svelte +汇总中的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆