-
Notifications
You must be signed in to change notification settings - Fork 0
Dynamic environment update #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
b60e8f7
69789ce
5bff647
fa906ea
85ed3b1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| .git | ||
| .idea | ||
| src | ||
|
|
||
| .npmignore | ||
| tsconfig.json | ||
| tsup.config.ts |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| todo description |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| // vite-env.d.ts | ||
| declare const PACKAGE_INFO_FIELD_NAME: string; | ||
| declare const PACKAGE_INFO_FIELD_VERSION: string; | ||
|
|
||
| declare const BUILD_TIME_VARIABLES_VERSION: string; | ||
| declare const BUILD_TIME_VARIABLES_BRANCH: string; | ||
| declare const BUILD_TIME_VARIABLES_COMMIT_HASH: string; | ||
| declare const BUILD_TIME_VARIABLES_RELEASE_NAME: string; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| { | ||
| "name": "@37bytes/vite-build-time-environment", | ||
| "version": "0.0.5", | ||
| "description": "Vite plugin for integrating build-time environment variables like Git branch and commit hash.", | ||
| "license": "MIT", | ||
| "author": "37bytes", | ||
| "repository": "https://github.com/37bytes/public-packages/tree/master/packages/vite-build-time-environment", | ||
| "keywords": [ | ||
| "vite", | ||
| "vite-plugin", | ||
| "build-time", | ||
| "versioning", | ||
| "environment-variables", | ||
| "ci-cd", | ||
| "build-info", | ||
| "build-variables" | ||
| ], | ||
| "files": [ | ||
| "build", | ||
| "client.d.ts", | ||
| "README_RU.md" | ||
| ], | ||
| "type": "module", | ||
| "main": "./build/buildTimeEnvironmentSupport.cjs", | ||
| "types": "./build/buildTimeEnvironmentSupport.d.cts", | ||
| "module": "./build/buildTimeEnvironmentSupport.js", | ||
| "typesVersions": { | ||
| "*": { | ||
| "./build/buildTimeEnvironmentSupport.js": [ | ||
| "./build/buildTimeEnvironmentSupport.d.ts" | ||
| ] | ||
| } | ||
| }, | ||
| "exports": { | ||
| ".": { | ||
| "require": "./build/buildTimeEnvironmentSupport.cjs", | ||
| "import": "./build/buildTimeEnvironmentSupport.js" | ||
| } | ||
| }, | ||
| "scripts": { | ||
| "prepublish": "npm run build", | ||
| "build": "rimraf build && tsup", | ||
| "npm-packlist": "npm run build && npx -y npm-packlist@6.0.1" | ||
| }, | ||
| "devDependencies": { | ||
| "vite": "^4.0.0", | ||
| "rimraf": "5.0.5", | ||
| "tsup": "^8.0.1", | ||
| "typescript": "^5.3.3" | ||
| }, | ||
| "peerDependencies": { | ||
| "vite": "^4.0.0 || ^5.0.0" | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { Plugin } from 'vite'; | ||
|
|
||
| interface Aliases { | ||
| VERSION_FIELD_NAME?: string; | ||
| BRANCH_FIELD_NAME?: string; | ||
| COMMIT_HASH_FIELD_NAME?: string; | ||
| } | ||
|
|
||
| interface Params { | ||
| packageName: string; | ||
| packageVersion: string; | ||
| aliases?: Aliases; | ||
| } | ||
|
|
||
| const buildTimeIdentifiersPlugin = ({ packageName, packageVersion, aliases }: Params): Plugin => { | ||
| if (!packageName) { | ||
| throw new Error('packageName cannot be falsy'); | ||
| } | ||
|
|
||
| if (!packageVersion) { | ||
| throw new Error('packageVersion cannot be falsy'); | ||
| } | ||
|
|
||
| return { | ||
| name: '@37bytes/vite-build-time-environment', | ||
| config(config) { | ||
| const version = process.env[aliases?.VERSION_FIELD_NAME ?? 'VERSION']; | ||
| const branch = process.env[aliases?.BRANCH_FIELD_NAME ?? 'BRANCH'] || '[unknown git branch]'; | ||
| const commitHash = process.env[aliases?.COMMIT_HASH_FIELD_NAME ?? 'COMMIT_HASH'] || '[unknown commit hash]'; | ||
|
|
||
| const releaseName = `${packageName}@${packageVersion}${version ? `+${version}` : ''}`; | ||
|
|
||
| config.define = { | ||
| ...config.define, | ||
|
|
||
| PACKAGE_INFO_FIELD_NAME: JSON.stringify(packageName), | ||
| PACKAGE_INFO_FIELD_VERSION: JSON.stringify(packageVersion), | ||
|
|
||
| BUILD_TIME_VARIABLES_VERSION: JSON.stringify(version || '[unknown build version]'), | ||
| BUILD_TIME_VARIABLES_BRANCH: JSON.stringify(branch), | ||
| BUILD_TIME_VARIABLES_COMMIT_HASH: JSON.stringify(commitHash), | ||
|
|
||
| BUILD_TIME_VARIABLES_RELEASE_NAME: JSON.stringify(releaseName) | ||
| }; | ||
| } | ||
| }; | ||
| }; | ||
|
|
||
| export default buildTimeIdentifiersPlugin; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "extends": "../../tsconfig.json", | ||
| "compilerOptions": { | ||
| "target": "es2022", | ||
| "outDir": "./build", | ||
| "rootDir": "./src" | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import { defineConfig } from 'tsup'; | ||
|
|
||
| export default defineConfig({ | ||
| entry: ['src/buildTimeEnvironmentSupport.ts'], | ||
| outDir: 'build', | ||
| format: ['cjs', 'esm'], | ||
| dts: true, | ||
| sourcemap: false, | ||
| clean: true | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| .git | ||
| .idea | ||
| src | ||
|
|
||
| .npmignore | ||
| tsconfig.json | ||
| tsup.config.ts |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Dynamic Environments Support Rollup Plugin | ||
|
|
||
| This plugin provides support for dynamic environments for projects using Vite. It provides automatic generation of scripts with environment variables during development, making it easy to work with different environment configurations. | ||
|
|
||
| ## Installation | ||
|
|
||
| Install the plugin using npm: | ||
|
|
||
| ```bash | ||
| npm install @37bytes/rollup-plugin-dynamic-environments --save-dev | ||
| ``` | ||
|
|
||
| ## Usage | ||
| ``` | ||
| // vite.config.js | ||
| import dynamicEnvironmentsSupport from '@37bytes/vite-dynamic-environments'; | ||
|
|
||
| export default { | ||
| plugins: [ | ||
| dynamicEnvironmentsSupport({ | ||
| // Plugin parameters (optional, default values are specified) | ||
| scriptLink: '/dynamicEnvironment.js', // Link to connect the script in HTML | ||
| ignorePrefixes: ['VITE_'], // Environment variable prefixes to ignore | ||
| dynamicEnvironmentsDir: 'environments/dynamic', // Directory with dynamic environment files | ||
| outputDir: 'build-env' // Directory for outputting generated scripts | ||
| }) | ||
| ] | ||
| }; | ||
| ``` | ||
|
|
||
| ## Options | ||
|
|
||
| ### scriptLink | ||
| The link where the script with environment variables will be accessed during development (by default: ```'/dynamicEnvironment.js'```) | ||
|
|
||
| ### ignorePrefixes | ||
| Prefixes of environment variables to be ignored during script generation (by default: ```['VITE_']```) | ||
|
|
||
| ### dynamicEnvironmentsDir | ||
| The directory with dynamic environment files (by default: ```'environments/dynamic'```) | ||
|
|
||
| ### outputDir | ||
| Directory for outputting generated scripts (by default: ```'build-env'```) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| [//]: # (todo: уточнить название по конвенции) | ||
| # Vite Dynamic Environments Support Plugin | ||
|
|
||
| Этот плагин предоставляет поддержку динамических окружений для проектов, использующих Vite. Он обеспечивает автоматическую генерацию скриптов с переменными окружения в процессе разработки, что упрощает работу с различными конфигурациями окружения. | ||
|
|
||
| ## Установка | ||
|
|
||
| Установите плагин с помощью npm: | ||
|
|
||
| ```bash | ||
| npm install @37bytes/vite-dynamic-environments --save-dev | ||
| ``` | ||
|
|
||
| ## Использование | ||
| ``` | ||
| // vite.config.js | ||
| import dynamicEnvironmentsSupport from '@37bytes/vite-dynamic-environments'; | ||
|
|
||
| export default { | ||
| plugins: [ | ||
| dynamicEnvironmentsSupport({ | ||
| // Параметры плагина (необязательно, указаны значения по умолчанию) | ||
| scriptLink: '/dynamicEnvironment.js', // Ссылка для подключения скрипта в HTML | ||
| ignorePrefixes: ['VITE_'], // Префиксы переменных окружения, которые нужно игнорировать | ||
| dynamicEnvironmentsDir: 'environments/dynamic', // Директория с файлами динамических окружений | ||
| outputDir: 'build-env' // Директория для вывода сгенерированных скриптов | ||
| }) | ||
| ] | ||
| }; | ||
| ``` | ||
|
|
||
| ## Опции | ||
|
|
||
| ### scriptLink | ||
| Ссылка, по которой будет доступен скрипт с переменными окружения во время разработки (по умолчанию: ```'/dynamicEnvironment.js'```) | ||
|
|
||
| ### ignorePrefixes | ||
| Префиксы переменных окружения, которые нужно игнорировать при генерации скрипта (по умолчанию: ```['VITE_']```) | ||
|
|
||
| ### dynamicEnvironmentsDir | ||
| Директория с файлами динамических окружений (по умолчанию: ```'environments/dynamic'```) | ||
|
|
||
| ### outputDir | ||
| Директория для вывода сгенерированных скриптов (по умолчанию: ```'build-env'```) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| VAR_ONE="var_one" | ||
| VAR_TWO="var_two" | ||
| CONST_ONE="const_one" | ||
| CONST_TWO="const_two" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import { describe, expect, test } from '@jest/globals'; | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. jest? предлагаю перейти на vitest |
||
| import generateScript from '../src/utils/generateScript'; | ||
| import getDynamicEnvironment from '../src/utils/getDynamicEnvironment'; | ||
| import { join } from 'node:path'; | ||
|
|
||
| describe('generate script', () => { | ||
| const path = join(process.cwd(), '__tests__/.env.test'); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Мне кажется, тут фикстуры нужны. |
||
|
|
||
| const env = getDynamicEnvironment({ path }); | ||
| test('returns string', () => { | ||
| expect(typeof generateScript(env)).toBe('string'); | ||
| expect(typeof generateScript({})).toBe('string'); | ||
| }); | ||
| test('returns correct string', () => { | ||
| expect(generateScript(env).trim()).toBe(`window.dynamicEnvironment = Object.freeze(${JSON.stringify(env)});`); | ||
| }); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { describe, expect, test } from '@jest/globals'; | ||
| import getDynamicEnvironment from '../src/utils/getDynamicEnvironment'; | ||
| import { join } from 'node:path'; | ||
|
|
||
| describe('get env variables from file', () => { | ||
| const path = join(process.cwd(), '__tests__/.env.test'); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| test('without ignored prefixes', () => { | ||
| expect(JSON.stringify(getDynamicEnvironment({ path }))).toBe( | ||
| JSON.stringify({ | ||
| VAR_ONE: 'var_one', | ||
| VAR_TWO: 'var_two', | ||
| CONST_ONE: 'const_one', | ||
| CONST_TWO: 'const_two' | ||
| }) | ||
| ); | ||
| }); | ||
| test('with ignored prefix', () => { | ||
| expect(JSON.stringify(getDynamicEnvironment({ path, ignorePrefixes: ['VAR_'] }))).toBe( | ||
| JSON.stringify({ | ||
| CONST_ONE: 'const_one', | ||
| CONST_TWO: 'const_two' | ||
| }) | ||
| ); | ||
| expect(JSON.stringify(getDynamicEnvironment({ path, ignorePrefixes: ['CONST_'] }))).toBe( | ||
| JSON.stringify({ | ||
| VAR_ONE: 'var_one', | ||
| VAR_TWO: 'var_two' | ||
| }) | ||
| ); | ||
| }); | ||
| test('everything ignored', () => { | ||
| expect( | ||
| JSON.stringify( | ||
| getDynamicEnvironment({ | ||
| path, | ||
| ignorePrefixes: ['VAR_', 'CONST_'] | ||
| }) | ||
| ) | ||
| ).toBe(JSON.stringify({})); | ||
| }); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { describe, expect, test } from '@jest/globals'; | ||
| import getLast from '../src/utils/getLast'; | ||
|
|
||
| describe('get last element of array', () => { | ||
| test('a full array', () => { | ||
| const array1 = [1, 2, 3]; | ||
| const array2 = ['1', '2']; | ||
| expect(getLast(array1)).toBe(3); | ||
| expect(getLast(array2)).toBe('2'); | ||
| }); | ||
| test('an array of one', () => { | ||
| const array = [1]; | ||
| expect(getLast(array)).toBe(1); | ||
| }); | ||
| test('an array with elements of various types', () => { | ||
| const array = ['1', { value: 2 }, 3]; | ||
| expect(getLast(array)).toBe(3); | ||
| }); | ||
| test("returns 'undefined' for an empty array", () => { | ||
| const array = []; | ||
| expect(getLast(array)).toBe(undefined); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| // vite-env.d.ts | ||
| declare global { | ||
| interface Window { | ||
| dynamicEnvironment?: Record<string, string>; | ||
| } | ||
| } | ||
|
|
||
| // Это позволяет использовать файл как модуль в системах модулей ES. | ||
| export {}; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| /** @type {import('ts-jest').JestConfigWithTsJest} */ | ||
| module.exports = { | ||
| preset: 'ts-jest', | ||
| testEnvironment: 'node' | ||
| }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
todo?