vite-plugin-assets-split 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 Mr. Python
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,67 @@
1
+ # vite-plugin-assets-split
2
+
3
+ A Vite plugin to split large static assets into smaller chunks. This is useful for dealing with file size limitations on certain static hosting platforms (e.g., Cloudflare Pages, GitHub Pages limits).
4
+
5
+ ## Features
6
+
7
+ - Import static files with `?split` query parameter.
8
+ - Automatically splits files into chunks based on a configurable size limit.
9
+ - Returns an array of URLs for the chunks.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install vite-plugin-assets-split -D
15
+ # or
16
+ yarn add vite-plugin-assets-split -D
17
+ # or
18
+ pnpm add vite-plugin-assets-split -D
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### 1. Configure the plugin in `vite.config.ts`
24
+
25
+ ```typescript
26
+ import { defineConfig } from 'vite';
27
+ import assetsSplit from 'vite-plugin-assets-split';
28
+
29
+ export default defineConfig({
30
+ plugins: [
31
+ assetsSplit({
32
+ limit: 1024 * 1024 * 2, // Optional: Set chunk size limit (e.g., 2MB). Default is 1MB.
33
+ }),
34
+ ],
35
+ });
36
+ ```
37
+
38
+ ### 2. Import assets with `?split`
39
+
40
+ ```typescript
41
+ // Import a large file. The result will be an array of strings (URLs).
42
+ import modelChunks from './large-model.glb?split';
43
+
44
+ console.log(modelChunks);
45
+ // Output: ['/assets/large-model.part1.glb', '/assets/large-model.part2.glb', ...]
46
+
47
+ // Example: Loading a split file (pseudo-code)
48
+ async function loadSplitFile(urls: string[]) {
49
+ const buffers = await Promise.all(urls.map(url => fetch(url).then(res => res.arrayBuffer())));
50
+ // Combine buffers logic here...
51
+ }
52
+ ```
53
+
54
+ ## TypeScript Support
55
+
56
+ To get proper type inference for imports with `?split`, add the following to your `vite-env.d.ts` or a global declaration file:
57
+
58
+ ```typescript
59
+ declare module '*?split' {
60
+ const urls: string[];
61
+ export default urls;
62
+ }
63
+ ```
64
+
65
+ ## License
66
+
67
+ MIT
@@ -0,0 +1,12 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ interface Options {
4
+ /**
5
+ * Maximum size of each chunk in bytes.
6
+ * Default is 1MB (1024 * 1024 bytes).
7
+ */
8
+ limit?: number;
9
+ }
10
+ declare function assetsSplit(options?: Options): Plugin;
11
+
12
+ export { type Options, assetsSplit as default };
@@ -0,0 +1,12 @@
1
+ import { Plugin } from 'vite';
2
+
3
+ interface Options {
4
+ /**
5
+ * Maximum size of each chunk in bytes.
6
+ * Default is 1MB (1024 * 1024 bytes).
7
+ */
8
+ limit?: number;
9
+ }
10
+ declare function assetsSplit(options?: Options): Plugin;
11
+
12
+ export { type Options, assetsSplit as default };
package/dist/index.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ default: () => assetsSplit
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var import_promises = __toESM(require("fs/promises"));
37
+ var import_node_path = __toESM(require("path"));
38
+ function assetsSplit(options = {}) {
39
+ const limit = options.limit ?? 1024 * 1024;
40
+ let config;
41
+ return {
42
+ name: "vite-plugin-assets-split",
43
+ enforce: "pre",
44
+ // Ensure this runs before Vite's default asset handling
45
+ configResolved(resolvedConfig) {
46
+ config = resolvedConfig;
47
+ },
48
+ configureServer(server) {
49
+ server.middlewares.use(async (req, res, next) => {
50
+ const urlObj = new URL(req.url, `http://${req.headers.host}`);
51
+ if (urlObj.searchParams.has("split-chunk")) {
52
+ try {
53
+ const chunkIndex = parseInt(urlObj.searchParams.get("split-chunk"), 10);
54
+ let filePath;
55
+ const pathname = urlObj.pathname;
56
+ if (pathname.startsWith("/@fs/")) {
57
+ filePath = pathname.slice(5);
58
+ } else {
59
+ filePath = import_node_path.default.join(config.root, pathname);
60
+ }
61
+ filePath = decodeURIComponent(filePath);
62
+ try {
63
+ const buffer = await import_promises.default.readFile(filePath);
64
+ const start = chunkIndex * limit;
65
+ if (start >= buffer.length) {
66
+ res.statusCode = 404;
67
+ res.end("Chunk index out of bounds");
68
+ return;
69
+ }
70
+ const end = Math.min(start + limit, buffer.length);
71
+ const chunk = buffer.subarray(start, end);
72
+ res.setHeader("Content-Type", "application/octet-stream");
73
+ res.setHeader("Content-Length", chunk.length);
74
+ res.end(chunk);
75
+ } catch (err) {
76
+ next(err);
77
+ }
78
+ } catch (e) {
79
+ console.error("[vite-plugin-assets-split] Middleware error:", e);
80
+ next(e);
81
+ }
82
+ } else {
83
+ next();
84
+ }
85
+ });
86
+ },
87
+ async load(id) {
88
+ if (!id.includes("?")) return null;
89
+ const [filePath, query] = id.split("?");
90
+ const params = new URLSearchParams(query);
91
+ if (!params.has("split")) {
92
+ return null;
93
+ }
94
+ try {
95
+ const buffer = await import_promises.default.readFile(filePath);
96
+ const totalSize = buffer.length;
97
+ const chunkCount = Math.ceil(totalSize / limit);
98
+ const fileName = import_node_path.default.basename(filePath);
99
+ const ext = import_node_path.default.extname(fileName);
100
+ const nameWithoutExt = import_node_path.default.basename(fileName, ext);
101
+ const references = [];
102
+ if (config.command === "serve") {
103
+ for (let i = 0; i < chunkCount; i++) {
104
+ let urlPath;
105
+ if (filePath.startsWith(config.root)) {
106
+ urlPath = "/" + import_node_path.default.relative(config.root, filePath);
107
+ } else {
108
+ urlPath = "/@fs/" + filePath;
109
+ }
110
+ urlPath = urlPath.split(import_node_path.default.sep).join("/");
111
+ references.push(`${urlPath}?split-chunk=${i}`);
112
+ }
113
+ return `export default ${JSON.stringify(references)};`;
114
+ } else {
115
+ for (let i = 0; i < chunkCount; i++) {
116
+ const start = i * limit;
117
+ const end = Math.min(start + limit, totalSize);
118
+ const chunk = buffer.subarray(start, end);
119
+ const refId = this.emitFile({
120
+ type: "asset",
121
+ name: `${nameWithoutExt}.part${i + 1}${ext}`,
122
+ source: chunk
123
+ });
124
+ references.push(refId);
125
+ }
126
+ const code = `export default [${references.map((ref) => `import.meta.ROLLUP_FILE_URL_${ref}`).join(", ")}];`;
127
+ return {
128
+ code,
129
+ map: null
130
+ };
131
+ }
132
+ } catch (error) {
133
+ console.error(`[vite-plugin-assets-split] Error processing file ${filePath}:`, error);
134
+ throw error;
135
+ }
136
+ }
137
+ };
138
+ }
package/dist/index.mjs ADDED
@@ -0,0 +1,107 @@
1
+ // src/index.ts
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ function assetsSplit(options = {}) {
5
+ const limit = options.limit ?? 1024 * 1024;
6
+ let config;
7
+ return {
8
+ name: "vite-plugin-assets-split",
9
+ enforce: "pre",
10
+ // Ensure this runs before Vite's default asset handling
11
+ configResolved(resolvedConfig) {
12
+ config = resolvedConfig;
13
+ },
14
+ configureServer(server) {
15
+ server.middlewares.use(async (req, res, next) => {
16
+ const urlObj = new URL(req.url, `http://${req.headers.host}`);
17
+ if (urlObj.searchParams.has("split-chunk")) {
18
+ try {
19
+ const chunkIndex = parseInt(urlObj.searchParams.get("split-chunk"), 10);
20
+ let filePath;
21
+ const pathname = urlObj.pathname;
22
+ if (pathname.startsWith("/@fs/")) {
23
+ filePath = pathname.slice(5);
24
+ } else {
25
+ filePath = path.join(config.root, pathname);
26
+ }
27
+ filePath = decodeURIComponent(filePath);
28
+ try {
29
+ const buffer = await fs.readFile(filePath);
30
+ const start = chunkIndex * limit;
31
+ if (start >= buffer.length) {
32
+ res.statusCode = 404;
33
+ res.end("Chunk index out of bounds");
34
+ return;
35
+ }
36
+ const end = Math.min(start + limit, buffer.length);
37
+ const chunk = buffer.subarray(start, end);
38
+ res.setHeader("Content-Type", "application/octet-stream");
39
+ res.setHeader("Content-Length", chunk.length);
40
+ res.end(chunk);
41
+ } catch (err) {
42
+ next(err);
43
+ }
44
+ } catch (e) {
45
+ console.error("[vite-plugin-assets-split] Middleware error:", e);
46
+ next(e);
47
+ }
48
+ } else {
49
+ next();
50
+ }
51
+ });
52
+ },
53
+ async load(id) {
54
+ if (!id.includes("?")) return null;
55
+ const [filePath, query] = id.split("?");
56
+ const params = new URLSearchParams(query);
57
+ if (!params.has("split")) {
58
+ return null;
59
+ }
60
+ try {
61
+ const buffer = await fs.readFile(filePath);
62
+ const totalSize = buffer.length;
63
+ const chunkCount = Math.ceil(totalSize / limit);
64
+ const fileName = path.basename(filePath);
65
+ const ext = path.extname(fileName);
66
+ const nameWithoutExt = path.basename(fileName, ext);
67
+ const references = [];
68
+ if (config.command === "serve") {
69
+ for (let i = 0; i < chunkCount; i++) {
70
+ let urlPath;
71
+ if (filePath.startsWith(config.root)) {
72
+ urlPath = "/" + path.relative(config.root, filePath);
73
+ } else {
74
+ urlPath = "/@fs/" + filePath;
75
+ }
76
+ urlPath = urlPath.split(path.sep).join("/");
77
+ references.push(`${urlPath}?split-chunk=${i}`);
78
+ }
79
+ return `export default ${JSON.stringify(references)};`;
80
+ } else {
81
+ for (let i = 0; i < chunkCount; i++) {
82
+ const start = i * limit;
83
+ const end = Math.min(start + limit, totalSize);
84
+ const chunk = buffer.subarray(start, end);
85
+ const refId = this.emitFile({
86
+ type: "asset",
87
+ name: `${nameWithoutExt}.part${i + 1}${ext}`,
88
+ source: chunk
89
+ });
90
+ references.push(refId);
91
+ }
92
+ const code = `export default [${references.map((ref) => `import.meta.ROLLUP_FILE_URL_${ref}`).join(", ")}];`;
93
+ return {
94
+ code,
95
+ map: null
96
+ };
97
+ }
98
+ } catch (error) {
99
+ console.error(`[vite-plugin-assets-split] Error processing file ${filePath}:`, error);
100
+ throw error;
101
+ }
102
+ }
103
+ };
104
+ }
105
+ export {
106
+ assetsSplit as default
107
+ };
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "vite-plugin-assets-split",
3
+ "version": "1.0.0",
4
+ "description": "A Vite plugin to split large static assets into smaller chunks using a special import query.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsup src/index.ts --format cjs,esm --dts",
13
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
14
+ "playground": "vite playground",
15
+ "prepublishOnly": "npm run build"
16
+ },
17
+ "keywords": [
18
+ "vite",
19
+ "plugin",
20
+ "assets",
21
+ "split",
22
+ "chunk",
23
+ "large file"
24
+ ],
25
+ "author": "Mr-Python-in-China",
26
+ "license": "MIT",
27
+ "peerDependencies": {
28
+ "vite": "*"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^25.1.0",
32
+ "tsup": "^8.5.1",
33
+ "typescript": "^5.9.3",
34
+ "vite": "^7.3.1"
35
+ }
36
+ }