如何安装svelte
“Process is not defined”, the compiler just slapped you in the face again. You are tempted to hardcode your environment variables values in your code, then you realize just how much of a bad idea this is!
“未定义过程”,编译器只是再次打了您耳光。 您很容易在代码中对环境变量值进行硬编码,然后您意识到这是一个多么糟糕的主意!
The default configuration of the sveltejs/template starter project doesn’t allow the use of environment variables out-of-the-box, The purpose of this article is to show you how you can change that.
sveltejs / template starter项目的默认配置不允许开箱即用地使用环境变量。本文的目的是向您展示如何进行更改。
Few tweaks in the default configuration will be all that is required, and rollup.js is where all the magic will happen.
只需很少的调整即可完成默认配置,而rollup.js正是所有神奇之处。
Let’s start!
开始吧!
Make sure you already have a svelte project setup. If not, you can create one quickly:
确保您已经有了一个精简的项目设置。 如果没有,您可以快速创建一个:
degit sveltejs/template your-super-secret-project
依存关系 (Dependencies)
First of all, you’ll want to install two dev dependencies. open your terminal and paste the following code:
首先,您将要安装两个dev依赖项。 打开您的终端并粘贴以下代码:
npm i dotenv @rollup/plugin-replace --save-dev#Or If you are using yarnyarn add dotenv @rollup/plugin-replace -D
dotenv will load your environment variables from the .env file in the root directory of your project.
dotenv将从项目根目录中的.env文件加载环境变量。
@rollup/plugin-replace will replace process.env.YOUR_ENV_VARS with their respective values.
@ rollup / plugin-replace会将process.env.YOUR_ENV_VARS替换为其各自的值。
汇总配置 (Rollup Config)
Next, you’ll want to open your rollup config file in the root directory of your project.
接下来,您将要在项目的根目录中打开汇总配置文件。
Import the packages you’ve just installed:
导入刚刚安装的软件包:
import { config } from 'dotenv';
import replace from '@rollup/plugin-replace';
Under Plugins, add the following:
在“插件”下,添加以下内容:
plugins: [
//...
replace({ FOO: 'bar',
process: JSON.stringify({
env: {
isProd: production,
...config().parsed
}
}),
}),
//...
]
To access .env values in your code, just use process.env.YOUR_ENV_VAR.
要访问代码中的.env值,只需使用process.env.YOUR_ENV_VAR。
Done! Make sure to add .env to your .gitignore file.
做完了! 确保将.env添加到您的.gitignore文件中。
Did you enjoy the article? be sure to share with someone who might find it useful.
你喜欢这篇文章吗? 请务必与可能会觉得有用的人分享。
Thanks for taking the time to read!
感谢您抽出宝贵的时间阅读!
翻译自: https://medium.com/weekly-webtips/using-environment-variables-with-svelte-js-3f389e43f131
如何安装svelte