Skip to content

Commit

Permalink
feat: support cacheDir and base
Browse files Browse the repository at this point in the history
1. improveDX, make manifest.json invisible, write file to `node_modules/.vite-plugin-public-typescript` by default. export some interface for devs to use the manifest

2. `inject-script` has built-in manifest support now. users dont need to manually import manifest from real file anymore

3. if users dont pass in the `base` field, plugin will use the `base` of vite config by default

4. split code, make the source code clearer
  • Loading branch information
hemengke1997 committed Oct 29, 2023
1 parent 70a0dd3 commit faabab8
Show file tree
Hide file tree
Showing 46 changed files with 455 additions and 324 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ concurrency:

jobs:
deploy:
if: "contains(github.event.head_commit.message, 'deploy')"
if: contains(github.event.head_commit.message, 'release') || contains(github.event.head_commit.message, 'deploy')
runs-on: ubuntu-latest
steps:
- name: Checkout
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ jobs:
key: ${{ runner.os }}-playwright-bin-v1
path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }}

- name: Install Playwright
# does not need to explicitly set chromium after https://github.com/microsoft/playwright/issues/14862 is solved
run: pnpx playwright install chromium

- name: Build
run: pnpm run build

Expand Down
57 changes: 36 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

![npm][npm-img]

<!-- **中文** | [English](./README.md) -->

**在vite的运行时或构建时编译指定目录下的typescript文件,供开发者独立使用**

Expand All @@ -26,12 +25,13 @@

## 功能

- 运行时和构建时,把指定文件夹中的 `typescript` 文件编译为 `javascript`,供浏览器直接使用
- 输出带有 `hash` 的js文件,无需担心缓存
- 自定义编译选项,指定目标浏览器范围,无需担心兼容性
- 支持 `vite` 环境变量
- 支持 `HMR`
- 支持不同的输出方式(内存模式和文件模式)
- 支持 `CSR``SSR` 应用


## 安装

Expand All @@ -41,24 +41,27 @@ pnpm add vite-plugin-public-typescript -D

## 配置项

| 参数 | 类型 | 默认值 | 描述 |
| -------------- | -------------- | ------------------- | ---------------------------------------------- |
| inputDir | `string` | `public-typescript` | 存放需要编译的 `typescript` 的目录 |
| outputDir | `string` | `/` | 输出公共 javascript 的目录,相对于 `publicDir` |
| manifestName | `string` | `manifest` | `manifest` 的文件名 |
| hash | `boolean` | `true` | 编译后的 `js` 是否生成 `hash ` |
| esbuildOptions | `BuildOptions` | `{}` | esbuild 构建选项 |
| ssrBuild | `boolean` | `false` | 当前打包环境是否是 ssr |
| sideEffects | `boolean` | `false` |`typescript` 文件中有导入第三方库,则开启 |
| destination | `string` | `memory` | 输出模式:内存模式 \| 文件模式 |
| 参数 | 类型 | 默认值 | 描述 |
| -------------- | -------------- | --------------------------------------------- | ---------------------------------------------- |
| inputDir | `string` | `public-typescript` | 存放需要编译的 `typescript` 的目录 |
| outputDir | `string` | `/` | 输出公共 javascript 的目录,相对于 `publicDir` |
| manifestName | `string` | `manifest` | `manifest` 的文件名 |
| hash | `boolean` | `true` | 编译后的 `js` 是否生成 `hash ` |
| esbuildOptions | `BuildOptions` | `{}` | esbuild 构建选项 |
| ssrBuild | `boolean` | `false` | 当前打包环境是否是 ssr |
| sideEffects | `boolean` | `true` | 是否编译三方库 |
| destination | `string` | `memory` | 输出模式:内存模式 \| 文件模式 |
| cacheDir | `string` | `node_modules/.vite-plugin-public-typescript` | 存放manifest缓存的目录 |
| base | `string` | vite config 中的 `base` | 资源 base url |




## 用法

```typescript
import { defineConfig } from 'vite'
import { publicTypescript, injectScripts } from 'vite-plugin-public-typescript'
import manifest from './public-typescript/manifest.json'

export default defineConfig({
plugins: [
Expand All @@ -69,7 +72,7 @@ export default defineConfig({
outputDir: '/out',
destination: 'memory',
}),
injectScripts([
injectScripts((manifest) => [
{
attrs: {
src: manifest.script,
Expand All @@ -81,6 +84,14 @@ export default defineConfig({
})
```

### 获取manifest

```typescript
import { manifest } from 'vite-plugin-public-typescript/client'

console.log(manifest)
```


### SPA

Expand All @@ -94,12 +105,11 @@ export default defineConfig({
import type { HtmlTagDescriptor } from 'vite'
import { defineConfig } from 'vite'
import { publicTypescript, injectScripts } from 'vite-plugin-public-typescript'
import manifest from './public-typescript/manifest.json'

export default defineConfig({
plugins: [
publicTypescript(),
injectScripts([
injectScripts((manifest) => [
{
attrs: {
src: manifest.spa,
Expand Down Expand Up @@ -133,11 +143,16 @@ export default defineConfig({
#### server.js

```js
import manifest from './public-typescript/manifest.json'

const html = template
// inject js
.replace('<!--app-prehead-->', `<script src=${manifest.ssr}></script>`)
import { injectScriptsToHtml } from 'vite-plugin-public-typescript'

html = injectScriptsToHtml(html, (manifest) => [
{
attrs: {
src: manifest.ssr,
},
injectTo: 'head-prepend',
},
])
```


Expand Down
33 changes: 23 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,26 @@
"README.md",
"dist"
],
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"main": "./dist/node/index.cjs",
"module": "./dist/node/index.js",
"types": "./dist/node/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.cjs",
"import": "./dist/index.js"
"types": "./dist/node/index.d.ts",
"require": "./dist/node/index.cjs",
"import": "./dist/node/index.js"
},
"./client": {
"types": "./dist/client/index.d.ts",
"require": "./dist/client/index.cjs",
"import": "./dist/client/index.js"
}
},
"typesVersions": {
"*": {
"client": [
"./dist/client/index.d.ts"
]
}
},
"scripts": {
Expand Down Expand Up @@ -57,14 +69,15 @@
"magic-string": "^0.30.5",
"on-change": "^4.0.2",
"parse5": "^7.1.2",
"picocolors": "^1.0.0",
"tiny-glob": "^0.2.9",
"watcher": "^2.3.0"
},
"devDependencies": {
"@commitlint/cli": "^18.0.0",
"@minko-fe/commitlint-config": "^2.0.2",
"@minko-fe/eslint-config": "^2.0.2",
"@minko-fe/tsconfig": "^2.0.2",
"@minko-fe/commitlint-config": "^2.0.4",
"@minko-fe/eslint-config": "^2.0.4",
"@minko-fe/tsconfig": "^2.0.4",
"@types/debug": "^4.1.9",
"@types/fs-extra": "^11.0.2",
"@types/node": "^20.8.6",
Expand All @@ -75,7 +88,7 @@
"npm-run-all": "^4.1.5",
"simple-git-hooks": "^2.9.0",
"taze": "^0.11.4",
"tsup": "^7.2.0",
"tsup": "^7.0.0",
"typescript": "^5.2.2",
"vite": "^4.4.11",
"vitest": "^0.34.5",
Expand Down
5 changes: 0 additions & 5 deletions playground/spa-file-mode/public-typescript/manifest.json

This file was deleted.

1 change: 1 addition & 0 deletions playground/spa-file-mode/public/out/define.0852dc5a.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(()=>{var o={hello:"world"};window.VITE_DEFINE={};window.VITE_DEFINE["custom-define"]="custom define!";window.VITE_DEFINE["hello-world"]=o;})();
1 change: 1 addition & 0 deletions playground/spa-file-mode/public/out/env.e6648627.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(()=>{var e={VITE_ENV_FROM_ENVFILE:"imfromdotenv",BASE_URL:"/vite-plugin-public-typescript/",MODE:"development",DEV:!0,PROD:!1};window.VITE_ENV=e;})();
1 change: 1 addition & 0 deletions playground/spa-file-mode/public/out/hmr.c01ee876.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(()=>{console.log("hmr");window.hmr="hmr original text";})();
4 changes: 2 additions & 2 deletions playground/spa-file-mode/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { type ReactNode, useEffect, useState } from 'react'
import manifest from '../public-typescript/manifest.json'
import { manifest } from 'vite-plugin-public-typescript/client'
import './App.css'

function formatManifst() {
return Object.keys(manifest).map((key) => (
<div key={key} style={{ display: 'flex' }}>
<div>文件 {key}.ts 的 js uri 是:</div>
<div>{(manifest as Record<string, string>)[key]}</div>
<div>{manifest[key]}</div>
</div>
))
}
Expand Down
3 changes: 1 addition & 2 deletions playground/spa-file-mode/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import { injectScripts, publicTypescript } from 'vite-plugin-public-typescript'
import manifest from './public-typescript/manifest.json'

// https://vitejs.dev/config/
export default defineConfig(() => ({
Expand All @@ -19,7 +18,7 @@ export default defineConfig(() => ({
outputDir: 'out',
destination: 'file',
}),
injectScripts([
injectScripts((manifest) => [
{
attrs: { src: manifest.hmr },
injectTo: 'body',
Expand Down
8 changes: 5 additions & 3 deletions playground/spa/__tests__/spa.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import { beforeAll, describe, expect, test } from 'vitest'

const hmrOriginText = 'hmr original text'

const manifestPath = 'node_modules/.vite-plugin-public-typescript/manifest.json'

describe('console', async () => {
test('should console hmr string', async () => {
await untilBrowserLogAfter(() => page.goto(viteTestUrl), 'hmr')
Expand Down Expand Up @@ -47,7 +49,7 @@ describe('manifest', () => {
let manifest: string
beforeAll(() => {
try {
manifest = readFile('public-typescript/manifest.json')
manifest = readFile(manifestPath)
} catch {}
})

Expand All @@ -62,7 +64,7 @@ describe('manifest', () => {
})

test.runIf(isServe)('should not trigger vite server restart when manifest file changed', async () => {
editFile('public-typescript/manifest.json', (content) => content)
editFile(manifestPath, (content) => content)
await withRetry(async () => {
expect(serverLogs).not.toEqual(expect.arrayContaining([expect.stringMatching('server restarted')]))
expect(serverLogs).not.toEqual(expect.arrayContaining([expect.stringMatching('error')]))
Expand All @@ -75,7 +77,7 @@ describe.skipIf(isServe)('build', () => {
let manifest: string
beforeAll(() => {
try {
manifest = readFile('public-typescript/manifest.json')
manifest = readFile(manifestPath)
jsFiles = listFiles('dist/out')
} catch {}
})
Expand Down
5 changes: 0 additions & 5 deletions playground/spa/public-typescript/manifest.json

This file was deleted.

4 changes: 2 additions & 2 deletions playground/spa/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { type ReactNode, useEffect, useState } from 'react'
import manifest from '../public-typescript/manifest.json'
import { manifest } from 'vite-plugin-public-typescript/client'
import './App.css'

function formatManifst() {
return Object.keys(manifest).map((key) => (
<div key={key} style={{ display: 'flex' }}>
<div>文件 {key}.ts 的 js uri 是:</div>
<div>{(manifest as Record<string, string>)[key]}</div>
<div>{manifest[key]}</div>
</div>
))
}
Expand Down
7 changes: 5 additions & 2 deletions playground/spa/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@
font-size: 16px;
line-height: 24px;
font-weight: 400;

color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;

font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
Expand All @@ -20,6 +18,7 @@ a {
color: #646cff;
text-decoration: inherit;
}

a:hover {
color: #535bf2;
}
Expand Down Expand Up @@ -48,9 +47,11 @@ button {
cursor: pointer;
transition: border-color 0.25s;
}

button:hover {
border-color: #646cff;
}

button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
Expand All @@ -61,9 +62,11 @@ button:focus-visible {
color: #213547;
background-color: #ffffff;
}

a:hover {
color: #747bff;
}

button {
background-color: #f9f9f9;
}
Expand Down
6 changes: 3 additions & 3 deletions playground/spa/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import { injectScripts, publicTypescript } from 'vite-plugin-public-typescript'
import manifest from './public-typescript/manifest.json'

// https://vitejs.dev/config/
export default defineConfig(() => ({
Expand All @@ -18,8 +17,9 @@ export default defineConfig(() => ({
hash: true,
outputDir: 'out',
destination: 'memory',
cacheDir: 'node_modules/.vite-plugin-public-typescript',
}),
injectScripts([
injectScripts((manifest) => [
{
attrs: { src: manifest.hmr },
injectTo: 'body',
Expand All @@ -38,5 +38,5 @@ export default defineConfig(() => ({
},
]),
],
clearScreen: true,
clearScreen: false,
}))
3 changes: 0 additions & 3 deletions playground/ssr/public-typescript/manifest.json

This file was deleted.

Loading

0 comments on commit faabab8

Please sign in to comment.