vite-plugin-singlefile-compression 2.0.4 → 2.0.5

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.txt CHANGED
@@ -1,5 +1,5 @@
1
1
  The MIT License (MIT)
2
- Copyright © 2024-present bddjr ; Adapted from https://www.npmjs.com/package/vite-plugin-singlefile
2
+ Copyright © 2024 bddjr
3
3
 
4
4
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
5
 
package/README.md CHANGED
@@ -105,19 +105,19 @@ export interface Options {
105
105
  https://bddjr.github.io/vite-plugin-singlefile-compression/
106
106
 
107
107
  ```
108
- vite v6.0.11 building for production...
108
+ vite v6.2.6 building for production...
109
109
  ✓ 45 modules transformed.
110
110
  rendering chunks (1)...
111
111
 
112
- vite-plugin-singlefile-compression 2.0.1 building...
112
+ vite-plugin-singlefile-compression 2.0.5 building...
113
113
 
114
- file:///D:/bddjr/Desktop/code/js/vite-plugin-singlefile-compression/test/dist/index.html
115
- 101.6 KiB -> 46.39 KiB
114
+ file:///D:/code/js/vite-plugin-singlefile-compression/test/dist/index.html
115
+ 101.63 KiB -> 46.42 KiB
116
116
 
117
117
  Finish.
118
118
 
119
- dist/index.html 47.50 kB
120
- ✓ built in 732ms
119
+ dist/index.html 47.53 kB
120
+ ✓ built in 770ms
121
121
  ```
122
122
 
123
123
  ![](effect.jpg)
@@ -133,10 +133,3 @@ npm i
133
133
  cd ..
134
134
  npm run build
135
135
  ```
136
-
137
- ## License
138
-
139
- Using [MIT License](LICENSE.txt).
140
- [src/template](src/template) using [Unlicense](src/template/LICENSE.txt).
141
-
142
- Adapted from [vite-plugin-singlefile](https://www.npmjs.com/package/vite-plugin-singlefile).
@@ -0,0 +1 @@
1
+ export declare function cutPrefix(str: string, prefix: string): string;
@@ -0,0 +1,5 @@
1
+ export function cutPrefix(str, prefix) {
2
+ return str.startsWith(prefix)
3
+ ? str.slice(prefix.length)
4
+ : str;
5
+ }
@@ -1,5 +1,8 @@
1
+ import { compressFormat } from './compress.js';
1
2
  export declare const template: {
2
- base(script: string, format: string, useBase128: boolean): string;
3
+ base(script: string, format: compressFormat, useBase128: boolean): string;
3
4
  assets(assetsJSON: string): string;
4
- resolve: string;
5
+ css(cssSource: string): string;
6
+ icon(dataURL: string): string;
7
+ importmeta(p: string): string;
5
8
  };
@@ -1,13 +1,26 @@
1
1
  import fs from 'fs';
2
2
  import { fileURLToPath } from 'url';
3
+ import { compress } from './compress.js';
4
+ function r(name) {
5
+ return fs.readFileSync(fileURLToPath(import.meta.resolve(`./template/${name}.js`))).toString();
6
+ }
7
+ function rt(name, template) {
8
+ const s = r(name).split(template, 2);
9
+ if (s.length !== 2)
10
+ throw "s.length!==2";
11
+ return s;
12
+ }
3
13
  const files = {
4
- base64: fs.readFileSync(fileURLToPath(import.meta.resolve("./template/base64.js"))).toString(),
5
- base128: fs.readFileSync(fileURLToPath(import.meta.resolve("./template/base128.js"))).toString(),
6
- assets: fs.readFileSync(fileURLToPath(import.meta.resolve("./template/assets.js"))).toString().split('{"":""}', 2),
7
- resolve: fs.readFileSync(fileURLToPath(import.meta.resolve("./template/resolve.js"))).toString(),
14
+ base64: r('base64'),
15
+ base128: r('base128'),
16
+ assets: rt('assets', '{"":""}'),
17
+ css: rt('css', '"<style>"'),
18
+ icon: rt('icon', '"<icon>"'),
19
+ importmeta: rt('importmeta', '"<path>"'),
8
20
  };
9
21
  export const template = {
10
22
  base(script, format, useBase128) {
23
+ script = compress(format, script, useBase128);
11
24
  if (useBase128) {
12
25
  return files.base128
13
26
  .replace("<format>", format)
@@ -20,5 +33,13 @@ export const template = {
20
33
  assets(assetsJSON) {
21
34
  return files.assets.join(assetsJSON);
22
35
  },
23
- resolve: files.resolve,
36
+ css(cssSource) {
37
+ return files.css.join(JSON.stringify(cssSource));
38
+ },
39
+ icon(dataURL) {
40
+ return files.icon.join(JSON.stringify(dataURL));
41
+ },
42
+ importmeta(p) {
43
+ return files.importmeta.join(JSON.stringify(p));
44
+ },
24
45
  };
package/dist/index.js CHANGED
@@ -6,10 +6,10 @@ import fs from 'fs';
6
6
  import { pathToFileURL } from "url";
7
7
  import { version } from './getVersion.js';
8
8
  import { template } from './getTemplate.js';
9
- import { compress } from "./compress.js";
10
9
  import { bufferToDataURL } from "./dataurl.js";
11
10
  import { KiB } from "./KiB.js";
12
11
  import { getInnerOptions } from "./options.js";
12
+ import { cutPrefix } from "./cutPrefix.js";
13
13
  export function singleFileCompression(opt) {
14
14
  let conf;
15
15
  return {
@@ -22,19 +22,16 @@ export function singleFileCompression(opt) {
22
22
  }
23
23
  export default singleFileCompression;
24
24
  function setConfig(config) {
25
- config.base = './';
25
+ config.base ??= './';
26
26
  config.build ??= {};
27
- // config.build.assetsDir = 'assets'
28
- config.build.cssCodeSplit = false;
27
+ config.build.cssCodeSplit ??= false;
29
28
  config.build.assetsInlineLimit ??= () => true;
30
29
  config.build.chunkSizeWarningLimit ??= Number.MAX_SAFE_INTEGER;
31
30
  config.build.modulePreload ??= { polyfill: false };
32
- // config.build.target ??= 'esnext'
33
31
  config.build.reportCompressedSize ??= false;
34
32
  config.build.rollupOptions ??= {};
35
- config.build.rollupOptions.output ??= {};
36
- for (const output of [config.build.rollupOptions.output].flat(1)) {
37
- output.inlineDynamicImports = true;
33
+ for (const output of [config.build.rollupOptions.output ??= {}].flat(1)) {
34
+ output.inlineDynamicImports ??= true;
38
35
  }
39
36
  }
40
37
  async function generateBundle(bundle, config, options) {
@@ -48,23 +45,19 @@ async function generateBundle(bundle, config, options) {
48
45
  bundle[options.rename].fileName = options.rename;
49
46
  delete bundle["index.html"];
50
47
  }
51
- const distURL = pathToFileURL(config.build.outDir).href + '/';
48
+ const distURL = pathToFileURL(config.build.outDir).href + '/',
52
49
  /** "assets/" */
53
- const assetsDir = path.posix.join(config.build.assetsDir, '/');
50
+ assetsDir = path.posix.join(config.build.assetsDir, '/'),
51
+ /** "./assets/" */
52
+ assetsDirWithBase = config.base + assetsDir,
54
53
  /** '[href^="./assets/"]' */
55
- const assetsHrefSelector = `[href^="./${assetsDir}"]`;
54
+ assetsHrefSelector = `[href^="${assetsDirWithBase}"]`,
56
55
  /** '[src^="./assets/"]' */
57
- const assetsSrcSelector = `[src^="./${assetsDir}"]`;
58
- const fakeScript = `_vitePluginSinglefileCompression(${Date.now()})`;
59
- const globalDelete = new Set();
60
- const globalDoNotDelete = new Set();
61
- const globalRemoveDistFileNames = new Set();
62
- const globalAssetsDataURL = {};
63
- const globalPublicFilesCache = {};
64
- /** fotmat: ["assets/index-XXXXXXXX.js"] */
65
- const bundleAssetsNames = [];
56
+ assetsSrcSelector = `[src^="${assetsDirWithBase}"]`, fakeScript = `_vitePluginSinglefileCompression(${Date.now()})`, globalDelete = new Set(), globalDoNotDelete = new Set(), globalRemoveDistFileNames = new Set(), globalAssetsDataURL = {}, globalPublicFilesCache = {},
57
+ /** format: ["assets/index-XXXXXXXX.js"] */
58
+ bundleAssetsNames = [],
66
59
  /** format: ["index.html"] */
67
- const bundleHTMLNames = [];
60
+ bundleHTMLNames = [];
68
61
  for (const name of Object.keys(bundle)) {
69
62
  if (name.startsWith(assetsDir))
70
63
  bundleAssetsNames.push(name);
@@ -72,50 +65,46 @@ async function generateBundle(bundle, config, options) {
72
65
  bundleHTMLNames.push(name);
73
66
  }
74
67
  for (const htmlFileName of bundleHTMLNames) {
68
+ console.log("\n " + pc.underline(pc.cyan(distURL) + pc.greenBright(bundle[htmlFileName].fileName)));
75
69
  // init
76
- const htmlChunk = bundle[htmlFileName];
77
- const oldHTML = htmlChunk.source;
70
+ const htmlChunk = bundle[htmlFileName], oldHTML = htmlChunk.source, dom = new JSDOM(oldHTML), document = dom.window.document, thisDel = new Set(), newJSCode = [], scriptElement = document.querySelector(`script[type=module]${assetsSrcSelector}`), scriptName = scriptElement ? cutPrefix(scriptElement.src, config.base) : '';
78
71
  let oldSize = oldHTML.length;
79
- const dom = new JSDOM(oldHTML);
80
- const document = dom.window.document;
81
- const scriptElement = document.querySelector(`script[type=module]${assetsSrcSelector}`);
82
- if (!scriptElement) {
83
- console.error(`Error: Can not find script tag from ${htmlFileName}`);
84
- continue;
72
+ // fill fake script
73
+ if (scriptElement) {
74
+ scriptElement.remove();
75
+ scriptElement.removeAttribute('src');
76
+ scriptElement.innerHTML = fakeScript;
77
+ document.body.appendChild(scriptElement);
78
+ }
79
+ else {
80
+ document.body.insertAdjacentHTML('beforeend', `<script type="module">${fakeScript}</script>`);
85
81
  }
86
- const thisDel = new Set();
87
- // Fix async import
88
- const newJSCode = ["self.__VITE_PRELOAD__=void 0"];
89
82
  // get css tag
90
- {
91
- const element = document.querySelector(`link[rel=stylesheet]${assetsHrefSelector}`);
92
- if (element) {
93
- const name = element.href.slice("./".length);
94
- thisDel.add(name);
95
- const css = bundle[name];
96
- const cssSource = css.source;
97
- if (cssSource) {
98
- oldSize += cssSource.length;
99
- // do not delete not inlined asset
100
- for (const name of bundleAssetsNames) {
101
- if (cssSource.includes(name.slice(assetsDir.length)))
102
- globalDoNotDelete.add(name);
103
- }
104
- // add script for load css
105
- newJSCode.push(
106
- // 'document.querySelector("script[type=module]").insertAdjacentElement("afterend",document.createElement("style")).innerHTML='
107
- 'document.head.appendChild(document.createElement("style")).innerHTML='
108
- + JSON.stringify(cssSource.replace(/\n$/, '')));
83
+ let allCSS = '';
84
+ for (const element of document.querySelectorAll(`link[rel=stylesheet]${assetsHrefSelector}`)) {
85
+ const name = cutPrefix(element.href, config.base);
86
+ thisDel.add(name);
87
+ const css = bundle[name];
88
+ const cssSource = css.source;
89
+ if (cssSource) {
90
+ oldSize += cssSource.length;
91
+ // do not delete not inlined asset
92
+ for (const name of bundleAssetsNames) {
93
+ if (cssSource.includes(name.slice(assetsDir.length)))
94
+ globalDoNotDelete.add(name);
109
95
  }
110
- // delete tag
111
- element.remove();
96
+ // add script for load css
97
+ allCSS += cssSource.replace(/\n$/, '');
112
98
  }
99
+ // remove tag
100
+ element.remove();
113
101
  }
102
+ newJSCode.push(template.css(allCSS));
114
103
  // inline html assets
115
104
  const assetsDataURL = {};
116
105
  if (options.tryInlineHtmlAssets) {
117
106
  for (const element of document.querySelectorAll(assetsSrcSelector)) {
118
- const name = element.src.slice(`./${assetsDir}`.length);
107
+ const name = cutPrefix(element.src, assetsDirWithBase);
119
108
  if (name.endsWith('.js'))
120
109
  continue;
121
110
  if (!Object.hasOwn(assetsDataURL, name)) {
@@ -139,9 +128,9 @@ async function generateBundle(bundle, config, options) {
139
128
  let needInline = true;
140
129
  let iconName = 'favicon.ico';
141
130
  // replace tag
142
- const element = document.querySelector('link[rel=icon][href^="./"], link[rel="shortcut icon"][href^="./"]');
131
+ const element = document.querySelector(`link[rel=icon][href^="${config.base}"], link[rel="shortcut icon"][href^="${config.base}"]`);
143
132
  if (element) {
144
- iconName = element.href.slice("./".length);
133
+ iconName = cutPrefix(element.href, config.base);
145
134
  if (bundleAssetsNames.includes(iconName)) {
146
135
  needInline = false;
147
136
  }
@@ -172,7 +161,7 @@ async function generateBundle(bundle, config, options) {
172
161
  }
173
162
  const { dataURL, size } = globalPublicFilesCache[iconName];
174
163
  oldSize += size;
175
- newJSCode.push('document.querySelector("link[rel=icon]").href=' + JSON.stringify(dataURL));
164
+ newJSCode.push(template.icon(dataURL));
176
165
  if (!element) {
177
166
  // add link icon tag
178
167
  document.head.insertAdjacentHTML('beforeend', '<link rel="icon" href="data:">');
@@ -184,48 +173,47 @@ async function generateBundle(bundle, config, options) {
184
173
  }
185
174
  }
186
175
  }
187
- // script
188
- {
189
- const name = scriptElement.src.slice("./".length);
190
- thisDel.add(name);
191
- const js = bundle[name];
192
- oldSize += js.code.length;
193
- // fix new URL
194
- newJSCode.push(`import.meta.url=new URL(${JSON.stringify(name)},location).href`);
195
- // fix import.meta.resolve
196
- newJSCode.push(template.resolve);
176
+ // generate html
177
+ htmlChunk.source = dom.serialize();
178
+ // minify html
179
+ if (options.htmlMinifierTerser)
180
+ htmlChunk.source = await htmlMinify(htmlChunk.source, options.htmlMinifierTerser);
181
+ // fill script
182
+ function inlineHtmlAssets() {
183
+ if (options.tryInlineHtmlAssets) {
184
+ // add script for load html assets
185
+ const assetsJSON = JSON.stringify(assetsDataURL);
186
+ if (assetsJSON !== '{}')
187
+ newJSCode.push(template.assets(assetsJSON));
188
+ }
189
+ }
190
+ if (scriptElement) {
191
+ thisDel.add(scriptName);
192
+ let { code } = bundle[scriptName];
193
+ oldSize += code.length;
194
+ code = code.replace(/;?\n?$/, '');
197
195
  // do not delete not inlined asset
198
196
  for (const name of bundleAssetsNames) {
199
197
  const assetName = name.slice(assetsDir.length);
200
- if (js.code.includes(assetName)) {
198
+ if (code.includes(assetName)) {
201
199
  globalDoNotDelete.add(name);
202
200
  delete assetsDataURL[assetName];
203
201
  }
204
202
  }
205
- if (options.tryInlineHtmlAssets) {
206
- // add script for load html assets
207
- const assetsJSON = JSON.stringify(assetsDataURL);
208
- if (assetsJSON != '{}')
209
- newJSCode.push(template.assets(assetsJSON));
210
- }
211
- // add script
212
- newJSCode.push(js.code.replace(/;?\n?$/, ''));
203
+ inlineHtmlAssets();
204
+ newJSCode.push(template.importmeta(scriptName));
205
+ // polyfill 仅在以下选项的值为 true 时需要。
206
+ // config.build.rollupOptions.output.inlineDynamicImports
207
+ if (code.includes("__VITE_PRELOAD__"))
208
+ newJSCode.push("var __VITE_PRELOAD__");
209
+ newJSCode.push(code);
213
210
  }
214
- // fill fake script
215
- scriptElement.removeAttribute('src');
216
- scriptElement.removeAttribute('crossorigin');
217
- scriptElement.innerHTML = fakeScript;
218
- // generate html
219
- htmlChunk.source = dom.serialize();
220
- // minify html
221
- if (options.htmlMinifierTerser)
222
- htmlChunk.source = await htmlMinify(htmlChunk.source, options.htmlMinifierTerser);
223
- // fill script
224
- htmlChunk.source = htmlChunk.source.split(fakeScript, 2).join(template.base(compress(options.compressFormat, newJSCode.join(';'), options.useBase128), options.compressFormat, options.useBase128));
211
+ else {
212
+ inlineHtmlAssets();
213
+ }
214
+ htmlChunk.source = htmlChunk.source.split(fakeScript, 2).join(template.base(newJSCode.join(';'), options.compressFormat, options.useBase128));
225
215
  // log
226
- console.log("\n"
227
- + " " + pc.underline(pc.cyan(distURL) + pc.greenBright(bundle[htmlFileName].fileName)) + '\n'
228
- + " " + pc.gray(KiB(oldSize) + " -> ") + pc.cyanBright(KiB(htmlChunk.source.length)) + '\n');
216
+ console.log(" " + pc.gray(KiB(oldSize) + " -> ") + pc.cyanBright(KiB(htmlChunk.source.length)) + '\n');
229
217
  // delete assets
230
218
  for (const name of thisDel) {
231
219
  globalDelete.add(name);
@@ -250,5 +238,5 @@ async function generateBundle(bundle, config, options) {
250
238
  }
251
239
  }
252
240
  }
253
- console.log(pc.green('Finish.\n'));
241
+ console.log(pc.green('Finish.') + pc.reset('\n'));
254
242
  }
@@ -0,0 +1 @@
1
+ document.head.appendChild(document.createElement("style")).innerHTML="<style>"
@@ -0,0 +1 @@
1
+ document.querySelector("link[rel=icon]").href="<icon>"
@@ -0,0 +1 @@
1
+ {import.meta.url=new URL("<path>",location).href;let t=import.meta.resolve;import.meta.resolve=e=>/^\.{0,2}\//.test(e)?new URL(e,import.meta.url).href:t(e)}
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "vite-plugin-singlefile-compression",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
+ "author": "bddjr",
5
+ "license": "MIT",
6
+ "description": "",
4
7
  "main": "dist/index.js",
5
- "typings": "dist/index.d.ts",
8
+ "types": "dist/index.d.ts",
6
9
  "files": [
7
10
  "dist"
8
11
  ],
@@ -11,9 +14,6 @@
11
14
  "build": "rimraf dist && tsc && node build.js && cd test && npm run build",
12
15
  "prepublishOnly": "npm run build"
13
16
  },
14
- "author": "bddjr",
15
- "license": "MIT",
16
- "description": "",
17
17
  "repository": {
18
18
  "type": "git",
19
19
  "url": "git+https://github.com/bddjr/vite-plugin-singlefile-compression.git"
@@ -1,24 +0,0 @@
1
- This is free and unencumbered software released into the public domain.
2
-
3
- Anyone is free to copy, modify, publish, use, compile, sell, or
4
- distribute this software, either in source code form or as a compiled
5
- binary, for any purpose, commercial or non-commercial, and by any
6
- means.
7
-
8
- In jurisdictions that recognize copyright laws, the author or authors
9
- of this software dedicate any and all copyright interest in the
10
- software to the public domain. We make this dedication for the benefit
11
- of the public at large and to the detriment of our heirs and
12
- successors. We intend this dedication to be an overt act of
13
- relinquishment in perpetuity of all present and future rights to this
14
- software under copyright law.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
- IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
- OTHER DEALINGS IN THE SOFTWARE.
23
-
24
- For more information, please refer to <https://unlicense.org/>
@@ -1 +0,0 @@
1
- {let t=import.meta.resolve;import.meta.resolve=e=>/^\.{0,2}\//.test(e)?new URL(e,import.meta.url).href:t(e)}