vite-plugin-lib 1.4.0 → 2.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/README.md CHANGED
@@ -44,10 +44,11 @@ import { library } from 'vite-plugin-lib'
44
44
  export default defineConfig({
45
45
  plugins: [
46
46
  library({
47
- entry: 'src/index.ts', // file name determines output file names
48
- formats: ['es', 'umd'], // optional, default is ['es', 'umd']
49
- name: 'YourGlobalUMDName',
47
+ entry: 'src/index.ts', // file name determines output file names, default is 'src/index.ts'
48
+ formats: ['es'], // optional, default is ['es']
49
+ name: 'YourGlobalUMDName', // optional if format does not include 'umd' or 'iife'
50
50
  external: ['some-package'], // optional, default is all node_modules and builtin modules
51
+ manifest: 'package.json', // relative path to package.json, default is package.json
51
52
  }),
52
53
  ],
53
54
  })
package/dist/index.d.mts CHANGED
@@ -2,14 +2,24 @@ import { LibraryFormats, Plugin } from 'vite';
2
2
  import * as vitePluginDts from 'vite-plugin-dts';
3
3
  export { vitePluginDts as dts };
4
4
 
5
+ declare const coverage: {
6
+ enabled: boolean;
7
+ all: boolean;
8
+ include: string[];
9
+ provider: "v8";
10
+ };
5
11
  interface Options {
6
- name: string;
12
+ /** Defaults to 'src/index.ts' */
7
13
  entry: string;
8
- formats?: LibraryFormats[];
9
14
  externalPackages?: (string | RegExp)[];
15
+ /** Defaults to ['es'] */
16
+ formats?: LibraryFormats[];
17
+ /** Defaults to 'package.json' */
18
+ manifest: string;
19
+ name?: string;
10
20
  verbose?: boolean;
11
21
  }
12
- declare function tsconfigPaths({ verbose }?: Partial<Options>): Plugin;
13
- declare function library(options: Options): Plugin[];
22
+ declare function tsconfigPaths(options?: Partial<Options>): Plugin;
23
+ declare function library(options?: Partial<Options>): Plugin[];
14
24
 
15
- export { Options, library, tsconfigPaths };
25
+ export { type Options, coverage, library, tsconfigPaths };
package/dist/index.d.ts CHANGED
@@ -2,14 +2,24 @@ import { LibraryFormats, Plugin } from 'vite';
2
2
  import * as vitePluginDts from 'vite-plugin-dts';
3
3
  export { vitePluginDts as dts };
4
4
 
5
+ declare const coverage: {
6
+ enabled: boolean;
7
+ all: boolean;
8
+ include: string[];
9
+ provider: "v8";
10
+ };
5
11
  interface Options {
6
- name: string;
12
+ /** Defaults to 'src/index.ts' */
7
13
  entry: string;
8
- formats?: LibraryFormats[];
9
14
  externalPackages?: (string | RegExp)[];
15
+ /** Defaults to ['es'] */
16
+ formats?: LibraryFormats[];
17
+ /** Defaults to 'package.json' */
18
+ manifest: string;
19
+ name?: string;
10
20
  verbose?: boolean;
11
21
  }
12
- declare function tsconfigPaths({ verbose }?: Partial<Options>): Plugin;
13
- declare function library(options: Options): Plugin[];
22
+ declare function tsconfigPaths(options?: Partial<Options>): Plugin;
23
+ declare function library(options?: Partial<Options>): Plugin[];
14
24
 
15
- export { Options, library, tsconfigPaths };
25
+ export { type Options, coverage, library, tsconfigPaths };
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { existsSync } from 'node:fs';
2
- import { readdir, readFile, writeFile } from 'node:fs/promises';
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { unlink, readdir, readFile, writeFile } from 'node:fs/promises';
3
3
  import { builtinModules } from 'node:module';
4
4
  import path from 'node:path';
5
+ import process from 'node:process';
5
6
  import c from 'picocolors';
6
7
  import ts from 'typescript';
7
8
  import dts__default from 'vite-plugin-dts';
@@ -19,10 +20,13 @@ function logError(text) {
19
20
  console.error(`${c.red("[vite:lib]")} ${text}`);
20
21
  }
21
22
 
22
- async function generateMTSDeclarations(typesDir) {
23
+ async function generateMTSDeclarations(typesDir, deleteSourceFiles) {
23
24
  const files = await collectFiles(typesDir);
24
25
  for (const file of files) {
25
26
  await createMTSImports(file);
27
+ if (deleteSourceFiles) {
28
+ unlink(file);
29
+ }
26
30
  }
27
31
  log(`Generated ${files.length} MTS declarations.`);
28
32
  }
@@ -41,24 +45,70 @@ async function collectFiles(dir) {
41
45
  async function createMTSImports(file) {
42
46
  const content = await readFile(file, "utf-8");
43
47
  const lines = content.split("\n");
44
- const modified = lines.map(transformLine);
48
+ const modified = lines.map((line) => transformLine(file, line));
45
49
  const targetFile = file.replace(".d.ts", ".d.mts");
46
50
  await writeFile(targetFile, modified.join("\n"));
47
51
  }
48
- function transformLine(line) {
49
- const isStaticImport = line.includes("import ") && line.includes(`from '.`);
50
- if (isStaticImport) {
51
- return `${line.substring(0, line.length - 2)}.d.mts';`;
52
+ function transformLine(file, line) {
53
+ return transformStaticImport(file, line, "'") ?? transformStaticImport(file, line, '"') ?? transformExport(file, line, "'") ?? transformExport(file, line, '"') ?? line;
54
+ }
55
+ function transformStaticImport(file, line, quote) {
56
+ const importPathMarker = `from ${quote}`;
57
+ const isStaticImport = line.includes("import ") && line.includes(`${importPathMarker}.`);
58
+ if (!isStaticImport) {
59
+ return void 0;
60
+ }
61
+ const importStartIndex = line.lastIndexOf(importPathMarker);
62
+ const importPath = line.substring(
63
+ importStartIndex + importPathMarker.length,
64
+ line.length - 2
65
+ );
66
+ const resolvedImport = path.resolve(path.dirname(file), importPath);
67
+ if (existsSync(resolvedImport)) {
68
+ log(`got index import ${resolvedImport}`);
69
+ return `${line.substring(0, line.length - 2)}/index.mjs${quote};`;
70
+ }
71
+ return `${line.substring(0, line.length - 2)}.mjs${quote};`;
72
+ }
73
+ function transformExport(file, line, quote) {
74
+ const exportPathMarker = ` from ${quote}`;
75
+ const isStaticExport = line.includes("export ") && line.includes(`${exportPathMarker}.`);
76
+ if (!isStaticExport) {
77
+ return void 0;
52
78
  }
53
- const isStaticExport = line.includes("export ") && line.includes(` from '.`);
54
- if (isStaticExport) {
55
- return `${line.substring(0, line.length - 2)}.mjs';`;
79
+ const exportStartIndex = line.lastIndexOf(exportPathMarker);
80
+ const exportPath = line.substring(
81
+ exportStartIndex + exportPathMarker.length,
82
+ line.length - 2
83
+ );
84
+ const resolvedExport = path.resolve(path.dirname(file), exportPath);
85
+ if (existsSync(resolvedExport)) {
86
+ log(`got index export ${resolvedExport}`);
87
+ return `${line.substring(0, line.length - 2)}/index.mjs${quote};`;
56
88
  }
57
- return line;
89
+ return `${line.substring(0, line.length - 2)}.mjs${quote};`;
58
90
  }
59
91
 
60
92
  const typesDir = "dist/types";
61
- function tsconfigPaths({ verbose } = {}) {
93
+ const coverage = {
94
+ enabled: !!process.env.COVERAGE,
95
+ all: true,
96
+ include: ["src/**/*.*"],
97
+ provider: "v8"
98
+ };
99
+ const defaults = {
100
+ entry: "src/index.ts",
101
+ formats: ["es"],
102
+ manifest: "package.json"
103
+ };
104
+ function mergeWithDefaults(options) {
105
+ return {
106
+ ...defaults,
107
+ ...options
108
+ };
109
+ }
110
+ function tsconfigPaths(options = {}) {
111
+ const { verbose } = mergeWithDefaults(options);
62
112
  return {
63
113
  name: "vite-plugin-lib:alias",
64
114
  enforce: "pre",
@@ -88,6 +138,7 @@ function tsconfigPaths({ verbose } = {}) {
88
138
  function buildConfig({
89
139
  entry,
90
140
  formats,
141
+ manifest,
91
142
  name,
92
143
  externalPackages
93
144
  }) {
@@ -110,13 +161,28 @@ function buildConfig({
110
161
  fileName: (format) => formatToFileName(entry, format)
111
162
  },
112
163
  rollupOptions: {
113
- external: externalPackages ?? [/node_modules/, ...builtinModules]
164
+ external: externalPackages ?? [
165
+ /node_modules/,
166
+ ...builtinModules,
167
+ ...getDependencies(manifest)
168
+ ]
114
169
  }
115
170
  }
116
171
  };
117
172
  }
118
173
  };
119
174
  }
175
+ function getDependencies(manifest) {
176
+ try {
177
+ const content = readFileSync(manifest, { encoding: "utf-8" });
178
+ const { dependencies = {} } = JSON.parse(content);
179
+ return Object.keys(dependencies);
180
+ } catch (error) {
181
+ const message = getErrorMessage(error);
182
+ logError(`Could not read ${c.green(manifest)}: ${message}`);
183
+ throw error;
184
+ }
185
+ }
120
186
  function logInjectedAliases(aliasOptions, config, verbose) {
121
187
  log(`Injected ${c.green(aliasOptions.length)} aliases.`);
122
188
  if (!verbose) {
@@ -188,17 +254,18 @@ function formatToFileName(entry, format) {
188
254
  }
189
255
  return `${entryFileName}.${format}.js`;
190
256
  }
191
- function library(options) {
257
+ function library(options = {}) {
258
+ const mergedOptions = mergeWithDefaults(options);
192
259
  return [
193
260
  tsconfigPaths(),
194
- buildConfig(options),
261
+ buildConfig(mergedOptions),
195
262
  dts__default({
196
263
  cleanVueFileName: true,
197
264
  copyDtsFiles: true,
198
- include: `${path.resolve(options.entry, "..")}/**`,
265
+ include: `${path.resolve(mergedOptions.entry, "..")}/**`,
199
266
  outDir: typesDir,
200
267
  staticImport: true,
201
- afterBuild: includesESFormat(options.formats) ? () => generateMTSDeclarations(typesDir) : void 0
268
+ afterBuild: includesESFormat(options.formats) ? () => generateMTSDeclarations(typesDir, options.formats?.length === 1) : void 0
202
269
  })
203
270
  ];
204
271
  }
@@ -242,4 +309,4 @@ function getErrorMessage(error) {
242
309
  return isObject ? error.message : String(error);
243
310
  }
244
311
 
245
- export { library, tsconfigPaths };
312
+ export { coverage, library, tsconfigPaths };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-lib",
3
- "version": "1.4.0",
3
+ "version": "2.0.0",
4
4
  "description": "Vite plugin for build configuration, automatic aliases, and type declarations.",
5
5
  "author": "Jan Müller <janmueller3698@gmail.com>",
6
6
  "license": "MIT",
@@ -18,19 +18,13 @@
18
18
  ],
19
19
  "exports": {
20
20
  ".": {
21
- "require": {
22
- "types": "./dist/index.d.ts",
23
- "default": "./dist/index.cjs"
24
- },
25
21
  "import": {
26
22
  "types": "./dist/index.d.mts",
27
23
  "default": "./dist/index.mjs"
28
24
  }
29
25
  }
30
26
  },
31
- "main": "dist/index.cjs",
32
- "module": "dist/index.mjs",
33
- "types": "dist/index.d.ts",
27
+ "types": "dist/index.d.mts",
34
28
  "files": [
35
29
  "dist",
36
30
  "LICENSE"
@@ -41,14 +35,14 @@
41
35
  },
42
36
  "dependencies": {
43
37
  "picocolors": "1.0.0",
44
- "vite-plugin-dts": "3.3.1"
38
+ "vite-plugin-dts": "3.5.2"
45
39
  },
46
40
  "devDependencies": {
47
- "@types/node": "18.17.1",
48
- "typescript": "5.1.6",
49
- "unbuild": "v2.0.0-rc.0",
50
- "vite": "4.4.7",
51
- "@yeger/tsconfig": "1.1.2"
41
+ "@types/node": "18.17.11",
42
+ "typescript": "5.2.2",
43
+ "unbuild": "2.0.0",
44
+ "vite": "4.4.9",
45
+ "@yeger/tsconfig": "2.0.0"
52
46
  },
53
47
  "publishConfig": {
54
48
  "access": "public"
package/dist/index.cjs DELETED
@@ -1,267 +0,0 @@
1
- 'use strict';
2
-
3
- const node_fs = require('node:fs');
4
- const promises = require('node:fs/promises');
5
- const node_module = require('node:module');
6
- const path = require('node:path');
7
- const c = require('picocolors');
8
- const ts = require('typescript');
9
- const dts = require('vite-plugin-dts');
10
- const vite = require('vite');
11
-
12
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
13
-
14
- function _interopNamespaceCompat(e) {
15
- if (e && typeof e === 'object' && 'default' in e) return e;
16
- const n = Object.create(null);
17
- if (e) {
18
- for (const k in e) {
19
- n[k] = e[k];
20
- }
21
- }
22
- n.default = e;
23
- return n;
24
- }
25
-
26
- const path__default = /*#__PURE__*/_interopDefaultCompat(path);
27
- const c__default = /*#__PURE__*/_interopDefaultCompat(c);
28
- const ts__default = /*#__PURE__*/_interopDefaultCompat(ts);
29
- const dts__default = /*#__PURE__*/_interopDefaultCompat(dts);
30
- const dts__namespace = /*#__PURE__*/_interopNamespaceCompat(dts);
31
-
32
- function log(text) {
33
- console.log(`${c__default.cyan("[vite:lib]")} ${text}`);
34
- }
35
- function logWarn(text) {
36
- console.warn(`${c__default.yellow("[vite:lib]")} ${text}`);
37
- }
38
- function logError(text) {
39
- console.error(`${c__default.red("[vite:lib]")} ${text}`);
40
- }
41
-
42
- async function generateMTSDeclarations(typesDir) {
43
- const files = await collectFiles(typesDir);
44
- for (const file of files) {
45
- await createMTSImports(file);
46
- }
47
- log(`Generated ${files.length} MTS declarations.`);
48
- }
49
- async function collectFiles(dir) {
50
- const entries = await promises.readdir(dir, {
51
- recursive: false,
52
- // does not provide full path to nested files
53
- withFileTypes: true
54
- });
55
- const files = entries.filter((entry) => entry.isFile());
56
- const nestedFiles = await Promise.all(
57
- entries.filter((entry) => entry.isDirectory()).map((entry) => collectFiles(vite.normalizePath(path__default.join(dir, entry.name))))
58
- );
59
- return files.map((file) => vite.normalizePath(path__default.join(dir, file.name))).concat(...nestedFiles);
60
- }
61
- async function createMTSImports(file) {
62
- const content = await promises.readFile(file, "utf-8");
63
- const lines = content.split("\n");
64
- const modified = lines.map(transformLine);
65
- const targetFile = file.replace(".d.ts", ".d.mts");
66
- await promises.writeFile(targetFile, modified.join("\n"));
67
- }
68
- function transformLine(line) {
69
- const isStaticImport = line.includes("import ") && line.includes(`from '.`);
70
- if (isStaticImport) {
71
- return `${line.substring(0, line.length - 2)}.d.mts';`;
72
- }
73
- const isStaticExport = line.includes("export ") && line.includes(` from '.`);
74
- if (isStaticExport) {
75
- return `${line.substring(0, line.length - 2)}.mjs';`;
76
- }
77
- return line;
78
- }
79
-
80
- const typesDir = "dist/types";
81
- function tsconfigPaths({ verbose } = {}) {
82
- return {
83
- name: "vite-plugin-lib:alias",
84
- enforce: "pre",
85
- config: async (config) => {
86
- const tsconfigPath = path__default.resolve(config.root ?? ".", "tsconfig.json");
87
- const { baseUrl, paths } = await readConfig(tsconfigPath);
88
- if (!baseUrl || !paths) {
89
- log("No paths found in tsconfig.json.");
90
- return config;
91
- }
92
- const pathToAlias = pathToAliasFactory(tsconfigPath, baseUrl, verbose);
93
- const aliasOptions = Object.entries(paths).map(pathToAlias).filter(Boolean);
94
- if (aliasOptions.length > 0) {
95
- logInjectedAliases(aliasOptions, config, verbose);
96
- }
97
- const existingAlias = transformExistingAlias(config.resolve?.alias);
98
- return {
99
- ...config,
100
- resolve: {
101
- ...config.resolve,
102
- alias: [...existingAlias, ...aliasOptions]
103
- }
104
- };
105
- }
106
- };
107
- }
108
- function buildConfig({
109
- entry,
110
- formats,
111
- name,
112
- externalPackages
113
- }) {
114
- if (!externalPackages) {
115
- log("Externalized all packages.");
116
- }
117
- return {
118
- name: "vite-plugin-lib:build",
119
- enforce: "pre",
120
- config: async (config) => {
121
- return {
122
- ...config,
123
- build: {
124
- ...config.build,
125
- lib: {
126
- ...config.build?.lib,
127
- entry: path__default.resolve(config.root ?? ".", entry),
128
- formats,
129
- name,
130
- fileName: (format) => formatToFileName(entry, format)
131
- },
132
- rollupOptions: {
133
- external: externalPackages ?? [/node_modules/, ...node_module.builtinModules]
134
- }
135
- }
136
- };
137
- }
138
- };
139
- }
140
- function logInjectedAliases(aliasOptions, config, verbose) {
141
- log(`Injected ${c__default.green(aliasOptions.length)} aliases.`);
142
- if (!verbose) {
143
- return;
144
- }
145
- const base = `${path__default.resolve(config.root ?? ".")}/`;
146
- aliasOptions.map(
147
- ({ find, replacement }) => `${c__default.gray(">")} ${c__default.green(find.toString())} ${c__default.gray(
148
- c__default.bold("->")
149
- )} ${c__default.green(replacement.replace(base, ""))}`
150
- ).forEach(log);
151
- }
152
- function pathToAliasFactory(tsconfigPath, baseUrl, verbose) {
153
- return ([alias, replacements]) => {
154
- if (replacements.length === 0) {
155
- if (verbose) {
156
- logWarn(`No replacements for alias ${c__default.green(alias)}.`);
157
- }
158
- return void 0;
159
- }
160
- if (verbose && replacements.length > 1) {
161
- logWarn(`Found more than one replacement for alias ${c__default.green(alias)}.`);
162
- logWarn("Using the first existing replacement.");
163
- }
164
- const find = alias.replace("/*", "");
165
- const replacement = getFirstExistingReplacement(
166
- tsconfigPath,
167
- baseUrl,
168
- replacements,
169
- find
170
- );
171
- if (!replacement) {
172
- if (verbose) {
173
- logWarn(`No replacement found for alias ${c__default.green(alias)}.`);
174
- }
175
- return void 0;
176
- }
177
- return {
178
- find,
179
- replacement
180
- };
181
- };
182
- }
183
- function getFirstExistingReplacement(tsconfigPath, baseUrl, replacements, find, verbose) {
184
- for (const replacement of replacements) {
185
- const resolvedReplacement = path__default.resolve(
186
- tsconfigPath,
187
- baseUrl,
188
- replacement.replace("/*", "") ?? find
189
- );
190
- if (node_fs.existsSync(resolvedReplacement)) {
191
- return resolvedReplacement;
192
- } else if (verbose) {
193
- logWarn(`Path ${c__default.green(replacement)} does not exist.`);
194
- }
195
- }
196
- return void 0;
197
- }
198
- function formatToFileName(entry, format) {
199
- const entryFileName = entry.substring(
200
- entry.lastIndexOf("/") + 1,
201
- entry.lastIndexOf(".")
202
- );
203
- if (format === "es") {
204
- return `${entryFileName}.mjs`;
205
- }
206
- if (format === "cjs") {
207
- return `${entryFileName}.cjs`;
208
- }
209
- return `${entryFileName}.${format}.js`;
210
- }
211
- function library(options) {
212
- return [
213
- tsconfigPaths(),
214
- buildConfig(options),
215
- dts__default({
216
- cleanVueFileName: true,
217
- copyDtsFiles: true,
218
- include: `${path__default.resolve(options.entry, "..")}/**`,
219
- outDir: typesDir,
220
- staticImport: true,
221
- afterBuild: includesESFormat(options.formats) ? () => generateMTSDeclarations(typesDir) : void 0
222
- })
223
- ];
224
- }
225
- function transformExistingAlias(alias) {
226
- if (!alias) {
227
- return [];
228
- }
229
- if (Array.isArray(alias)) {
230
- return alias;
231
- }
232
- return Object.entries(alias).map(([find, replacement]) => ({
233
- find,
234
- replacement
235
- }));
236
- }
237
- async function readConfig(configPath) {
238
- try {
239
- const configFileText = await promises.readFile(configPath, { encoding: "utf-8" });
240
- const { config } = ts__default.parseConfigFileTextToJson(configPath, configFileText);
241
- if (!("baseUrl" in config?.compilerOptions)) {
242
- throw new Error("No baseUrl provided in tsconfig.json.");
243
- }
244
- const { options } = ts__default.parseJsonConfigFileContent(
245
- config,
246
- // eslint-disable-next-line import/no-named-as-default-member
247
- ts__default.sys,
248
- path__default.dirname(configPath)
249
- );
250
- return options;
251
- } catch (error) {
252
- const message = getErrorMessage(error);
253
- logError(`Could not read tsconfig.json: ${message}`);
254
- throw error;
255
- }
256
- }
257
- function includesESFormat(formats) {
258
- return formats?.includes("es") ?? true;
259
- }
260
- function getErrorMessage(error) {
261
- const isObject = typeof error === "object" && error !== null && "message" in error;
262
- return isObject ? error.message : String(error);
263
- }
264
-
265
- exports.dts = dts__namespace;
266
- exports.library = library;
267
- exports.tsconfigPaths = tsconfigPaths;
package/dist/index.d.cts DELETED
@@ -1,15 +0,0 @@
1
- import { LibraryFormats, Plugin } from 'vite';
2
- import * as vitePluginDts from 'vite-plugin-dts';
3
- export { vitePluginDts as dts };
4
-
5
- interface Options {
6
- name: string;
7
- entry: string;
8
- formats?: LibraryFormats[];
9
- externalPackages?: (string | RegExp)[];
10
- verbose?: boolean;
11
- }
12
- declare function tsconfigPaths({ verbose }?: Partial<Options>): Plugin;
13
- declare function library(options: Options): Plugin[];
14
-
15
- export { Options, library, tsconfigPaths };