From 07aef1b4c02a64732b31b00591d2d9d9c8025aab Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Fri, 8 Jul 2022 17:05:58 +0800 Subject: [PATCH] docs: cleanup changes (#8989) --- docs/config/server-options.md | 4 +- docs/guide/api-javascript.md | 15 +++-- docs/guide/api-plugin.md | 4 +- docs/guide/assets.md | 4 -- docs/guide/build.md | 40 ++++++------- docs/guide/env-and-mode.md | 9 ++- docs/guide/features.md | 5 +- docs/guide/index.md | 2 +- docs/guide/migration.md | 22 ++++---- docs/guide/ssr.md | 12 ++-- docs/guide/static-deploy.md | 96 +++++++++++--------------------- packages/plugin-legacy/README.md | 2 +- packages/plugin-vue/README.md | 3 +- 13 files changed, 97 insertions(+), 121 deletions(-) diff --git a/docs/config/server-options.md b/docs/config/server-options.md index d5ed802ef716a6..6a43117f2ff164 100644 --- a/docs/config/server-options.md +++ b/docs/config/server-options.md @@ -198,8 +198,8 @@ Create Vite server in middleware mode. - **Example:** ```js -const express = require('express') -const { createServer: createViteServer } = require('vite') +import express from 'express' +import { createServer as createViteServer } from 'vite' async function createServer() { const app = express() diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md index 33202e0d608238..6167bd7dfe7793 100644 --- a/docs/guide/api-javascript.md +++ b/docs/guide/api-javascript.md @@ -13,7 +13,10 @@ async function createServer(inlineConfig?: InlineConfig): Promise **Example Usage:** ```js -const { createServer } = require('vite') +import { fileURLToPath } from 'url' +import { createServer } from 'vite' + +const __dirname = fileURLToPath(new URL('.', import.meta.url)) ;(async () => { const server = await createServer({ @@ -134,8 +137,11 @@ async function build( **Example Usage:** ```js -const path = require('path') -const { build } = require('vite') +import path from 'path' +import { fileURLToPath } from 'url' +import { build } from 'vite' + +const __dirname = fileURLToPath(new URL('.', import.meta.url)) ;(async () => { await build({ @@ -161,8 +167,7 @@ async function preview(inlineConfig?: InlineConfig): Promise **Example Usage:** ```js -const { preview } = require('vite') - +import { preview } from 'vite' ;(async () => { const previewServer = await preview({ // any valid user config options, plus `mode` and `configFile` diff --git a/docs/guide/api-plugin.md b/docs/guide/api-plugin.md index 968505906b1c39..89c71cfdeecee7 100644 --- a/docs/guide/api-plugin.md +++ b/docs/guide/api-plugin.md @@ -11,7 +11,7 @@ Vite strives to offer established patterns out of the box, so before creating a When creating a plugin, you can inline it in your `vite.config.js`. There is no need to create a new package for it. Once you see that a plugin was useful in your projects, consider sharing it to help others [in the ecosystem](https://chat.vitejs.dev). ::: tip -When learning, debugging, or authoring plugins we suggest including [vite-plugin-inspect](https://github.com/antfu/vite-plugin-inspect) in your project. It allows you to inspect the intermediate state of Vite plugins. After installing, you can visit `localhost:5173/__inspect/` to inspect the modules and transformation stack of your project. Check out install instructions in the [vite-plugin-inspect docs](https://github.com/antfu/vite-plugin-inspect). +When learning, debugging, or authoring plugins, we suggest including [vite-plugin-inspect](https://github.com/antfu/vite-plugin-inspect) in your project. It allows you to inspect the intermediate state of Vite plugins. After installing, you can visit `localhost:5173/__inspect/` to inspect the modules and transformation stack of your project. Check out install instructions in the [vite-plugin-inspect docs](https://github.com/antfu/vite-plugin-inspect). ![vite-plugin-inspect](/images/vite-plugin-inspect.png) ::: @@ -199,7 +199,7 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo name: 'mutate-config', config(config, { command }) { if (command === 'build') { - config.root = __dirname + config.root = 'foo' } } }) diff --git a/docs/guide/assets.md b/docs/guide/assets.md index a9483a610faccc..4ba6e417bd3d40 100644 --- a/docs/guide/assets.md +++ b/docs/guide/assets.md @@ -113,7 +113,3 @@ const imgUrl = new URL(imagePath, import.meta.url).href ::: warning Does not work with SSR This pattern does not work if you are using Vite for Server-Side Rendering, because `import.meta.url` have different semantics in browsers vs. Node.js. The server bundle also cannot determine the client host URL ahead of time. ::: - -::: warning `target` needs to be `es2020` or higher -This pattern will not work if [build-target](/config/build-options.md#build-target) or [optimizedeps.esbuildoptions.target](/config/dep-optimization-options.md#optimizedeps-esbuildoptions) is set to a value lower than `es2020`. -::: diff --git a/docs/guide/build.md b/docs/guide/build.md index 48d2f5a14ccf9c..e5a4af31c865d2 100644 --- a/docs/guide/build.md +++ b/docs/guide/build.md @@ -35,7 +35,7 @@ The build can be customized via various [build config options](/config/build-opt ```js // vite.config.js -module.exports = defineConfig({ +export default defineConfig({ build: { rollupOptions: { // https://rollupjs.org/guide/en/#big-list-of-options @@ -53,7 +53,7 @@ You can configure how chunks are split using `build.rollupOptions.output.manualC ```js // vite.config.js import { splitVendorChunkPlugin } from 'vite' -module.exports = defineConfig({ +export default defineConfig({ plugins: [splitVendorChunkPlugin()] }) ``` @@ -66,7 +66,7 @@ You can enable rollup watcher with `vite build --watch`. Or, you can directly ad ```js // vite.config.js -module.exports = defineConfig({ +export default defineConfig({ build: { watch: { // https://rollupjs.org/guide/en/#watch-options @@ -97,10 +97,10 @@ During build, all you need to do is to specify multiple `.html` files as entry p ```js // vite.config.js -const { resolve } = require('path') -const { defineConfig } = require('vite') +import { resolve } from 'path' +import { defineConfig } from 'vite' -module.exports = defineConfig({ +export default defineConfig({ build: { rollupOptions: { input: { @@ -122,10 +122,10 @@ When it is time to bundle your library for distribution, use the [`build.lib` co ```js // vite.config.js -const path = require('path') -const { defineConfig } = require('vite') +import { resolve } from 'path' +import { defineConfig } from 'vite' -module.exports = defineConfig({ +export default defineConfig({ build: { lib: { entry: path.resolve(__dirname, 'lib/main.js'), @@ -214,17 +214,17 @@ experimental: { If the hashed assets and public files aren't deployed together, options for each group can be defined independently using asset `type` included in the third `context` param given to the function. ```js - experimental: { - renderBuiltUrl(filename: string, { hostType: 'js' | 'css' | 'html', type: 'public' | 'asset' }) { - if (type === 'public') { - return 'https://www.domain.com/' + filename - } - else if (path.extname(importer) === '.js') { - return { runtime: `window.__assetsPath(${JSON.stringify(filename)})` } - } - else { - return 'https://cdn.domain.com/assets/' + filename - } +experimental: { + renderBuiltUrl(filename: string, { hostType: 'js' | 'css' | 'html', type: 'public' | 'asset' }) { + if (type === 'public') { + return 'https://www.domain.com/' + filename + } + else if (path.extname(importer) === '.js') { + return { runtime: `window.__assetsPath(${JSON.stringify(filename)})` } + } + else { + return 'https://cdn.domain.com/assets/' + filename } } +} ``` diff --git a/docs/guide/env-and-mode.md b/docs/guide/env-and-mode.md index e3eb14f6524329..43da3c3b8ace38 100644 --- a/docs/guide/env-and-mode.md +++ b/docs/guide/env-and-mode.md @@ -12,6 +12,8 @@ Vite exposes env variables on the special **`import.meta.env`** object. Some bui - **`import.meta.env.DEV`**: {boolean} whether the app is running in development (always the opposite of `import.meta.env.PROD`) +- **`import.meta.env.SSR`**: {boolean} whether the app is running in the [server](./ssr.md#conditional-logic). + ### Production Replacement During production, these env variables are **statically replaced**. It is therefore necessary to always reference them using the full static string. For example, dynamic key access like `import.meta.env[key]` will not work. @@ -47,12 +49,17 @@ Loaded env variables are also exposed to your client source code via `import.met To prevent accidentally leaking env variables to the client, only variables prefixed with `VITE_` are exposed to your Vite-processed code. e.g. the following file: ``` -DB_PASSWORD=foobar VITE_SOME_KEY=123 +DB_PASSWORD=foobar ``` Only `VITE_SOME_KEY` will be exposed as `import.meta.env.VITE_SOME_KEY` to your client source code, but `DB_PASSWORD` will not. +```js +console.log(import.meta.env.VITE_SOME_KEY) // 123 +console.log(import.meta.env.DB_PASSWORD) // undefined +``` + If you want to customize env variables prefix, see [envPrefix](/config/index#envprefix) option. :::warning SECURITY NOTES diff --git a/docs/guide/features.md b/docs/guide/features.md index 265d6c82fa45ef..b7449e15bfc1c9 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -108,11 +108,12 @@ Vite provides first-class Vue support: - Vue 3 SFC support via [@vitejs/plugin-vue](https://github.com/vitejs/vite/tree/main/packages/plugin-vue) - Vue 3 JSX support via [@vitejs/plugin-vue-jsx](https://github.com/vitejs/vite/tree/main/packages/plugin-vue-jsx) -- Vue 2 support via [underfin/vite-plugin-vue2](https://github.com/underfin/vite-plugin-vue2) +- Vue 2.7 support via [vitejs/vite-plugin-vue2](https://github.com/vitejs/vite-plugin-vue2) +- Vue <2.7 support via [underfin/vite-plugin-vue2](https://github.com/underfin/vite-plugin-vue2) ## JSX -`.jsx` and `.tsx` files are also supported out of the box. JSX transpilation is also handled via [esbuild](https://esbuild.github.io), and defaults to the React 16 flavor. React 17 style JSX support in esbuild is tracked [here](https://github.com/evanw/esbuild/issues/334). +`.jsx` and `.tsx` files are also supported out of the box. JSX transpilation is also handled via [esbuild](https://esbuild.github.io). Vue users should use the official [@vitejs/plugin-vue-jsx](https://github.com/vitejs/vite/tree/main/packages/plugin-vue-jsx) plugin, which provides Vue 3 specific features including HMR, global component resolving, directives and slots. diff --git a/docs/guide/index.md b/docs/guide/index.md index f0f327c22988a2..0236b895aedee1 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -18,7 +18,7 @@ You can learn more about the rationale behind the project in the [Why Vite](./wh ## Browser Support -- The default build targets browsers that support both [native ES Modules](https://caniuse.com/es6-module) and [native ESM dynamic import](https://caniuse.com/es6-module-dynamic-import). Legacy browsers can be supported via the official [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) - see the [Building for Production](./build) section for more details. +The default build targets browsers that support both [native ES Modules](https://caniuse.com/es6-module) and [native ESM dynamic import](https://caniuse.com/es6-module-dynamic-import). Legacy browsers can be supported via the official [@vitejs/plugin-legacy](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) - see the [Building for Production](./build) section for more details. ## Trying Vite Online diff --git a/docs/guide/migration.md b/docs/guide/migration.md index 9a80580fcf2eb0..4b0d492c026fea 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -17,17 +17,17 @@ A small fraction of users will now require using [@vitejs/plugin-legacy](https:/ ## Config Options Changes -- The following options that were already deprecated in v2 have been removed: +The following options that were already deprecated in v2 have been removed: - - `alias` (switch to [`resolve.alias`](../config/shared-options.md#resolve-alias)) - - `dedupe` (switch to [`resolve.dedupe`](../config/shared-options.md#resolve-dedupe)) - - `build.base` (switch to [`base`](../config/shared-options.md#base)) - - `build.brotliSize` (switch to [`build.reportCompressedSize`](../config/build-options.md#build-reportcompressedsize)) - - `build.cleanCssOptions` (Vite now uses esbuild for CSS minification) - - `build.polyfillDynamicImport` (use [`@vitejs/plugin-legacy`](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) for browsers without dynamic import support) - - `optimizeDeps.keepNames` (switch to [`optimizeDeps.esbuildOptions.keepNames`](../config/dep-optimization-options.md#optimizedeps-esbuildoptions)) +- `alias` (switch to [`resolve.alias`](../config/shared-options.md#resolve-alias)) +- `dedupe` (switch to [`resolve.dedupe`](../config/shared-options.md#resolve-dedupe)) +- `build.base` (switch to [`base`](../config/shared-options.md#base)) +- `build.brotliSize` (switch to [`build.reportCompressedSize`](../config/build-options.md#build-reportcompressedsize)) +- `build.cleanCssOptions` (Vite now uses esbuild for CSS minification) +- `build.polyfillDynamicImport` (use [`@vitejs/plugin-legacy`](https://github.com/vitejs/vite/tree/main/packages/plugin-legacy) for browsers without dynamic import support) +- `optimizeDeps.keepNames` (switch to [`optimizeDeps.esbuildOptions.keepNames`](../config/dep-optimization-options.md#optimizedeps-esbuildoptions)) -## Architecture changes and legacy Options +## Architecture Changes and Legacy Options This section describes the biggest architecture changes in Vite v3. To allow projects to migrate from v2 in case of a compat issue, legacy options have been added to revert to the Vite v2 strategies. @@ -72,7 +72,7 @@ Also [`build.rollupOptions.output.inlineDynamicImports`](https://rollupjs.org/gu - When using an alias with `import.meta.glob`, the keys are always absolute. - `import.meta.globEager` is now deprecated. Use `import.meta.glob('*', { eager: true })` instead. -### WebAssembly support +### WebAssembly Support `import init from 'example.wasm'` syntax is dropped to prevent future collision with ["ESM integration for Wasm"](https://github.com/WebAssembly/esm-integration). You can use `?init` which is similar to the previous behavior. @@ -87,7 +87,7 @@ You can use `?init` which is similar to the previous behavior. }) ``` -### Automatic https certificate generation +### Automatic https Certificate Generation A valid certificate is needed when using `https`. In Vite v2, if no certificate was configured, a self-signed certificate was automatically created and cached. Since Vite v3, we recommend manually creating your certificates. If you still want to use the automatic generation from v2, this feature can be enabled back by adding [@vitejs/plugin-basic-ssl](https://github.com/vitejs/vite-plugin-basic-ssl) to the project plugins. diff --git a/docs/guide/ssr.md b/docs/guide/ssr.md index eb3cbdedc78cf1..535feaf36931b7 100644 --- a/docs/guide/ssr.md +++ b/docs/guide/ssr.md @@ -66,10 +66,10 @@ When building an SSR app, you likely want to have full control over your main se **server.js** ```js{17-19} -const fs = require('fs') -const path = require('path') -const express = require('express') -const { createServer: createViteServer } = require('vite') +import fs from 'fs' +import path from 'path' +import express from 'express' +import {createServer as createViteServer} from 'vite' async function createServer() { const app = express() @@ -154,7 +154,7 @@ The `dev` script in `package.json` should also be changed to use the server scri To ship an SSR project for production, we need to: 1. Produce a client build as normal; -2. Produce an SSR build, which can be directly loaded via `require()` so that we don't have to go through Vite's `ssrLoadModule`; +2. Produce an SSR build, which can be directly loaded via `import()` so that we don't have to go through Vite's `ssrLoadModule`; Our scripts in `package.json` will look like this: @@ -174,7 +174,7 @@ Then, in `server.js` we need to add some production specific logic by checking ` - Instead of reading the root `index.html`, use the `dist/client/index.html` as the template instead, since it contains the correct asset links to the client build. -- Instead of `await vite.ssrLoadModule('/src/entry-server.js')`, use `require('./dist/server/entry-server.js')` instead (this file is the result of the SSR build). +- Instead of `await vite.ssrLoadModule('/src/entry-server.js')`, use `import('./dist/server/entry-server.js')` instead (this file is the result of the SSR build). - Move the creation and all usage of the `vite` dev server behind dev-only conditional branches, then add static file serving middlewares to serve files from `dist/client`. diff --git a/docs/guide/static-deploy.md b/docs/guide/static-deploy.md index 1d16b65af32e31..756f6a9c85d010 100644 --- a/docs/guide/static-deploy.md +++ b/docs/guide/static-deploy.md @@ -18,10 +18,10 @@ The following guides are based on some shared assumptions: It is important to note that `vite preview` is intended for previewing the build locally and not meant as a production server. ::: tip NOTE -These guides provide instructions for performing a static deployment of your Vite site. Vite also has experimental support for Server Side Rendering. SSR refers to front-end frameworks that support running the same application in Node.js, pre-rendering it to HTML, and finally hydrating it on the client. Check out the [SSR Guide](./ssr) to learn about this feature. On the other hand, if you are looking for integration with traditional server-side frameworks, check out the [Backend Integration guide](./backend-integration) instead. +These guides provide instructions for performing a static deployment of your Vite site. Vite also supports Server Side Rendering. SSR refers to front-end frameworks that support running the same application in Node.js, pre-rendering it to HTML, and finally hydrating it on the client. Check out the [SSR Guide](./ssr) to learn about this feature. On the other hand, if you are looking for integration with traditional server-side frameworks, check out the [Backend Integration guide](./backend-integration) instead. ::: -## Building The App +## Building the App You may run `npm run build` command to build the app. @@ -31,7 +31,7 @@ $ npm run build By default, the build output will be placed at `dist`. You may deploy this `dist` folder to any of your preferred platforms. -### Testing The App Locally +### Testing the App Locally Once you've built the app, you may test it locally by running `npm run preview` command. @@ -52,7 +52,7 @@ You may configure the port of the server by passing `--port` flag as an argument } ``` -Now the `preview` method will launch the server at `http://localhost:8080`. +Now the `preview` command will launch the server at `http://localhost:8080`. ## GitHub Pages @@ -97,40 +97,6 @@ Now the `preview` method will launch the server at `http://localhost:8080`. You can also run the above script in your CI setup to enable automatic deployment on each push. ::: -### GitHub Pages and Travis CI - -1. Set the correct `base` in `vite.config.js`. - - If you are deploying to `https://.github.io/`, you can omit `base` as it defaults to `'/'`. - - If you are deploying to `https://.github.io//`, for example your repository is at `https://github.com//`, then set `base` to `'//'`. - -2. Create a file named `.travis.yml` in the root of your project. - -3. Run `npm install` locally and commit the generated lockfile (`package-lock.json`). - -4. Use the GitHub Pages deploy provider template, and follow the [Travis CI documentation](https://docs.travis-ci.com/user/deployment/pages/). - - ```yaml - language: node_js - node_js: - - lts/* - install: - - npm ci - script: - - npm run build - deploy: - provider: pages - skip_cleanup: true - local_dir: dist - # A token generated on GitHub allowing Travis to push code on you repository. - # Set in the Travis settings page of your repository, as a secure variable. - github_token: $GITHUB_TOKEN - keep_history: true - on: - branch: main - ``` - ## GitLab Pages and GitLab CI 1. Set the correct `base` in `vite.config.js`. @@ -187,6 +153,33 @@ The Netlify CLI will share with you a preview URL to inspect. When you are ready $ ntl deploy --prod ``` +## Vercel + +### Vercel CLI + +1. Install the [Vercel CLI](https://vercel.com/cli) and run `vercel` to deploy. +2. Vercel will detect that you are using Vite and will enable the correct settings for your deployment. +3. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/)) + +```bash +$ npm i -g vercel +$ vercel init vite +Vercel CLI +> Success! Initialized "vite" example in ~/your-folder. +- To deploy, `cd vite` and run `vercel`. +``` + +### Vercel for Git + +1. Push your code to your git repository (GitHub, GitLab, Bitbucket). +2. [Import your Vite project](https://vercel.com/new) into Vercel. +3. Vercel will detect that you are using Vite and will enable the correct settings for your deployment. +4. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/)) + +After your project has been imported and deployed, all subsequent pushes to branches will generate [Preview Deployments](https://vercel.com/docs/concepts/deployments/environments#preview), and all changes made to the Production Branch (commonly “main”) will result in a [Production Deployment](https://vercel.com/docs/concepts/deployments/environments#production). + +Learn more about Vercel’s [Git Integration](https://vercel.com/docs/concepts/git). + ## Cloudflare Pages ### Cloudflare Pages via Wrangler @@ -325,33 +318,6 @@ You can also deploy to a [custom domain](http://surge.sh/help/adding-a-custom-do $ heroku open ``` -## Vercel - -### Vercel CLI - -1. Install the [Vercel CLI](https://vercel.com/cli) and run `vercel` to deploy. -2. Vercel will detect that you are using Vite and will enable the correct settings for your deployment. -3. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/)) - -```bash -$ npm i -g vercel -$ vercel init vite -Vercel CLI -> Success! Initialized "vite" example in ~/your-folder. -- To deploy, `cd vite` and run `vercel`. -``` - -### Vercel for Git - -1. Push your code to your git repository (GitHub, GitLab, Bitbucket). -2. [Import your Vite project](https://vercel.com/new) into Vercel. -3. Vercel will detect that you are using Vite and will enable the correct settings for your deployment. -4. Your application is deployed! (e.g. [vite-vue-template.vercel.app](https://vite-vue-template.vercel.app/)) - -After your project has been imported and deployed, all subsequent pushes to branches will generate [Preview Deployments](https://vercel.com/docs/concepts/deployments/environments#preview), and all changes made to the Production Branch (commonly “main”) will result in a [Production Deployment](https://vercel.com/docs/concepts/deployments/environments#production). - -Learn more about Vercel’s [Git Integration](https://vercel.com/docs/concepts/git). - ## Azure Static Web Apps You can quickly deploy your Vite app with Microsoft Azure [Static Web Apps](https://aka.ms/staticwebapps) service. You need: diff --git a/packages/plugin-legacy/README.md b/packages/plugin-legacy/README.md index 4cec856f95d7af..b5c3631ab2ac60 100644 --- a/packages/plugin-legacy/README.md +++ b/packages/plugin-legacy/README.md @@ -163,7 +163,7 @@ Run `node --input-type=module -e "import {cspHashes} from '@vitejs/plugin-legacy These values (without the `sha256-` prefix) can also be retrieved via ```js -const { cspHashes } = require('@vitejs/plugin-legacy') +import { cspHashes } from '@vitejs/plugin-legacy' ``` When using the `regenerator-runtime` polyfill, it will attempt to use the `globalThis` object to register itself. If `globalThis` is not available (it is [fairly new](https://caniuse.com/?search=globalThis) and not widely supported, including IE 11), it attempts to perform dynamic `Function(...)` call which violates the CSP. To avoid dynamic `eval` in the absence of `globalThis` consider adding `core-js/proposals/global-this` to `additionalLegacyPolyfills` to define it. diff --git a/packages/plugin-vue/README.md b/packages/plugin-vue/README.md index ae848051cecd10..5f2236edf02604 100644 --- a/packages/plugin-vue/README.md +++ b/packages/plugin-vue/README.md @@ -110,6 +110,7 @@ export default { ```ts import vue from '@vitejs/plugin-vue' +import yaml from 'js-yaml' const vueI18nPlugin = { name: 'vue-i18n', @@ -118,7 +119,7 @@ const vueI18nPlugin = { return } if (/\.ya?ml$/.test(id)) { - code = JSON.stringify(require('js-yaml').load(code.trim())) + code = JSON.stringify(yaml.load(code.trim())) } return `export default Comp => { Comp.i18n = ${code}