Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,313 changes: 1,026 additions & 287 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions packages/vite-build-time-environment/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.git
.idea
src

.npmignore
tsconfig.json
tsup.config.ts
1 change: 1 addition & 0 deletions packages/vite-build-time-environment/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
todo description
8 changes: 8 additions & 0 deletions packages/vite-build-time-environment/client.d.ts
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;
54 changes: 54 additions & 0 deletions packages/vite-build-time-environment/package.json
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;
8 changes: 8 additions & 0 deletions packages/vite-build-time-environment/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"target": "es2022",
"outDir": "./build",
"rootDir": "./src"
}
}
10 changes: 10 additions & 0 deletions packages/vite-build-time-environment/tsup.config.ts
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
});
7 changes: 7 additions & 0 deletions packages/vite-dynamic-environments/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.git
.idea
src

.npmignore
tsconfig.json
tsup.config.ts
43 changes: 43 additions & 0 deletions packages/vite-dynamic-environments/README.md
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'```)
44 changes: 44 additions & 0 deletions packages/vite-dynamic-environments/README_RU.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
[//]: # (todo: уточнить название по конвенции)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'```)
4 changes: 4 additions & 0 deletions packages/vite-dynamic-environments/__tests__/.env.test
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';
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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');
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне кажется, тут фикстуры нужны.
__fixtures__/.env.test вместо __tests__/.env.test


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');
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__fixtures__/.env.test вместо __tests__/.env.test

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({}));
});
});
23 changes: 23 additions & 0 deletions packages/vite-dynamic-environments/__tests__/getLast.test.ts
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);
});
});
9 changes: 9 additions & 0 deletions packages/vite-dynamic-environments/client.d.ts
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 {};
5 changes: 5 additions & 0 deletions packages/vite-dynamic-environments/jest.config.cjs
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'
};
Loading