Skip to content

Commit

Permalink
chore: merge main
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Mar 4, 2022
2 parents c9fb79a + 79dd003 commit f7e8ade
Show file tree
Hide file tree
Showing 116 changed files with 2,431 additions and 770 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
30 changes: 30 additions & 0 deletions CONTRIBUTING.md
Expand Up @@ -14,6 +14,36 @@ To develop and test the core `vite` package:

You can alternatively use [Vite.js Docker Dev](https://github.com/nystudio107/vitejs-docker-dev) for a containerized Docker setup for Vite.js development.

## Debugging

If you want to use break point and explore code execution you can use the ["Run and debug"](https://code.visualstudio.com/docs/editor/debugging) feature from vscode.

1. Add a `debugger` statement where you want to stop the code execution.

2. Click on the "Run and Debug" icon in the activity bar of the editor.

3. Click on the "Javascript Debug Terminal" button.

4. It will open a terminal, then go to `packages/playground/xxx` and run `pnpm run dev`.

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
6 changes: 5 additions & 1 deletion docs/config/index.md
Expand Up @@ -139,9 +139,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 +510,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
2 changes: 1 addition & 1 deletion docs/guide/api-javascript.md
Expand Up @@ -94,7 +94,7 @@ interface ViteDevServer {
*/
ssrLoadModule(
url: string,
options?: { isolated?: boolean }
options?: { fixStacktrace?: boolean }
): Promise<Record<string, any>>
/**
* Fix ssr error stacktrace.
Expand Down
14 changes: 14 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 Down
36 changes: 27 additions & 9 deletions docs/guide/dep-pre-bundling.md
Expand Up @@ -3,10 +3,10 @@
When you run `vite` for the first time, you may notice this message:

```
Optimizable dependencies detected:
react, react-dom
Pre-bundling them to speed up dev server page load...
(this will be run only when your dependencies have changed)
Pre-bundling dependencies:
react
react-dom
(this will be run only when your dependencies or config have changed)
```

## The Why
Expand All @@ -28,6 +28,8 @@ This is Vite performing what we call "dependency pre-bundling". This process ser

By pre-bundling `lodash-es` into a single module, we now only need one HTTP request instead!

Note that this only applies in development mode.

## Automatic Dependency Discovery

If an existing cache is not found, Vite will crawl your source code and automatically discover dependency imports (i.e. "bare imports" that expect to be resolved from `node_modules`) and use these found imports as entry points for the pre-bundle. The pre-bundling is performed with `esbuild` so it's typically very fast.
Expand All @@ -36,11 +38,27 @@ After the server has already started, if a new dependency import is encountered

## Monorepos and Linked Dependencies

In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and instead will analyze the linked dep's dependency list instead.
In a monorepo setup, a dependency may be a linked package from the same repo. Vite automatically detects dependencies that are not resolved from `node_modules` and treats the linked dep as source code. It will not attempt to bundle the linked dep, and will analyze the linked dep's dependency list instead.

However, this requires the linked dep to be exported as ESM. If not, you can add the dependency to [`optimizeDeps.include`](/config/#optimizedeps-include) and [`build.commonjsOptions.include`](/config/#build-commonjsoptions) in your config.

```js
export default defineConfig({
optimizeDeps: {
include: ['linked-dep']
},
build: {
commonjsOptions: {
include: [/linked-dep/, /node_modules/]
}
}
})
```

When making changes to the linked dep, restart the dev server with the `--force` command line option for the changes to take effect.

::: warning Note
Linked dependencies might not work properly in the final build due to differences in dependency resolution.
Use `npm pack` instead for all local dependencies to avoid issues in the final bundle. (The `npm pack` is only ever needed when the linked source code or package only exports CJS code. If it exports ESM code, then it is not needed.)
::: warning Deduping
Due to differences in linked dependency resolution, transitive dependencies can deduplicated incorrectly, causing issues when used in runtime. If you stumble on this issue, use `npm pack` on the linked dependency to fix it.
:::

## Customizing the Behavior
Expand All @@ -57,7 +75,7 @@ Both `include` and `exclude` can be used to deal with this. If the dependency is

Vite caches the pre-bundled dependencies in `node_modules/.vite`. It determines whether it needs to re-run the pre-bundling step based on a few sources:

- The `dependencies` list in your `package.json`
- The `dependencies` list in your `package.json`.
- Package manager lockfiles, e.g. `package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`.
- Relevant fields in your `vite.config.js`, if present.

Expand Down
4 changes: 4 additions & 0 deletions packages/playground/assets/__tests__/assets.spec.ts
Expand Up @@ -120,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
Binary file added packages/playground/assets/favicon.ico
Binary file not shown.
53 changes: 53 additions & 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 Expand Up @@ -137,6 +138,14 @@ <h2>new URL('...', import.meta.url)</h2>
<img class="import-meta-url-img" />
<code class="import-meta-url"></code>

<h2>new URL('...', import.meta.url,) (with comma)</h2>
<img class="import-meta-url-img-comma" />
<code class="import-meta-url-comma"></code>

<h2>new URL('...', import.meta.url,) (with comma + new line)</h2>
<img class="import-meta-url-img-comma-nl" />
<code class="import-meta-url-comma-nl"></code>

<h2>new URL(`./${dynamic}`, import.meta.url)</h2>
<p>
<img class="dynamic-import-meta-url-img-1" />
Expand All @@ -147,6 +156,16 @@ <h2>new URL(`./${dynamic}`, import.meta.url)</h2>
<code class="dynamic-import-meta-url-2"></code>
</p>

<h2>new URL(`./${dynamic}`, import.meta.url,) (with comma)</h2>
<p>
<img class="dynamic-import-meta-url-img-1-comma" />
<code class="dynamic-import-meta-url-1-comma"></code>
</p>
<p>
<img class="dynamic-import-meta-url-img-2-comma" />
<code class="dynamic-import-meta-url-2-comma"></code>
</p>

<h2>simple script tag import-expression</h2>
<code class="import-expression"></code>
<script>
Expand Down Expand Up @@ -182,6 +201,13 @@ <h3 class="import-css">@import</h3>
@import url('./css/import.css');
</style>

<h3 class="foo-public">
@import CSS from publicDir should load (this should be red)
</h3>
<style>
@import '/foo.css';
</style>

<script type="module">
import './css/fonts.css'
import './css/css-url.css'
Expand Down Expand Up @@ -215,6 +241,22 @@ <h3 class="import-css">@import</h3>
const metaUrl = new URL('./nested/asset.png', import.meta.url)
text('.import-meta-url', metaUrl)
document.querySelector('.import-meta-url-img').src = metaUrl

// prettier-ignore
const metaUrlWithComma = new URL('./nested/asset.png', import.meta.url,)
text('.import-meta-url-comma', metaUrlWithComma)
document.querySelector('.import-meta-url-img-comma').src = metaUrlWithComma

// testing trailing comma and new line
// prettier-ignore
const metaUrlWithCommaNL = new URL(
'./nested/asset.png',
import.meta.url,
)
text('.import-meta-url-comma-nl', metaUrlWithCommaNL)
document.querySelector('.import-meta-url-img-comma-nl').src =
metaUrlWithCommaNL

/**
* don't process the code in the comment
* const url = new URL('non_existent_file.png', import.meta.url)
Expand All @@ -229,6 +271,17 @@ <h3 class="import-css">@import</h3>
testDynamicImportMetaUrl('icon', 1)
testDynamicImportMetaUrl('asset', 2)

function testDynamicImportMetaUrlWithComma(name, i) {
// prettier-ignore
const metaUrl = new URL(`./nested/${name}.png`, import.meta.url,)
text(`.dynamic-import-meta-url-${i}-comma`, metaUrl)
document.querySelector(`.dynamic-import-meta-url-img-${i}-comma`).src =
metaUrl
}

testDynamicImportMetaUrlWithComma('icon', 1)
testDynamicImportMetaUrlWithComma('asset', 2)

function text(el, text) {
document.querySelector(el).textContent = text
}
Expand Down
3 changes: 3 additions & 0 deletions packages/playground/assets/static/foo.css
@@ -0,0 +1,3 @@
.foo-public {
color: red;
}
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

0 comments on commit f7e8ade

Please sign in to comment.