vite-plugin-lib 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) 2022 Jan Müller
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,54 @@
1
+ # vite-plugin-lib
2
+
3
+ > Vite plugin for build configuration, automatic aliases, and type declarations.
4
+
5
+ [![npm](https://img.shields.io/npm/v/vite-plugin-lib?color=a1b858&label=)](https://npmjs.com/package/vite-plugin-lib)
6
+
7
+ ## Features
8
+
9
+ - Automatic aliases based on `tsconfig.json`
10
+ - Automatic build configuration
11
+ - Type declaration generation based on [vite-plugin-dts](https://github.com/qmhc/vite-plugin-dts).
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ yarn add -D vite-plugin-lib
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ This highly opinionated all-in one Vite plugin enables automatic alias configuration based on `tsconfig.json` paths, library export configuration, and type declaration generation.
22
+
23
+ ### Aliases
24
+
25
+ ```ts
26
+ import { defineConfig } from 'vite'
27
+
28
+ import { tsconfigPaths } from 'vite-plugin-lib'
29
+
30
+ export default defineConfig({
31
+ plugins: [tsconfigPaths()],
32
+ })
33
+ ```
34
+
35
+ ### Library
36
+
37
+ The `library` plugin includes the `alias` plugin, configures build settings, and generates `.d.ts` files.
38
+
39
+ ```ts
40
+ import { defineConfig } from 'vite'
41
+
42
+ import { library } from 'vite-plugin-lib'
43
+
44
+ export default defineConfig({
45
+ plugins: [
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',
50
+ external: ['some-package'], // optional, default is all node_modules and builtin modules
51
+ }),
52
+ ],
53
+ })
54
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+
3
+ const promises = require('fs/promises');
4
+ const module$1 = require('module');
5
+ const path = require('path');
6
+ const c = require('picocolors');
7
+ const typescript = require('typescript');
8
+ const dts = require('vite-plugin-dts');
9
+
10
+ function _interopNamespaceDefault(e) {
11
+ const n = Object.create(null);
12
+ if (e) {
13
+ for (const k in e) {
14
+ n[k] = e[k];
15
+ }
16
+ }
17
+ n.default = e;
18
+ return n;
19
+ }
20
+
21
+ const dts__namespace = /*#__PURE__*/_interopNamespaceDefault(dts);
22
+
23
+ function log(text) {
24
+ console.log(`${c.cyan("[vite:lib]")} ${text}`);
25
+ }
26
+ const tsconfigPaths = ({ verbose } = {}) => {
27
+ return {
28
+ name: "vite-plugin-lib:alias",
29
+ enforce: "pre",
30
+ config: async (config) => {
31
+ const tsconfigPath = path.resolve(config.root ?? ".", "tsconfig.json");
32
+ const { baseUrl, paths } = await readConfig(tsconfigPath);
33
+ if (!baseUrl || !paths) {
34
+ return config;
35
+ }
36
+ const aliasOptions = Object.entries(paths).map(
37
+ ([alias, replacement]) => ({
38
+ find: alias.replace("/*", ""),
39
+ replacement: path.resolve(
40
+ tsconfigPath,
41
+ baseUrl,
42
+ replacement[0].replace("/*", "")
43
+ )
44
+ })
45
+ );
46
+ if (aliasOptions.length > 0) {
47
+ log(`Injected ${c.green(aliasOptions.length)} aliases.`);
48
+ }
49
+ if (verbose) {
50
+ aliasOptions.forEach(
51
+ (alias) => log(
52
+ `Alias ${c.green(alias.find.toString())} -> ${c.green(
53
+ alias.replacement
54
+ )} configured`
55
+ )
56
+ );
57
+ }
58
+ const existingAlias = transformExistingAlias(config.resolve?.alias);
59
+ return {
60
+ ...config,
61
+ resolve: {
62
+ ...config.resolve,
63
+ alias: [...existingAlias, ...aliasOptions]
64
+ }
65
+ };
66
+ }
67
+ };
68
+ };
69
+ const buildConfig = ({
70
+ entry,
71
+ formats,
72
+ name,
73
+ externalPackages
74
+ }) => {
75
+ if (!externalPackages) {
76
+ log("Externalizing all packages.");
77
+ }
78
+ return {
79
+ name: "vite-plugin-lib:build",
80
+ enforce: "pre",
81
+ config: async (config) => {
82
+ return {
83
+ ...config,
84
+ build: {
85
+ ...config.build,
86
+ lib: {
87
+ ...config.build?.lib,
88
+ entry: path.resolve(config.root ?? ".", entry),
89
+ formats,
90
+ name,
91
+ fileName: (format) => formatToFileName(entry, format)
92
+ },
93
+ rollupOptions: {
94
+ external: externalPackages ?? [/node_modules/, ...module$1.builtinModules]
95
+ }
96
+ }
97
+ };
98
+ }
99
+ };
100
+ };
101
+ function formatToFileName(entry, format) {
102
+ const entryFileName = entry.substring(
103
+ entry.lastIndexOf("/") + 1,
104
+ entry.lastIndexOf(".")
105
+ );
106
+ if (format === "es") {
107
+ return `${entryFileName}.mjs`;
108
+ }
109
+ if (format === "cjs") {
110
+ return `${entryFileName}.cjs`;
111
+ }
112
+ return `${entryFileName}.${format}.js`;
113
+ }
114
+ function library(options) {
115
+ return [
116
+ tsconfigPaths(options),
117
+ buildConfig(options),
118
+ dts({
119
+ cleanVueFileName: true,
120
+ include: `${path.resolve(options.entry, "..")}**`,
121
+ outputDir: "dist/types",
122
+ staticImport: true
123
+ })
124
+ ];
125
+ }
126
+ function transformExistingAlias(alias) {
127
+ if (!alias) {
128
+ return [];
129
+ }
130
+ if (Array.isArray(alias)) {
131
+ return alias;
132
+ }
133
+ return Object.entries(alias).map(([find, replacement]) => ({
134
+ find,
135
+ replacement
136
+ }));
137
+ }
138
+ async function readConfig(configPath) {
139
+ const configFileText = await promises.readFile(configPath, { encoding: "utf-8" });
140
+ const { config } = typescript.parseConfigFileTextToJson(configPath, configFileText);
141
+ const { options } = typescript.parseJsonConfigFileContent(
142
+ config,
143
+ typescript.sys,
144
+ path.dirname(configPath)
145
+ );
146
+ return options;
147
+ }
148
+
149
+ exports.dts = dts__namespace;
150
+ exports.library = library;
151
+ exports.tsconfigPaths = tsconfigPaths;
@@ -0,0 +1,15 @@
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 const tsconfigPaths: ({ verbose }?: Partial<Options>) => Plugin;
13
+ declare function library(options: Options): Plugin[];
14
+
15
+ export { Options, library, tsconfigPaths };
package/dist/index.mjs ADDED
@@ -0,0 +1,136 @@
1
+ import { readFile } from 'fs/promises';
2
+ import { builtinModules } from 'module';
3
+ import path from 'path';
4
+ import c from 'picocolors';
5
+ import { parseConfigFileTextToJson, parseJsonConfigFileContent, sys } from 'typescript';
6
+ import dts__default from 'vite-plugin-dts';
7
+ import * as dts from 'vite-plugin-dts';
8
+ export { dts };
9
+
10
+ function log(text) {
11
+ console.log(`${c.cyan("[vite:lib]")} ${text}`);
12
+ }
13
+ const tsconfigPaths = ({ verbose } = {}) => {
14
+ return {
15
+ name: "vite-plugin-lib:alias",
16
+ enforce: "pre",
17
+ config: async (config) => {
18
+ const tsconfigPath = path.resolve(config.root ?? ".", "tsconfig.json");
19
+ const { baseUrl, paths } = await readConfig(tsconfigPath);
20
+ if (!baseUrl || !paths) {
21
+ return config;
22
+ }
23
+ const aliasOptions = Object.entries(paths).map(
24
+ ([alias, replacement]) => ({
25
+ find: alias.replace("/*", ""),
26
+ replacement: path.resolve(
27
+ tsconfigPath,
28
+ baseUrl,
29
+ replacement[0].replace("/*", "")
30
+ )
31
+ })
32
+ );
33
+ if (aliasOptions.length > 0) {
34
+ log(`Injected ${c.green(aliasOptions.length)} aliases.`);
35
+ }
36
+ if (verbose) {
37
+ aliasOptions.forEach(
38
+ (alias) => log(
39
+ `Alias ${c.green(alias.find.toString())} -> ${c.green(
40
+ alias.replacement
41
+ )} configured`
42
+ )
43
+ );
44
+ }
45
+ const existingAlias = transformExistingAlias(config.resolve?.alias);
46
+ return {
47
+ ...config,
48
+ resolve: {
49
+ ...config.resolve,
50
+ alias: [...existingAlias, ...aliasOptions]
51
+ }
52
+ };
53
+ }
54
+ };
55
+ };
56
+ const buildConfig = ({
57
+ entry,
58
+ formats,
59
+ name,
60
+ externalPackages
61
+ }) => {
62
+ if (!externalPackages) {
63
+ log("Externalizing all packages.");
64
+ }
65
+ return {
66
+ name: "vite-plugin-lib:build",
67
+ enforce: "pre",
68
+ config: async (config) => {
69
+ return {
70
+ ...config,
71
+ build: {
72
+ ...config.build,
73
+ lib: {
74
+ ...config.build?.lib,
75
+ entry: path.resolve(config.root ?? ".", entry),
76
+ formats,
77
+ name,
78
+ fileName: (format) => formatToFileName(entry, format)
79
+ },
80
+ rollupOptions: {
81
+ external: externalPackages ?? [/node_modules/, ...builtinModules]
82
+ }
83
+ }
84
+ };
85
+ }
86
+ };
87
+ };
88
+ function formatToFileName(entry, format) {
89
+ const entryFileName = entry.substring(
90
+ entry.lastIndexOf("/") + 1,
91
+ entry.lastIndexOf(".")
92
+ );
93
+ if (format === "es") {
94
+ return `${entryFileName}.mjs`;
95
+ }
96
+ if (format === "cjs") {
97
+ return `${entryFileName}.cjs`;
98
+ }
99
+ return `${entryFileName}.${format}.js`;
100
+ }
101
+ function library(options) {
102
+ return [
103
+ tsconfigPaths(options),
104
+ buildConfig(options),
105
+ dts__default({
106
+ cleanVueFileName: true,
107
+ include: `${path.resolve(options.entry, "..")}**`,
108
+ outputDir: "dist/types",
109
+ staticImport: true
110
+ })
111
+ ];
112
+ }
113
+ function transformExistingAlias(alias) {
114
+ if (!alias) {
115
+ return [];
116
+ }
117
+ if (Array.isArray(alias)) {
118
+ return alias;
119
+ }
120
+ return Object.entries(alias).map(([find, replacement]) => ({
121
+ find,
122
+ replacement
123
+ }));
124
+ }
125
+ async function readConfig(configPath) {
126
+ const configFileText = await readFile(configPath, { encoding: "utf-8" });
127
+ const { config } = parseConfigFileTextToJson(configPath, configFileText);
128
+ const { options } = parseJsonConfigFileContent(
129
+ config,
130
+ sys,
131
+ path.dirname(configPath)
132
+ );
133
+ return options;
134
+ }
135
+
136
+ export { library, tsconfigPaths };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "vite-plugin-lib",
3
+ "version": "1.0.0",
4
+ "description": "Vite plugin for build configuration, automatic aliases, and type declarations.",
5
+ "author": "Jan Müller <janmueller3698@gmail.com>",
6
+ "license": "MIT",
7
+ "funding": "https://github.com/sponsors/DerYeger",
8
+ "homepage": "https://github.com/DerYeger/yeger/tree/main/packages/vite-plugin-lib",
9
+ "repository": "github:DerYeger/yeger",
10
+ "bugs": {
11
+ "url": "https://github.com/DerYeger/yeger/issues"
12
+ },
13
+ "keywords": [
14
+ "vite-plugin",
15
+ "declarations",
16
+ "library",
17
+ "aliases"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "require": "./dist/index.cjs",
23
+ "import": "./dist/index.mjs"
24
+ }
25
+ },
26
+ "main": "dist/index.cjs",
27
+ "module": "dist/index.mjs",
28
+ "types": "dist/index.d.ts",
29
+ "files": [
30
+ "dist",
31
+ "LICENSE"
32
+ ],
33
+ "peerDependencies": {
34
+ "typescript": "*",
35
+ "vite": "^2.0.0 || ^3.0.0 || ^4.0.0"
36
+ },
37
+ "dependencies": {
38
+ "picocolors": "1.0.0",
39
+ "vite-plugin-dts": "1.7.1"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "18.11.13",
43
+ "@vitest/ui": "0.26.2",
44
+ "typescript": "4.9.4",
45
+ "unbuild": "1.0.2",
46
+ "vite": "4.0.0",
47
+ "@yeger/tsconfig": "1.1.0"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "unbuild",
54
+ "lint": "yeger-lint",
55
+ "check:tsc": "tsc --noEmit"
56
+ }
57
+ }