简体   繁体   English

svelte + rollup 中的环境变量

[英]Environment variables in svelte + rollup

I'm looking for a straightforward way to set up environments.我正在寻找一种设置环境的简单方法。 IE 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 . IE 如果我可以运行npm run dev:localnpm run dev:staging加载不同的环境文件,这些文件可以在运行时通过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.我直接从 sveltejs/template 使用带有汇总的 svelte。 It should be simple but I see no way of doing it.它应该很简单,但我看不出有什么办法。 It's cumbersome, but possible to do with webpack.这很麻烦,但可以使用 webpack。 Is there a simple way to do this?有没有一种简单的方法可以做到这一点?

You can inject build time constants in compiled code with @rollup/plugin-replace .您可以使用@rollup/plugin-replace在编译后的代码中注入构建时间常量。

Something like this:像这样的东西:

rollup.config.js

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

const production = !process.env.ROLLUP_WATCH

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

Note the double quotes of the value: '"production"' .注意值的双引号: '"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.此外,正如插件文档中所提到的,它应该放在插件数组的开头,以启用优化,例如通过它后面的其他插件抖掉死代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM