@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({
example: ".env.example.pub",
}),
],
};
Rollup
import ImportMetaEnvPlugin from "./@import-meta-env/unplugin";
export default {
plugins: [
ImportMetaEnvPlugin.rollup({
example: ".env.example.pub",
}),
],
};
Webpack
module.exports = {
plugins: [
require("./@import-meta-env/unplugin").webpack({
example: ".env.example.pub",
}),
],
};
Esbuild
import { build } from "esbuild";
build({
plugins: [
require("./@import-meta-env/unplugin").esbuild({
example: ".env.example.pub",
}),
],
});
Create a .env.example.pub
file in the root of your project:
Warning: the keys defined in this file will be exposed to client side.
You should read server side only environment variables from process.env.*
instead of import.meta.env
(see process.env
example here).
S3_BUCKET=
Set environment variables directly on your system:
$ export S3_BUCKET=YOURS3BUCKET
$ export SECRET_KEY=YOURSECRETKEYGOESHERE
Or add .env
file to .gitignore
, and create a .env
file in the project's root directory:
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, for example:
$ cross-env S3_BUCKET=YOURS3BUCKET import-meta-env && your-serve-script
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