Skip to content

Commit

Permalink
export type helper function and type optimization (nonzzz#59)
Browse files Browse the repository at this point in the history
* feat: expose a define helper

* chore: migrate to vitest

* test: init type-check test

* chore: fix ci

* chore: fix patches

* chore: fix workflow

* chore: clean example

* docs: morve faq

* feat: add publish workflow

* chore: fix type

* chore: expose

* chore: fmt

* chore: fallback v20

---------

Co-authored-by: mengdaoshizhongxinyang <[email protected]>
  • Loading branch information
nonzzz and mengdaoshizhongxinyang authored Jul 21, 2024
1 parent a0e477c commit bf1f8ed
Show file tree
Hide file tree
Showing 33 changed files with 1,783 additions and 2,558 deletions.
8 changes: 2 additions & 6 deletions .github/workflows/e2e-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,9 @@ jobs:
with:
node-version: ${{ matrix.version }}
- name: Install berry
run: corepack enable

- name: install dependices
run: yarn

- name: test 2.x to 4.x
run: yarn ava e2e/vite[2-4]/**/*.spec.ts
run: yarn exec vitest e2e/vite[2-4]/*.spec.ts --coverage.enabled=false
run-stable-e2e-test:
strategy:
matrix:
Expand All @@ -38,7 +34,7 @@ jobs:
run: yarn

- name: test 5.x
run: yarn ava e2e/vite5/**/*.spec.ts
run: yarn exec vitest e2e/vite5/*.spec.ts --coverage.enabled=false



27 changes: 27 additions & 0 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: publish
on:
push:
tags: ['v*']

jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Install Berry
run: corepack enable
- name: Install Dependices
run: yarn
- name: Pack and Publish
run: |
yarn build
npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
4 changes: 2 additions & 2 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ jobs:
run: corepack enable
- uses: actions/setup-node@v3
with:
node-version: 22
node-version: 20
- name: Install Dependices
run: yarn install

- name: Run Test
run: yarn test

- name: Report Coverage
uses: codecov/codecov-action@v2
uses: codecov/codecov-action@v2
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ dist
temp
types
.tmpl
.tmp
tmp
.dist
coverage

Expand All @@ -12,4 +14,6 @@ yarn-error.log*
.yarn/cache
.yarn/install-state.gz

.DS_Store
.DS_Store

tsconfig.vitest-temp.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
diff --git a/node_modules/vite/dist/node/chunks/dep-689425f3.js b/node_modules/vite/dist/node/chunks/dep-689425f3.js
index babf8d5..019289d 100644
--- a/node_modules/vite/dist/node/chunks/dep-689425f3.js
+++ b/node_modules/vite/dist/node/chunks/dep-689425f3.js
diff --git a/dist/node/chunks/dep-689425f3.js b/dist/node/chunks/dep-689425f3.js
index babf8d5f63131b54ee2fca88a707db4ff3681448..019289dab7de9a08d1f94c3a6ad7fc90f6c0e3c7 100644
--- a/dist/node/chunks/dep-689425f3.js
+++ b/dist/node/chunks/dep-689425f3.js
@@ -38271,7 +38271,7 @@ const isModernFlag = `__VITE_IS_MODERN__`;
const preloadMethod = `__vitePreload`;
const preloadMarker = `__VITE_PRELOAD__`;
Expand Down
20 changes: 20 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
install:
@echo "Setup yarn package manager..."
@corepack enable
yarn install

build:
@echo "Building..."
@yarn exec rollup --config rollup.config.ts --configPlugin swc3

dev:
@echo "Starting development server..."
@yarn exec rollup --config rollup.config.ts --configPlugin swc3 --watch

test:
@echo "Running tests..."
@yarn exec vitest --dir __tests__ --typecheck.enabled

end-to-end-test:
@echo "Running end-to-end tests..."
@yarn exec vitest --dir e2e
55 changes: 55 additions & 0 deletions Q&A.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Q & A

> What is this plugin do?
- It's a simple zlib binding for vite, No a code compressor or a mangle. It help you compress your bundle assets in your local machine to save your precious server memory.

> How do i know if i need this plugin?
- Normally, You won't need it for most scenes. Follow the previous answer we know we only using it to compress us bundle asset in client,
So if some other clould server provider provide the smae server, you don't need it.

> How can i use it?
- There are two step. 1, install this plugin and add it into your vite config then build your application, upload your bundle assets to your server.
2, Makesure you have already using `tomcat` or `nginx` or others proxy server and find the relevant configuration tutorial. Like nignix, you can refer
[document](https://nginx.org/en/docs/http/ngx_http_gzip_module.html)

> Why `vite-plugin-compression2` not `vite-plugin-compression`?
- To be honest, It won't maintain anymore, So that i made a new one.

> How can i define a custom compression algorithm?
```ts

import { defineCompressionOption } from 'vite-plugin-compression2'
import { ZlibOption } from 'zlib'

const opt = defineCompressionOption<ZlibOption>({
// ...
})

```

> How can i generate multiple compressed assets with difference compression algorithm?
```ts

import { defineComponent } from 'vite'
import { compression } from 'vite-plugin-compression2'

export default defineComponent({
plugins: [
// ...your plugin
compression(),
compression({ algorithm: 'brotliCompress' })
]
})


```

> Can `tarball` be used only?
- Yes.
44 changes: 1 addition & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,49 +44,7 @@ export default defineConfig({

## Q & A

> Why not vite-plugin-compression
- `vite-plugin-compression` no longer maintenance.

> Why vite-plugin-compression2
- `vite-plugin-compression2` has minimal dependencies and better performance.

> Can i custom the compression algorithm?
- Yes, you can see the unit test case.

> Can i generate multiple compressed assets with difference compression algorithm?
```js
import { defineComponent } from 'vite'
import { compression } from 'vite-plugin-compression2'

export default defineComponent({
plugins: [
// ...your plugin
compression(),
compression({ algorithm: 'brotliCompress' })
]
})
```

> Can i create a tarball for all of assets after compressed?
- Yes, you can import `tarball` plugin from this package(>=1.0.0)

```js
import { defineComponent } from 'vite'
import { compression, tarball } from 'vite-plugin-compression2'

export default defineComponent({
plugins: [
// ...your plugin
compression(),
tarball()
]
})
```
[FAQ](./Q&A.md)

### Others

Expand Down
14 changes: 3 additions & 11 deletions __tests__/compress.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { InputType } from 'zlib'
import test from 'ava'
import { expect, test } from 'vitest'
import { compress, ensureAlgorithm } from '../src/compress'
import type { Algorithm } from '../src/interface'

Expand All @@ -8,16 +8,8 @@ const mockCompress = async (userAlgorithm: Algorithm, buf: InputType) => {
return compress(buf, algorithm, {})
}

test('transer', async (t) => {
const fake = new TextEncoder().encode('test')
await mockCompress('gzip', fake)
t.pass()
})

test('compress with error', async (t) => {
const msg = await t.throwsAsync(mockCompress('gzip', 123 as any))
t.is(
msg.message,
test('compress with error', async () => {
expect(mockCompress('gzip', 123 as any)).rejects.toThrowError(
'The "chunk" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received type number (123)'
)
})
37 changes: 18 additions & 19 deletions __tests__/options.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import path from 'path'
import fsp from 'fs/promises'
import test from 'ava'
import { afterAll, expect, test } from 'vitest'

// import { build } from 'vite'
import type { Pretty, ViteCompressionPluginConfigAlgorithm } from '../src/interface'
import { compression } from '../src'
import { readAll } from '../src/utils'
import { readAll } from '../src/shared'
import type { Algorithm } from '../src'

const getId = () => Math.random().toString(32).slice(2, 10)
const sleep = (delay: number) => new Promise((resolve) => setTimeout(resolve, delay))

let vite: typeof import('vite')

const tempPath = path.join(__dirname, 'tmp')
const tmplPath = path.join(__dirname, '.tmp')

async function mockBuild<T extends Algorithm = never>(
conf: Pretty<ViteCompressionPluginConfigAlgorithm<T>>,
dir: string,
Expand All @@ -25,8 +27,8 @@ async function mockBuild<T extends Algorithm = never>(
build: {
rollupOptions: {
output: !single
? [{ dir: path.join(__dirname, 'temp', id) }, { dir: path.join(__dirname, '.tmpl', id) }]
: { dir: path.join(__dirname, '.tmpl', id) }
? [{ dir: path.join(tempPath, id) }, { dir: path.join(tmplPath, id) }]
: { dir: path.join(tmplPath, id) }
}
},
root: path.join(__dirname, 'fixtures', dir),
Expand All @@ -36,49 +38,46 @@ async function mockBuild<T extends Algorithm = never>(
return id
}

const tempPath = path.join(__dirname, 'temp')
const tmplPath = path.join(__dirname, '.tmpl')

test.after(async () => {
afterAll(async () => {
await fsp.rm(tempPath, { recursive: true })
await fsp.rm(tmplPath, { recursive: true })
})

test('rollupOptions First', async (t) => {
test('rollupOptions First', async () => {
const id = await mockBuild({ deleteOriginalAssets: true, include: /\.(html)$/ }, 'dynamic')
await sleep(3000)
const r = await Promise.all([readAll(path.join(tempPath, id)), readAll(path.join(tmplPath, id))])
const gz = r.map((v) => v.filter((s) => s.endsWith('.gz')))
t.is(gz[0].length, 1)
t.is(gz[1].length, 1)
expect(gz[0].length).toBe(1)
expect(gz[1].length).toBe(1)
})

test('rollupOptions with single output', async (t) => {
test('rollupOptions with single output', async () => {
const id = await mockBuild({ deleteOriginalAssets: true, include: /\.(html)$/ }, 'dynamic', true)
await sleep(3000)
const r = await readAll(path.join(tmplPath, id))
const gz = r.filter((v) => v.endsWith('.gz'))
t.is(gz.length, 1)
expect(gz.length).toBe(1)
})

test('rollupOptions with multiple outputs', async (t) => {
test('rollupOptions with multiple outputs', async () => {
const id = await mockBuild({ deleteOriginalAssets: true, exclude: /\.(html)$/ }, 'public-assets-nest')
await sleep(3000)
const r = await readAll(path.join(tmplPath, id))
const gz = r.filter((v) => v.endsWith('.gz'))
t.is(gz.length, 6)
expect(gz.length).toBe(6)
const r2 = await readAll(path.join(tempPath, id))
const gz2 = r2.filter((v) => v.endsWith('.gz'))
t.is(gz2.length, 6)
expect(gz2.length).toBe(6)
})

test('skipIfLargerOrEqual', async (t) => {
test('skipIfLargerOrEqual', async () => {
const id = await mockBuild(
{ deleteOriginalAssets: true, exclude: /\.(html)$/, skipIfLargerOrEqual: true },
'optimization'
)
await sleep(3000)
const r = await readAll(path.join(tmplPath, id))
const gz = r.filter((v) => v.endsWith('.gz'))
t.is(gz.length, 2)
expect(gz.length).toBe(2)
})
Loading

0 comments on commit bf1f8ed

Please sign in to comment.