@import-meta-env/unplugin
This plugin helps us inject environment variables into the import.meta.env
object after building the application instead of statically replacing it during production.
This project use SemVer for versioning. For the versions available, see the tags on this repository.
Motivation
Environment variables should be easy to change between deployments without rebuilding the application or even changing any code, so we should set environment variables on the system instead of checking them into a repository with .env
files.
During production, this plugin generates chunks with placeholders, which allow us to statically replace environment variables after building the application (don't worry, we provide an executable for this, you don't need to write them yourself) .
🚀 Quick Start
Install and register the plugin:
$ npm i dotenv @import-meta-env/unplugin @import-meta-env/cli
Vite
import ImportMetaEnvPlugin from "./@import-meta-env/unplugin";
export default {
plugins: [
ImportMetaEnvPlugin.vite({
}),
],
};
Rollup
import ImportMetaEnvPlugin from "./@import-meta-env/unplugin";
export default {
plugins: [
ImportMetaEnvPlugin.rollup({
}),
],
};
Webpack
module.exports = {
plugins: [
require("./@import-meta-env/unplugin").webpack({
}),
],
};
Esbuild
import { build } from "esbuild";
build({
plugins: [
require("./@import-meta-env/unplugin").esbuild({
}),
],
});
Create a .env.example
file in the root of your project:
S3_BUCKET=
Add .env
file to .gitignore, and create a .env
file in the project's root directory:
(⚠ This step is completely optional, you should set environment variables directly on your system if you can.)
S3_BUCKET="YOURS3BUCKET"
SECRET_KEY="YOURSECRETKEYGOESHERE"
import.meta.env
now has the keys and values you defined on your system:
console.log(import.meta.env.S3_BUCKET);
console.log(import.meta.env["S3_BUCKET"]);
console.log(import.meta.env.SECRET_KEY);
Finally, before serving your application, remember to execute import-meta-env
binary to inject environment variables.
Adjust the preview script in your package.json:
{
"scripts": {
"preview": "import-meta-env && vite preview",
"preview": "cross-env S3_BUCKET=YOURS3BUCKET import-meta-env && vite preview"
}
}
See also:
- examples
- @import-meta-env/babel - Provide an approximation of this plugin's specific transformations when running the code in other environments, for example, running tests with a NodeJS based test runner.
- @import-meta-env/cli - A binary package is used to inject environment variables into those placeholders.
📖 API
Please see types.ts
📝 License
This project is licensed under the MIT License - see the LICENSE file for details