Skip to content

Commit

Permalink
feat: Create a plugin that allows to easily expose environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
ElMassimo committed Apr 26, 2021
1 parent 7cd248f commit f199b99
Show file tree
Hide file tree
Showing 27 changed files with 7,672 additions and 0 deletions.
56 changes: 56 additions & 0 deletions .github/workflows/build.yml
@@ -0,0 +1,56 @@
name: build

on: [push]

jobs:
build:
name: Test Plugins

strategy:
matrix:
os: [ubuntu-latest]
node: [12.x, 14.x]

runs-on: ${{ matrix.os }}

steps:
- uses: actions/checkout@v2

- name: Use Node.js ${{ matrix.node }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node }}

- uses: pnpm/action-setup@v1.2.1
with:
version: 5.13.6
run_install: |
- recursive: false
- name: Build
run: pnpm build

- name: Test
run: pnpm test

lint:
name: Lint Plugins

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- name: Use Node.js
uses: actions/setup-node@v1
with:
node-version: 14.x

- uses: pnpm/action-setup@v1.2.1
with:
version: 5.13.6
run_install: |
- recursive: false
- name: Lint
run: pnpm lint
46 changes: 46 additions & 0 deletions .gitignore
@@ -0,0 +1,46 @@
/.bundle
pkg
log
tmp
node_modules
.byebug_history
yarn-debug.log*
yarn-error.log*
.yarn-integrity
gemfiles/*.lock
.DS_Store

# Vite on Rails
/public/vite
/public/vite-dev
/public/vite-test
test/test_app/public/vite-production
node_modules
*.local
.DS_Store

# Vitepress
dist
examples_dist
node_modules
coverage
.nyc_output
.rpt2_cache
.env
local.log
.DS_Store
e2e/reports
e2e/screenshots
__build__
playground_dist
yarn-error.log
temp
markdown
explorations
selenium-server.log

# Algolia
.algolia.env

# Plugin Tests
.port
1 change: 1 addition & 0 deletions .husky/.gitignore
@@ -0,0 +1 @@
_
4 changes: 4 additions & 0 deletions .husky/pre-commit
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
Empty file added CHANGELOG.md
Empty file.
38 changes: 38 additions & 0 deletions CONTRIBUTING.md
@@ -0,0 +1,38 @@
# How to contribute

## Reporting issues

If you think you've spotted a problem with this module, feel free to open up a
[new issue](https://github.com/ElMassimo/vite-plugin-environment/issues/new). There are a couple
of things you should check before doing so:

- Do you have the latest version of the plugin? If not, does updating to the latest
version fix your issue?
- Has somebody else [already reported](https://github.com/ElMassimo/vite-plugin-environment/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen) your issue? Feel free to comment or check-in on an existing issue that matches your own.
- Is your problem definitely to do with this module? For anything else, check the Vite.js repo instead.

## Fixing issues

If you've identified a fix to a new or existing issue, we welcome contributions!

- [Fork](https://help.github.com/articles/fork-a-repo) the [repo on github](https://github.com/ElMassimo/vite-plugin-environment)
- Make your changes locally
- Ensure the changes pass tests (`npm run test`)
- Commit and push your changes
- [Make a pull request](https://help.github.com/articles/using-pull-requests)
- Ensure CI passes (and if it fails, attempt to address the cause)

## Adding features

If you think you have
a useful addition that doesn’t take long to create a pull request for, feel free
to go ahead and make it and strike up a discussion. With any non-trivial amount
of work, the best thing to do is [create an issue](https://github.com/ElMassimo/vite-plugin-environment/issues/new)
in which to discuss the feature, for the following reasons:

- We might have already planned to work on your suggested feature.
- We might disagree about whether the addition is worthwhile or not.
- We might agree that the addition is worthwhile but disagree with the implementation.

Use your best judgement. What we want to avoid here is anybody feeling like they’ve
wasted their time!
21 changes: 21 additions & 0 deletions LICENSE.txt
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2021 Maximo Mussini

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
113 changes: 113 additions & 0 deletions README.md
@@ -0,0 +1,113 @@
<h2 align='center'><samp>vite-plugin-environment</samp></h2>

<p align='center'>Expose environment variables to your client code in <samp>Vite.js</samp></p>

<p align='center'>
<a href='https://www.npmjs.com/package/vite-plugin-environment'>
<img src='https://img.shields.io/npm/v/vite-plugin-environment?color=222&style=flat-square'>
</a>
<a href='https://github.com/ElMassimo/vite-plugin-environment/blob/main/LICENSE.txt'>
<img src='https://img.shields.io/badge/license-MIT-blue.svg'>
</a>
</p>

<br>

[plugin]: https://github.com/ElMassimo/vite-plugin-environment
[migration]: https://vite-ruby.netlify.app/guide/migration.html#migrating-to-vite
[vite.js]: http://vitejs.dev/
[EnvironmentPlugin]: https://webpack.js.org/plugins/environment-plugin/
[define]: https://vitejs.dev/config/#define
[Vite Ruby]: https://vite-ruby.netlify.app/config/#source-maps-%F0%9F%97%BA
[meta env]: https://vitejs.dev/guide/env-and-mode.html#env-files

## Why? 🤔

Although [Vite.js] provides its [own mechanism][meta env] for exposing environment variables through [`import.meta.env`][meta env], sometimes it's not possible or desirable to prefix variables with `VITE_`.

This plugin is a shorthand for exposing environment variables by configuring <kbd>[define]</kbd>.

It provides the same functionality as webpack's <kbd>[EnvironmentPlugin]</kbd>, but for Vite.js.

## Installation 💿

Install the package as a development dependency:

```bash
npm i -D vite-plugin-environment # yarn add -D vite-plugin-environment
```

## Usage 🚀

You can provide a list of environment variable names to expose to your client code:

```js
import { defineConfig } from 'vite'
import EnvironmentPlugin from 'vite-plugin-environment'

export default defineConfig({
plugins: [
EnvironmentPlugin(['API_KEY', 'DEBUG']),
],
})
```

And then use them as:

```js
const apiKey = process.env.API_KEY
```

This is equivalent to [manually configuring][define]:

```js
import { defineConfig } from 'vite'

export default defineConfig({
define: {
'process.env.API_KEY': JSON.stringify(process.env.API_KEY),
'process.env.DEBUG': JSON.stringify(process.env.DEBUG),
}
})
```

except it will also use any variables provided by your `.env` files, and will
__fail__ if any of the specified variables is _not defined_.

### Usage with default values

You may instead provide an object which maps keys to their default values.

The default value for a key is only used if the variable is not defined.

```js
EnvironmentPlugin({
// Uses 'development' if the NODE_ENV environment variable is not defined.
NODE_ENV: 'development',

// Have in mind that variables coming from process.env are always strings.
DEBUG: 'false',

// Required: will fail if the API_KEY environment variable is not provided.
API_KEY: undefined,

// Optional: will not fail if the APP_VERSION environment variable is missing.
APP_VERSION: null,
}),
```

Use `null` for optional variables, or `undefined` for variables that __must__ be provided.

### Using only `process.env`

By default the plugin will load `.env` files using the same [strategy][meta env] as Vite.js.

If you want to ignore `.env` files and only use values in `process.env`, you can opt out:

```js
EnvironmentPlugin(['API_KEY'], { loadEnvFiles: false }),
```

## License

This library is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
15 changes: 15 additions & 0 deletions jest.config.ts
@@ -0,0 +1,15 @@
import type { Config } from '@jest/types'

const config: Config.InitialOptions = {
preset: 'ts-jest',
testMatch: ['**/*.test.[jt]s?(x)'],
testTimeout: process.env.CI ? 30000 : 10000,
watchPathIgnorePatterns: ['<rootDir>/temp'],
globals: {
'ts-jest': {
tsconfig: './test/tsconfig.json',
},
},
}

export default config
67 changes: 67 additions & 0 deletions package.json
@@ -0,0 +1,67 @@
{
"name": "vite-plugin-environment",
"version": "1.0.2",
"description": "Easily expose environment variables in Vite.js",
"keywords": [
"env",
"environment",
"variables",
"vite",
"vite-plugin",
"vitejs"
],
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"lint": "eslint .",
"test": "jest",
"dev": "npm run build -- --watch",
"build": "tsup src/index.ts --dts --format cjs,esm",
"clean": "rm -rf ./dist",
"release": "node scripts/release",
"postinstall": "husky install",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"prepublishOnly": "pinst --disable && npm run build",
"postpublish": "PACKAGE_VERSION=$(cat package.json | grep \\\"version\\\" | head -1 | awk -F: '{ print $2 }' | sed 's/[\",]//g' | tr -d '[[:space:]]') && git tag v$PACKAGE_VERSION && git push --tags && pinst --enable"
},
"repository": {
"type": "git",
"url": "https://github.com/ElMassimo/vite-plugin-environment"
},
"homepage": "https://github.com/ElMassimo/vite-plugin-environment",
"bugs": "https://github.com/ElMassimo/vite-plugin-environment/issues",
"author": "Máximo Mussini <maximomussini@gmail.com>",
"license": "MIT",
"devDependencies": {
"@mussi/eslint-config": "^0.5",
"@types/debug": "^4.1.5",
"@types/jest": "^26.0.22",
"@typescript-eslint/eslint-plugin": "^4.12.0",
"conventional-changelog-cli": "^2.1.1",
"eslint": "^7.17.0",
"eslint-plugin-jest": "^24.3.5",
"fast-glob": "^3.2.5",
"husky": "^5.1.3",
"jest": "^26.6.3",
"lint-staged": "^10.5.4",
"pinst": "^2.1.6",
"rollup": "^2.36.1",
"ts-jest": "^26.5.5",
"ts-node": "^9.1.1",
"tsup": "^3.11.0",
"typescript": "^4.1.3",
"vite": "^2.2.0"
},
"peerDependencies": {
"vite": "^2.0"
},
"lint-staged": {
"*.{js,ts}": [
"eslint --fix"
]
}
}

0 comments on commit f199b99

Please sign in to comment.