vite-plugin-global-types 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Quentin Juarez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,170 @@
1
+ # vite-plugin-global-types
2
+
3
+ A Vite plugin that collects your exported types and interfaces into a generated
4
+ `global.d.ts`, so you can use them anywhere without importing them.
5
+
6
+ [![npm version](https://img.shields.io/npm/v/vite-plugin-global-types)](https://www.npmjs.com/package/vite-plugin-global-types)
7
+ [![npm downloads](https://img.shields.io/npm/dm/vite-plugin-global-types)](https://www.npmjs.com/package/vite-plugin-global-types)
8
+ [![license](https://img.shields.io/npm/l/vite-plugin-global-types)](LICENSE)
9
+
10
+ Write `const user: User = ...` without the `import type { User }` line above it,
11
+ and keep the types themselves in normal, explicitly exported modules.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ yarn add -D vite-plugin-global-types
17
+ # or
18
+ npm install -D vite-plugin-global-types
19
+ ```
20
+
21
+ Vite is a peer dependency. Vite 5 through 8 are supported.
22
+
23
+ ## Usage
24
+
25
+ ```ts
26
+ import path from 'path';
27
+ import { defineConfig } from 'vite';
28
+ import vitePluginGlobalTypes from 'vite-plugin-global-types';
29
+
30
+ export default defineConfig({
31
+ plugins: [
32
+ vitePluginGlobalTypes({
33
+ inputs: [path.resolve(__dirname, './src/types/index.ts')],
34
+ outputs: [path.resolve(__dirname, './src/types/global.d.ts')],
35
+ }),
36
+ ],
37
+ });
38
+ ```
39
+
40
+ Given this input:
41
+
42
+ ```ts
43
+ // src/types/index.ts
44
+ export type Foo<T = number> = T;
45
+ export interface Bar {
46
+ baz: string;
47
+ }
48
+ ```
49
+
50
+ the plugin writes:
51
+
52
+ ```text
53
+ // src/types/global.d.ts
54
+ /* eslint-disable */
55
+ /* prettier-ignore */
56
+ // @ts-nocheck
57
+ // noinspection JSUnusedGlobalSymbols
58
+ // Generated by vite-plugin-global-types
59
+ export {}
60
+
61
+ import * as IndexTypes from './index'
62
+
63
+ declare global {
64
+ type Foo<T = number> = IndexTypes.Foo<T>
65
+ interface Bar extends IndexTypes.Bar {}
66
+ }
67
+ ```
68
+
69
+ `Foo` and `Bar` are now global. Commit the generated file or add it to
70
+ `.gitignore`, either works, as long as `tsconfig.json` includes it.
71
+
72
+ ## When it runs
73
+
74
+ The plugin is `apply: 'serve'`, so it only runs in dev. It regenerates on
75
+ `buildStart` and on every file change the dev server sees. That keeps production
76
+ builds untouched: by the time you build, the declaration file is already on disk.
77
+
78
+ ## Options
79
+
80
+ ```ts
81
+ interface GenerateOptions {
82
+ inputs: (string | InputOption)[];
83
+ outputs: string[];
84
+ }
85
+
86
+ interface InputOption {
87
+ path: string;
88
+ filePattern?: RegExp;
89
+ excludeDirs?: string[];
90
+ importAs?: string;
91
+ }
92
+ ```
93
+
94
+ | Option | What it does |
95
+ | ------------- | ------------------------------------------------------------------------------------------- |
96
+ | `inputs` | Files or directories to scan. A plain string is shorthand for `{ path }` |
97
+ | `outputs` | One or more paths to write the same generated declaration to |
98
+ | `filePattern` | Applied when the input is a directory, to pick which files to scan. Defaults to all |
99
+ | `excludeDirs` | Directory names skipped while walking a directory input |
100
+ | `importAs` | Override the generated import specifier, for example `'@/types'` instead of a relative path |
101
+
102
+ Scanning a directory, keeping only `.ts` files and skipping generated output:
103
+
104
+ ```ts
105
+ vitePluginGlobalTypes({
106
+ inputs: [
107
+ {
108
+ path: path.resolve(__dirname, './src/types'),
109
+ filePattern: /\.ts$/,
110
+ excludeDirs: ['__generated__'],
111
+ importAs: '@/types',
112
+ },
113
+ ],
114
+ outputs: [path.resolve(__dirname, './src/types/global.d.ts')],
115
+ });
116
+ ```
117
+
118
+ It throws `No input files found` if nothing matched, rather than writing an empty
119
+ declaration file.
120
+
121
+ ## Limitations
122
+
123
+ Declarations are found by regex on `export type` and `export interface` at the
124
+ start of a line. Types that are not exported, or that are nested inside a
125
+ namespace, are not picked up. This is deliberate: it keeps the plugin fast enough
126
+ to re-run on every file change without holding a TypeScript program in memory.
127
+
128
+ ## Development
129
+
130
+ ```bash
131
+ yarn install
132
+ yarn verify # lint, format check, typecheck, tests, build
133
+ yarn test:watch
134
+ ```
135
+
136
+ There is a runnable example in `example/`:
137
+
138
+ ```bash
139
+ cd example
140
+ yarn install
141
+ yarn dev # writes src/types/global.d.ts on startup
142
+ ```
143
+
144
+ ## Releasing
145
+
146
+ Releases are driven by the commit messages. Push to `main` and CI decides
147
+ whether to publish, from the Conventional Commit prefixes in that push:
148
+
149
+ | Commit | Release |
150
+ | ------------------------------------------------ | ------- |
151
+ | `feat!:`, or a `BREAKING CHANGE:` footer | major |
152
+ | `feat:` | minor |
153
+ | `fix:`, `perf:` | patch |
154
+ | `chore:`, `docs:`, `ci:`, `test:`, anything else | none |
155
+
156
+ The highest bump in the push wins. CI runs `yarn verify`, publishes to npm,
157
+ then commits the version bump and tags it. Nothing to run by hand, and no
158
+ version is bumped by a commit that does not change the published code.
159
+
160
+ To publish without a qualifying commit, run the workflow manually and pick a
161
+ strategy. `current` publishes the version already in `package.json`, which is
162
+ what a first release or a retry after a credentials failure needs.
163
+
164
+ ```bash
165
+ gh workflow run CI --field strategy=minor
166
+ ```
167
+
168
+ ## License
169
+
170
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,20 @@
1
+ export interface InputOption {
2
+ path: string;
3
+ filePattern?: RegExp;
4
+ excludeDirs?: string[];
5
+ importAs?: string;
6
+ }
7
+ export interface GenerateOptions {
8
+ inputs: (string | InputOption)[];
9
+ outputs: string[];
10
+ }
11
+ /**
12
+ * Generate global.d.ts from multiple inputs
13
+ */
14
+ export declare function generateGlobalTypes(options: GenerateOptions): void;
15
+ export declare function extractGenericNames(generics: string): string;
16
+ export declare function findFiles(baseDir: string, { filePattern, excludeDirs, }?: {
17
+ filePattern?: RegExp;
18
+ excludeDirs?: string[];
19
+ }): string[];
20
+ export declare function generateAliasName(filePath: string, outputDir: string): string;
@@ -0,0 +1,160 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ /**
4
+ * Generate global.d.ts from multiple inputs
5
+ */
6
+ export function generateGlobalTypes(options) {
7
+ const { inputs, outputs } = options;
8
+ let allTypes = [];
9
+ let allInterfaces = [];
10
+ const imports = [];
11
+ const resolvedOutputs = outputs.map((o) => path.resolve(o));
12
+ const outputDir = path.dirname(resolvedOutputs[0]);
13
+ const inputFiles = [];
14
+ const resolvedInputs = inputs.map((input) => {
15
+ const isString = typeof input === 'string';
16
+ const inputPath = isString ? input : input.path;
17
+ const absPath = path.resolve(inputPath);
18
+ return {
19
+ path: inputPath,
20
+ filePattern: !isString ? input.filePattern : undefined,
21
+ excludeDirs: !isString ? input.excludeDirs : undefined,
22
+ importAs: !isString ? input.importAs : undefined,
23
+ absPath,
24
+ };
25
+ });
26
+ resolvedInputs.forEach((input) => {
27
+ if (fs.existsSync(input.absPath)) {
28
+ if (fs.statSync(input.absPath).isDirectory()) {
29
+ inputFiles.push(...findFiles(input.absPath, {
30
+ filePattern: input.filePattern || /.*/,
31
+ excludeDirs: input.excludeDirs || [],
32
+ }));
33
+ }
34
+ else {
35
+ inputFiles.push(input.absPath);
36
+ }
37
+ }
38
+ });
39
+ if (inputFiles.length === 0)
40
+ throw new Error('No input files found');
41
+ inputFiles.forEach((file) => {
42
+ const content = fs.readFileSync(file, 'utf-8');
43
+ const inputOption = resolvedInputs.find((inp) => file.startsWith(inp.absPath));
44
+ const alias = generateAliasName(file, outputDir);
45
+ const relativeImport = path
46
+ .relative(outputDir, file)
47
+ .replace(/\\/g, '/')
48
+ .replace(/\.ts$/, '');
49
+ // An input sitting next to the output yields a bare specifier like
50
+ // "index", which resolves as a package name instead of a sibling file.
51
+ const importPath = inputOption?.importAs ||
52
+ (relativeImport.startsWith('.') ? relativeImport : `./${relativeImport}`);
53
+ imports.push(`import * as ${alias} from '${importPath}'`);
54
+ const typeRegex = /^\s*export\s+type\s+([A-Za-z0-9_]+)(<.*>)?/gm;
55
+ const interfaceRegex = /^\s*export\s+interface\s+([A-Za-z0-9_]+)(<.*>)?/gm;
56
+ let match;
57
+ while ((match = typeRegex.exec(content)) !== null) {
58
+ const generics = match[2] || '';
59
+ allTypes.push({
60
+ name: match[1],
61
+ leftGenerics: generics,
62
+ rightGenerics: extractGenericNames(generics),
63
+ alias,
64
+ });
65
+ }
66
+ while ((match = interfaceRegex.exec(content)) !== null) {
67
+ const generics = match[2] || '';
68
+ allInterfaces.push({
69
+ name: match[1],
70
+ alias,
71
+ leftGenerics: generics,
72
+ rightGenerics: extractGenericNames(generics),
73
+ });
74
+ }
75
+ });
76
+ const outputContent = `/* eslint-disable */
77
+ /* prettier-ignore */
78
+ // @ts-nocheck
79
+ // noinspection JSUnusedGlobalSymbols
80
+ // Generated by vite-plugin-global-types
81
+ export {}
82
+
83
+ ${imports.join('\n')}
84
+
85
+ declare global {
86
+ ${allTypes
87
+ .map((t) => ` type ${t.name}${t.leftGenerics} = ${t.alias}.${t.name}${t.rightGenerics}`)
88
+ .join('\n')}
89
+ ${allInterfaces
90
+ .map((i) => ` interface ${i.name}${i.leftGenerics} extends ${i.alias}.${i.name}${i.rightGenerics} {}`)
91
+ .join('\n')}
92
+ }
93
+ `;
94
+ resolvedOutputs.forEach((outputPath) => {
95
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
96
+ fs.writeFileSync(outputPath, outputContent, 'utf-8');
97
+ });
98
+ }
99
+ // -----------------------
100
+ // Helpers
101
+ // -----------------------
102
+ export function extractGenericNames(generics) {
103
+ if (!generics.startsWith('<') || !generics.endsWith('>')) {
104
+ return generics;
105
+ }
106
+ const content = generics.substring(1, generics.length - 1);
107
+ let depth = 0;
108
+ let lastSplit = 0;
109
+ const parts = [];
110
+ for (let i = 0; i < content.length; i++) {
111
+ if (content[i] === '<') {
112
+ depth++;
113
+ }
114
+ else if (content[i] === '>') {
115
+ depth--;
116
+ }
117
+ else if (content[i] === ',' && depth === 0) {
118
+ parts.push(content.substring(lastSplit, i));
119
+ lastSplit = i + 1;
120
+ }
121
+ }
122
+ parts.push(content.substring(lastSplit));
123
+ return `<${parts
124
+ .map((part) => part.split('=')[0].split(' extends ')[0].trim())
125
+ .join(', ')}>`;
126
+ }
127
+ export function findFiles(baseDir, { filePattern = /.*/, excludeDirs = [], } = {}) {
128
+ let results = [];
129
+ const files = fs.readdirSync(baseDir, { withFileTypes: true });
130
+ for (const file of files) {
131
+ const fullPath = path.join(baseDir, file.name);
132
+ if (file.isDirectory()) {
133
+ if (excludeDirs.includes(file.name))
134
+ continue;
135
+ results.push(...findFiles(fullPath, { filePattern, excludeDirs }));
136
+ }
137
+ else if (file.isFile() && filePattern.test(file.name)) {
138
+ results.push(fullPath);
139
+ }
140
+ }
141
+ return results;
142
+ }
143
+ export function generateAliasName(filePath, outputDir) {
144
+ const relativePath = path.relative(outputDir, filePath).replace(/\\/g, '/');
145
+ const noExt = relativePath.replace(/\.ts$/, '');
146
+ const parts = noExt
147
+ .split('/')
148
+ .filter((p) => p && p !== '.' && p !== '..' && p !== 'index' && p !== 'types');
149
+ if (parts.length === 0) {
150
+ parts.push(path.basename(noExt));
151
+ }
152
+ const pascalCase = parts
153
+ .map((p) => p
154
+ .split(/[^A-Za-z0-9]/) // Split by non-alphanumeric (e.g. '-')
155
+ .filter(Boolean)
156
+ .map((seg) => seg.charAt(0).toUpperCase() + seg.slice(1))
157
+ .join(''))
158
+ .join('');
159
+ return pascalCase + 'Types';
160
+ }
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'vite';
2
+ import { GenerateOptions } from './generate-types.js';
3
+ export default function vitePluginGlobalTypes(options: GenerateOptions): Plugin;
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ // Explicit .js extension: this package ships as ESM ("type": "module"), and
2
+ // Node's ESM resolver does not guess extensions for relative imports.
3
+ import { generateGlobalTypes } from './generate-types.js';
4
+ export default function vitePluginGlobalTypes(options) {
5
+ return {
6
+ name: 'vite-plugin-global-types',
7
+ apply: 'serve',
8
+ configureServer(server) {
9
+ server.watcher.on('change', () => {
10
+ generateGlobalTypes(options);
11
+ });
12
+ },
13
+ buildStart() {
14
+ generateGlobalTypes(options);
15
+ },
16
+ };
17
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "vite-plugin-global-types",
3
+ "version": "1.0.0",
4
+ "description": "Vite plugin that collects exported types and interfaces into a generated global.d.ts, so you can use them without importing.",
5
+ "keywords": [
6
+ "codegen",
7
+ "declaration",
8
+ "dts",
9
+ "global",
10
+ "types",
11
+ "typescript",
12
+ "vite",
13
+ "vite-plugin"
14
+ ],
15
+ "homepage": "https://github.com/quentinjuarez/vite-plugin-global-types#readme",
16
+ "bugs": "https://github.com/quentinjuarez/vite-plugin-global-types/issues",
17
+ "license": "MIT",
18
+ "author": "quentinjuarez (https://www.quentinjuarez.dev)",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/quentinjuarez/vite-plugin-global-types.git"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "type": "module",
27
+ "main": "dist/index.js",
28
+ "types": "dist/index.d.ts",
29
+ "scripts": {
30
+ "build": "rm -rf dist && tsc",
31
+ "test": "vitest run",
32
+ "test:watch": "vitest",
33
+ "typecheck": "tsc --noEmit",
34
+ "lint": "oxlint",
35
+ "lint:fix": "oxlint --fix",
36
+ "format": "oxfmt . '!**/global.d.ts'",
37
+ "format:check": "oxfmt --check . '!**/global.d.ts'",
38
+ "verify": "yarn lint && yarn format:check && yarn typecheck && yarn test && yarn build"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.10.0",
42
+ "@vitest/coverage-v8": "^4.0.18",
43
+ "oxfmt": "^0.59.0",
44
+ "oxlint": "^1.74.0",
45
+ "typescript": "^5.9.3",
46
+ "vite": "^8.1.5",
47
+ "vitest": "^4.0.18"
48
+ },
49
+ "peerDependencies": {
50
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
51
+ },
52
+ "packageManager": "yarn@3.8.6"
53
+ }