Skip to content

Commit

Permalink
Merge branch 'main' into localhost
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Mar 5, 2022
2 parents ee658d0 + 9f7b859 commit 0894932
Show file tree
Hide file tree
Showing 105 changed files with 2,355 additions and 834 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Expand Up @@ -44,7 +44,7 @@ jobs:
version: 6

- name: Set node version to ${{ matrix.node_version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node_version }}
cache: "pnpm"
Expand Down Expand Up @@ -82,7 +82,7 @@ jobs:
version: 6

- name: Set node version to 16
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: 16
cache: "pnpm"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Expand Up @@ -23,7 +23,7 @@ jobs:
version: 6

- name: Set node version to 16.x
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: 16.x
registry-url: https://registry.npmjs.org/
Expand Down
7 changes: 7 additions & 0 deletions .npmrc
@@ -0,0 +1,7 @@
hoist-pattern[]=*eslint*
hoist-pattern[]=*babel*
hoist-pattern[]=*jest*
hoist-pattern[]=@emotion/*
hoist-pattern[]=postcss
hoist-pattern[]=pug
hoist-pattern[]=source-map-support
1 change: 1 addition & 0 deletions .prettierignore
Expand Up @@ -10,3 +10,4 @@ pnpm-lock.yaml
pnpm-workspace.yaml
packages/playground/tsconfig-json-load-error/has-error/tsconfig.json
packages/playground/html/invalid.html
packages/playground/worker/classic-worker.js
16 changes: 16 additions & 0 deletions CONTRIBUTING.md
Expand Up @@ -28,6 +28,22 @@ If you want to use break point and explore code execution you can use the ["Run

5. The execution will stop and you'll use the [Debug toolbar](https://code.visualstudio.com/docs/editor/debugging#_debug-actions) to continue, step over, restart the process...

### Debugging errors in Jest tests using Playwright (Chromium)

Some errors are masked and hidden away because of the layers of abstraction and sandboxed nature added by Jest, Playwright, and Chromium. In order to see what's actually going wrong and the contents of the devtools console in those instances, follow this setup:

1. Add a `debugger` statement to the `scripts/jestPerTestSetup.ts` -> `afterAll` hook. This will pause execution before the tests quit and the Playwright browser instance exits.

1. Run the tests with the `debug-serve` script command which will enable remote debugging: `pnpm run debug-serve -- --runInBand resolve`.

1. Wait for inspector devtools to open in your browser and the debugger to attach.

1. In the sources panel in the right column, click the play button to resume execution and allow the tests to run which will open a Chromium instance.

1. Focusing the Chomium instance, you can open the browser devtools and inspect the console there to find the underlying problems.

1. To close everything, just stop the test process back in your terminal.

## Testing Vite against external packages

You may wish to test your locally-modified copy of Vite against another package that is built with Vite. For pnpm, after building Vite, you can use [`pnpm.overrides`](https://pnpm.io/package_json#pnpmoverrides). Please note that `pnpm.overrides` must be specified in the root `package.json` and you must first list the package as a dependency in the root `package.json`:
Expand Down
22 changes: 21 additions & 1 deletion docs/config/index.md
Expand Up @@ -96,6 +96,22 @@ export default defineConfig(async ({ command, mode }) => {
})
```

### Environment Variables

Vite doesn't load `.env` files by default as the files to load can only be determined after evaluating the Vite config, for example, the `root` and `envDir` options affects the loading behaviour. However, you can use the exported `loadEnv` helper to load the specific `.env` file if needed.

```js
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ command, mode }) => {
// Load env file based on `mode` in the current working directory
const env = loadEnv(mode, process.cwd())
return {
// build specific config
}
})
```

## Shared Options

### root
Expand Down Expand Up @@ -139,9 +155,11 @@ export default defineConfig(async ({ command, mode }) => {

- Replacements are performed only when the match is surrounded by word boundaries (`\b`).

::: warning
Because it's implemented as straightforward text replacements without any syntax analysis, we recommend using `define` for CONSTANTS only.

For example, `process.env.FOO` and `__APP_VERSION__` are good fits. But `process` or `global` should not be put into this option. Variables can be shimmed or polyfilled instead.
:::

::: tip NOTE
For TypeScript users, make sure to add the type declarations in the `env.d.ts` or `vite-env.d.ts` file to get type checks and Intellisense.
Expand Down Expand Up @@ -508,12 +526,14 @@ export default defineConfig(async ({ command, mode }) => {

### server.hmr

- **Type:** `boolean | { protocol?: string, host?: string, port?: number, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }`
- **Type:** `boolean | { protocol?: string, host?: string, port?: number | false, path?: string, timeout?: number, overlay?: boolean, clientPort?: number, server?: Server }`

Disable or configure HMR connection (in cases where the HMR websocket must use a different address from the http server).

Set `server.hmr.overlay` to `false` to disable the server error overlay.

Set `server.hmr.port` to `false` when connecting to a domain without a port.

`clientPort` is an advanced option that overrides the port only on the client side, allowing you to serve the websocket on a different port than the client code looks for it on. Useful if you're using an SSL proxy in front of your dev server.

When using `server.middlewareMode` or `server.https`, assigning `server.hmr.server` to your HTTP(S) server will process HMR connection requests through your server. This can be helpful when using self-signed certificates or when you want to expose Vite over a network on a single port.
Expand Down
16 changes: 16 additions & 0 deletions docs/guide/build.md
Expand Up @@ -43,6 +43,20 @@ module.exports = defineConfig({

For example, you can specify multiple Rollup outputs with plugins that are only applied during build.

## Chunking Strategy

You can configure how chunks are split using `build.rollupOptions.manualChunks` (see [Rollup docs](https://rollupjs.org/guide/en/#outputmanualchunks)). Until Vite 2.7, the default chunking strategy divided the chunks into `index` and `vendor`. It is a good strategy for some SPAs, but it is hard to provide a general solution for every Vite target use case. From Vite 2.8, `manualChunks` is no longer modified by default. You can continue to use the Split Vendor Chunk strategy by adding the `splitVendorChunkPlugin` in your config file:

```js
// vite.config.js
import { splitVendorChunkPlugin } from 'vite'
module.exports = defineConfig({
plugins: [splitVendorChunkPlugin()]
})
```

This strategy is also provided as a `splitVendorChunk({ cache: SplitVendorChunkCache })` factory, in case composition with custom logic is needed. `cache.reset()` needs to be called at `buildStart` for build watch mode to work correctly in this case.

## Rebuild on files changes

You can enable rollup watcher with `vite build --watch`. Or, you can directly adjust the underlying [`WatcherOptions`](https://rollupjs.org/guide/en/#watch-options) via `build.watch`:
Expand All @@ -58,6 +72,8 @@ module.exports = defineConfig({
})
```

With the `--watch` flag enabled, changes to the `vite.config.js`, as well as any files to be bundled, will trigger a rebuild.

## Multi-Page App

Suppose you have the following source code structure:
Expand Down
21 changes: 6 additions & 15 deletions packages/playground/assets/__tests__/assets.spec.ts
Expand Up @@ -8,8 +8,7 @@ import {
readManifest,
readFile,
editFile,
notifyRebuildComplete,
untilUpdated
notifyRebuildComplete
} from '../../testUtils'

const assetMatch = isBuild
Expand Down Expand Up @@ -38,7 +37,7 @@ describe('injected scripts', () => {

test('html-proxy', async () => {
const hasHtmlProxy = await page.$(
'script[type="module"][src^="/foo/index.html?html-proxy"]'
'script[type="module"][src="/foo/index.html?html-proxy&index=0.js"]'
)
if (isBuild) {
expect(hasHtmlProxy).toBeFalsy()
Expand Down Expand Up @@ -121,6 +120,10 @@ describe('css url() references', () => {
const match = isBuild ? `data:image/png;base64` : `/foo/nested/icon.png`
expect(await getBg('.css-url-base64-inline')).toMatch(match)
expect(await getBg('.css-url-quotes-base64-inline')).toMatch(match)
const icoMatch = isBuild ? `data:image/x-icon;base64` : `favicon.ico`
const el = await page.$(`link.ico`)
const herf = await el.getAttribute('href')
expect(herf).toMatch(icoMatch)
})

test('multiple urls on the same line', async () => {
Expand Down Expand Up @@ -255,15 +258,3 @@ describe('css and assets in css in build watch', () => {
})
}
})

if (!isBuild) {
test('@import in html style tag hmr', async () => {
await untilUpdated(() => getColor('.import-css'), 'rgb(0, 136, 255)')
editFile(
'./css/import.css',
(code) => code.replace('#0088ff', '#00ff88'),
true
)
await untilUpdated(() => getColor('.import-css'), 'rgb(0, 255, 136)')
})
}
Binary file added packages/playground/assets/favicon.ico
Binary file not shown.
1 change: 1 addition & 0 deletions packages/playground/assets/index.html
Expand Up @@ -2,6 +2,7 @@

<head>
<meta charset="UTF-8" />
<link class="ico" rel="icon" type="image/svg+xml" href="favicon.ico" />
</head>

<link rel="icon" href="data:," />
Expand Down
3 changes: 3 additions & 0 deletions packages/playground/backend-integration/package.json
Expand Up @@ -10,5 +10,8 @@
},
"dependencies": {
"tailwindcss": "^2.2.19"
},
"devDependencies": {
"fast-glob": "^3.2.11"
}
}
@@ -0,0 +1,29 @@
import { getColor, getBgColor } from '../../testUtils'
import { createServer } from 'vite'
import path from 'path'

// Regression test for https://github.com/vitejs/vite/issues/4000
test('postcss plugins in different dir', async () => {
const port = 5005
const server = await createServer({
root: path.join(__dirname, '..', '..', 'tailwind'),
logLevel: 'silent',
server: {
port,
strictPort: true
},
build: {
// skip transpilation during tests to make it faster
target: 'esnext'
}
})
await server.listen()
try {
await page.goto(`http://localhost:${port}`)
const tailwindStyle = await page.$('.tailwind-style')
expect(await getBgColor(tailwindStyle)).toBe('rgb(254, 226, 226)')
expect(await getColor(tailwindStyle)).toBe('rgb(136, 136, 136)')
} finally {
await server.close()
}
})
1 change: 1 addition & 0 deletions packages/playground/css/package.json
Expand Up @@ -10,6 +10,7 @@
},
"devDependencies": {
"css-dep": "link:./css-dep",
"fast-glob": "^3.2.11",
"less": "^4.1.2",
"postcss-nested": "^5.0.6",
"sass": "^1.43.4",
Expand Down
2 changes: 2 additions & 0 deletions packages/playground/define/__tests__/define.spec.ts
Expand Up @@ -20,4 +20,6 @@ test('string', async () => {
expect(await page.textContent('.spread-array')).toBe(
JSON.stringify([...defines.__STRING__])
)
// html would't need to define replacement
expect(await page.textContent('.exp-define')).toBe('__EXP__')
})
1 change: 1 addition & 0 deletions packages/playground/define/index.html
Expand Up @@ -9,6 +9,7 @@ <h1>Define</h1>
<p>process as property: <code class="process-as-property"></code></p>
<p>spread object: <code class="spread-object"></code></p>
<p>spread array: <code class="spread-array"></code></p>
<p>define variable in html: <code class="exp-define">__EXP__</code></p>

<script type="module">
const __VAR_NAME__ = true // ensure define doesn't replace var name
Expand Down
1 change: 1 addition & 0 deletions packages/playground/env-nested/.env
@@ -0,0 +1 @@
VITE_PARENT_ENV=dont_load_me
15 changes: 15 additions & 0 deletions packages/playground/env-nested/__tests__/env-nested.spec.ts
@@ -0,0 +1,15 @@
import { isBuild } from 'testUtils'

const mode = isBuild ? `production` : `development`

test('mode', async () => {
expect(await page.textContent('.mode')).toBe(mode)
})

test('mode file override', async () => {
expect(await page.textContent('.mode-file')).toBe(`.env.${mode}`)
})

test('should not load parent .env file', async () => {
expect(await page.textContent('.parent-env')).not.toBe('dont_load_me')
})
1 change: 1 addition & 0 deletions packages/playground/env-nested/envs/.env.development
@@ -0,0 +1 @@
VITE_EFFECTIVE_MODE_FILE_NAME=.env.development
1 change: 1 addition & 0 deletions packages/playground/env-nested/envs/.env.production
@@ -0,0 +1 @@
VITE_EFFECTIVE_MODE_FILE_NAME=.env.production
16 changes: 16 additions & 0 deletions packages/playground/env-nested/index.html
@@ -0,0 +1,16 @@
<h1>Nested Environment Variables</h1>
<p>import.meta.env.MODE: <code class="mode"></code></p>
<p>
import.meta.env.VITE_EFFECTIVE_MODE_FILE_NAME: <code class="mode-file"></code>
</p>
<p>Empty import.meta.env.VITE_PARENT_ENV: <code class="parent-env"></code></p>

<script type="module">
text('.mode', import.meta.env.MODE)
text('.mode-file', import.meta.env.VITE_EFFECTIVE_MODE_FILE_NAME)
text('.parent-env', import.meta.env.VITE_PARENT_ENV)

function text(el, text) {
document.querySelector(el).textContent = text
}
</script>
11 changes: 11 additions & 0 deletions packages/playground/env-nested/package.json
@@ -0,0 +1,11 @@
{
"name": "test-env-nested",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"debug": "node --inspect-brk ../../vite/bin/vite",
"preview": "vite preview"
}
}
5 changes: 5 additions & 0 deletions packages/playground/env-nested/vite.config.js
@@ -0,0 +1,5 @@
const { defineConfig } = require('vite')

module.exports = defineConfig({
envDir: './envs'
})
13 changes: 13 additions & 0 deletions packages/playground/fs-serve/root/src/index.html
Expand Up @@ -8,6 +8,10 @@ <h2>Safe Fetch</h2>
<pre class="safe-fetch-status"></pre>
<pre class="safe-fetch"></pre>

<h2>Safe Fetch Subdirectory</h2>
<pre class="safe-fetch-subdir-status"></pre>
<pre class="safe-fetch-subdir"></pre>

<h2>Unsafe Fetch</h2>
<pre class="unsafe-fetch-status"></pre>
<pre class="unsafe-fetch"></pre>
Expand Down Expand Up @@ -42,6 +46,15 @@ <h2>Denied</h2>
.then((data) => {
text('.safe-fetch', JSON.stringify(data))
})
// inside allowed dir, safe fetch
fetch('/src/subdir/safe.txt')
.then((r) => {
text('.safe-fetch-subdir-status', r.status)
return r.text()
})
.then((data) => {
text('.safe-fetch-subdir', JSON.stringify(data))
})

// outside of allowed dir, treated as unsafe
fetch('/unsafe.txt')
Expand Down
1 change: 1 addition & 0 deletions packages/playground/fs-serve/root/src/subdir/safe.txt
@@ -0,0 +1 @@
KEY=safe
13 changes: 13 additions & 0 deletions packages/playground/glob-import/__tests__/glob-import.spec.ts
Expand Up @@ -7,6 +7,9 @@ import {
} from '../../testUtils'

const filteredResult = {
'./alias.js': {
default: 'hi'
},
'./foo.js': {
msg: 'foo'
}
Expand All @@ -30,11 +33,19 @@ const json = isBuild

const allResult = {
// JSON file should be properly transformed
'/dir/alias.js': {
default: 'hi'
},
'/dir/baz.json': json,
'/dir/foo.js': {
msg: 'foo'
},
'/dir/index.js': {
globWithAlias: {
'./alias.js': {
default: 'hi'
}
},
modules: filteredResult
},
'/dir/nested/bar.js': {
Expand Down Expand Up @@ -80,6 +91,7 @@ if (!isBuild) {
'/dir/a.js': {},
...allResult,
'/dir/index.js': {
...allResult['/dir/index.js'],
modules: {
'./a.js': {},
...allResult['/dir/index.js'].modules
Expand All @@ -102,6 +114,7 @@ if (!isBuild) {
},
...allResult,
'/dir/index.js': {
...allResult['/dir/index.js'],
modules: {
'./a.js': {
msg: 'a'
Expand Down
1 change: 1 addition & 0 deletions packages/playground/glob-import/dir/alias.js
@@ -0,0 +1 @@
export default 'hi'

0 comments on commit 0894932

Please sign in to comment.