chore:更换到主分支

This commit is contained in:
张益铭
2021-03-01 15:26:05 +08:00
parent 9064b372e8
commit 6a5f1810f9
3530 changed files with 59613 additions and 479452 deletions

2564
node_modules/vite/CHANGELOG.md generated vendored

File diff suppressed because it is too large Load Diff

21
node_modules/vite/LICENSE generated vendored
View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

582
node_modules/vite/README.md generated vendored
View File

@@ -1,578 +1,20 @@
# vite ⚡
[![npm][npm-img]][npm-url]
[![node][node-img]][node-url]
[![unix CI status][unix-ci-img]][unix-ci-url]
[![windows CI status][windows-ci-img]][windows-ci-url]
> Next Generation Frontend Tooling
Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with [Rollup](https://rollupjs.org/) for production.
- 💡 Instant Server Start
- ⚡️ Lightning Fast HMR
- 🛠️ Rich Features
- 📦 Optimized Build
- 🔩 Universal Plugin Interface
- 🔑 Fully Typed APIs
- Lightning-fast cold server start
- Instant hot module replacement (HMR)
- True on-demand compilation
- More details in [How and Why](#how-and-why)
Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts:
## Status
- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vitejs.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vitejs.dev/guide/features.html#hot-module-replacement).
In beta and will likely release 1.0 soon.
- A [build command](https://vitejs.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production.
## Getting Started
In addition, Vite is highly extensible via its [Plugin API](https://vitejs.dev/guide/api-plugin.html) and [JavaScript API](https://vitejs.dev/guide/api-javascript.html) with full typing support.
> Note to Vue users: Vite currently only works with Vue 3.x. This also means you can't use libraries that are not yet compatible with Vue 3.
```bash
$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev
```
If using Yarn:
```bash
$ yarn create vite-app <project-name>
$ cd <project-name>
$ yarn
$ yarn dev
```
> Although Vite is primarily designed to work with Vue 3, it can support other frameworks as well. For example, try `npm init vite-app --template react` or `--template preact`.
### Using master branch
If you can't wait for a new release to test the latest features, clone the `vite` to your local machine and execute the following commands:
```
yarn
yarn build
yarn link
```
Then go to your vite based project and run `yarn link vite`. Now restart the development server (`yarn dev`) to ride on the bleeding edge!
## Browser Support
Vite requires [native ES module imports](https://caniuse.com/#feat=es6-module) during development. The production build also relies on dynamic imports for code-splitting (which can be [polyfilled](https://github.com/GoogleChromeLabs/dynamic-import-polyfill)).
Vite assumes you are targeting modern browsers and by default only transpiles your code to `es2019` during build (so that optional chaining can work with terser minification). You can specify the target range via the `esbuildTarget` config option, where the lowest target available is `es2015`.
## Features
- [Bare Module Resolving](#bare-module-resolving)
- [Hot Module Replacement](#hot-module-replacement)
- [TypeScript](#typescript)
- [CSS / JSON Importing](#css--json-importing)
- [Asset URL Handling](#asset-url-handling)
- [PostCSS](#postcss)
- [CSS Modules](#css-modules)
- [CSS Pre-processors](#css-pre-processors)
- [JSX](#jsx)
- [Web Assembly](#web-assembly)
- [Inline Web Workers](#inline-web-workers)
- [Custom Blocks](#custom-blocks)
- [Config File](#config-file)
- [HTTPS/2](#https2)
- [Dev Server Proxy](#dev-server-proxy)
- [Production Build](#production-build)
- [Modes and Environment Variables](#modes-and-environment-variables)
- [Using Vite with Traditional Backend](#using-vite-with-traditional-backend)
Vite tries to mirror the default configuration in [vue-cli](http://cli.vuejs.org/) as much as possible. If you've used `vue-cli` or other webpack-based boilerplates before, you should feel right at home. That said, do expect things to be different here and there.
### Bare Module Resolving
Native ES imports don't support bare module imports like
```js
import { createApp } from 'vue'
```
The above will throw an error by default. Vite detects such bare module imports in all served `.js` files and rewrites them with special paths like `/@modules/vue`. Under these special paths, Vite performs module resolution to locate the correct files from your installed dependencies.
Note that `vue` has special treatment - if it isn't installed in the project locally, Vite will fallback to the version from its own dependencies. If you have Vite installed globally, this makes it possible to quickly prototype with Vue without installing anything locally.
### Hot Module Replacement
- The `vue`, `react` and `preact` templates of `create-vite-app` all come with HMR out of the box.
- For manual HMR, an API is provided via `import.meta.hot`.
For a module to self-accept, use `import.meta.hot.accept`:
```js
export const count = 1
// the conditional check is required so that HMR related code can be
// dropped in production
if (import.meta.hot) {
import.meta.hot.accept((newModule) => {
console.log('updated: count is now ', newModule.count)
})
}
```
A module can also accept updates from direct dependencies without reloading itself, using `import.meta.hot.acceptDeps`:
```js
import { foo } from './foo.js'
foo()
if (import.meta.hot) {
import.meta.hot.acceptDeps('./foo.js', (newFoo) => {
// the callback receives the updated './foo.js' module
newFoo.foo()
})
// Can also accept an array of dep modules:
import.meta.hot.acceptDeps(['./foo.js', './bar.js'], ([newFooModule, newBarModule]) => {
// the callback receives the updated modules in an Array
})
}
```
A self-accepting module or a module that expects to be accepted by others can use `hot.dispose` to clean-up any persistent side effects created by its updated copy:
```js
function setupSideEffect() {}
setupSideEffect()
if (import.meta.hot) {
import.meta.hot.dispose((data) => {
// cleanup side effect
})
}
```
For the full API, consult [importMeta.d.ts](https://github.com/vitejs/vite/blob/master/importMeta.d.ts).
Note that Vite's HMR does not actually swap the originally imported module: if an accepting module re-exports imports from a dep, then it is responsible for updating those re-exports (and these exports must be using `let`). In addition, importers up the chain from the accepting module will not be notified of the change.
This simplified HMR implementation is sufficient for most dev use cases, while allowing us to skip the expensive work of generating proxy modules.
### TypeScript
Vite supports importing `.ts` files and `<script lang="ts">` in Vue SFCs out of the box.
Vite only performs transpilation on `.ts` files and does **NOT** perform type checking. It assumes type checking is taken care of by your IDE and build process (you can run `tsc --noEmit` in the build script).
Vite uses [esbuild](https://github.com/evanw/esbuild) to transpile TypeScript into JavaScript which is about 20~30x faster than vanilla `tsc`, and HMR updates can reflect in the browser in under 50ms.
Note that because `esbuild` only performs transpilation without type information, it doesn't support certain features like const enum and implicit type-only imports. You must set `"isolatedModules": true` in your `tsconfig.json` under `compilerOptions` so that TS will warn you against the features that do not work with isolated transpilation.
### CSS / JSON Importing
You can directly import `.css` and `.json` files from JavaScript (including `<script>` tags of `*.vue` files, of course).
- `.json` files export their content as an object that is the default export.
- `.css` files do not export anything unless it ends with `.module.css` (See [CSS Modules](#css-modules) below). Importing them leads to the side effect of them being injected to the page during dev, and being included in the final `style.css` of the production build.
Both CSS and JSON imports also support Hot Module Replacement.
### Asset URL Handling
You can reference static assets in your `*.vue` templates, styles and plain `.css` files either using absolute public paths (based on project root) or relative paths (based on your file system). The latter is similar to the behavior you are used to if you have used `vue-cli` or webpack's `file-loader`.
Common image, media, and font filetypes are detected and included as assets automatically. You can override this using the `assetsInclude` configuration option.
All referenced assets, including those using absolute paths, will be copied to the dist folder with a hashed file name in the production build. Never-referenced assets will not be copied. Similar to `vue-cli`, image assets smaller than 4kb will be base64 inlined.
All **static** path references, including absolute paths, should be based on your working directory structure.
#### The `public` Directory
The `public` directory under project root can be used as an escape hatch to provide static assets that either are never referenced in source code (e.g. `robots.txt`), or must retain the exact same file name (without hashing).
Assets placed in `public` will be copied to the root of the dist directory as-is.
Note that you should reference files placed in `public` using root absolute path - for example, `public/icon.png` should always be referenced in source code as `/icon.png`.
#### Public Base Path
If you are deploying your project under a nested public path, simply specify `--base=/your/public/path/` and all asset paths will be rewritten accordingly.
For dynamic path references, there are two options:
- You can get the resolved public path of a static asset file by importing it from JavaScript. e.g. `import path from './foo.png'` will give you its resolved public path as a string.
- If you need to concatenate paths on the fly, you can use the globally injected `import.meta.env.BASE_URL` variable which will be the public base path. Note this variable is statically replaced during build so it must appear exactly as-is (i.e. `import.meta.env['BASE_URL']` won't work).
### PostCSS
Vite automatically applies your PostCSS config to all styles in `*.vue` files and imported plain `.css` files. Just install necessary plugins and add a `postcss.config.js` in your project root.
### CSS Modules
Note that you do **not** need to configure PostCSS if you want to use CSS Modules: it works out of the box. Inside `*.vue` components you can use `<style module>`, and for plain `.css` files, you need to name CSS modules files as `*.module.css` which allows you to import the naming hash from it.
### CSS Pre-Processors
Because Vite targets modern browsers only, it is recommended to use native CSS variables with PostCSS plugins that implement CSSWG drafts (e.g. [postcss-nesting](https://github.com/jonathantneal/postcss-nesting)) and author plain, future-standards-compliant CSS. That said, if you insist on using a CSS pre-processor, you can install the corresponding pre-processor and just use it:
```bash
yarn add -D sass
```
```vue
<style lang="scss">
/* use scss */
</style>
```
Or import them from JavaScript:
```js
import './style.scss'
```
#### Passing Options to Pre-Processor
> 1.0.0-beta.9+
> And if you want to pass options to the pre-processor, you can do that using the `cssPreprocessOptions` option in the config (see [Config File](#config-file) below).
> For example, to pass some shared global variables to all your Less styles:
```js
// vite.config.js
export default {
cssPreprocessOptions: {
less: {
modifyVars: {
'preprocess-custom-color': 'green'
}
}
}
}
```
### JSX
`.jsx` and `.tsx` files are also supported. JSX transpilation is also handled via `esbuild`.
The default JSX configuration works out of the box with Vue 3 (note there is currently no JSX-based HMR for Vue):
```jsx
import { createApp } from 'vue'
function App() {
return <Child>{() => 'bar'}</Child>
}
function Child(_, { slots }) {
return <div onClick={() => console.log('hello')}>{slots.default()}</div>
}
createApp(App).mount('#app')
```
Currently, this is auto-importing a `jsx` compatible function that converts esbuild-produced JSX calls into Vue 3 compatible vnode calls, which is sub-optimal. Vue 3 will eventually provide a custom JSX transform that can take advantage of Vue 3's runtime fast paths.
#### JSX with React/Preact
There are two other presets provided: `react` and `preact`. You can specify the preset by running Vite with `--jsx react` or `--jsx preact`.
If you need a custom JSX pragma, JSX can also be customized via `--jsx-factory` and `--jsx-fragment` flags from the CLI or `jsx: { factory, fragment }` from the API. For example, you can run `vite --jsx-factory=h` to use `h` for JSX element creation calls. In the config (see [Config File](#config-file) below), it can be specified as:
```js
// vite.config.js
export default {
jsx: {
factory: 'h',
fragment: 'Fragment'
}
}
```
Note that for the Preact preset, `h` is also auto injected so you don't need to manually import it. However, this may cause issues if you are using `.tsx` with Preact since TS expects `h` to be explicitly imported for type inference. In that case, you can use the explicit factory config shown above which disables the auto `h` injection.
### Web Assembly
> 1.0.0-beta.3+
Pre-compiled `.wasm` files can be directly imported - the default export will be an initialization function that returns a Promise of the exports object of the wasm instance:
``` js
import init from './example.wasm'
init().then(exports => {
exports.test()
})
```
The init function can also take the `imports` object which is passed along to `WebAssembly.instantiate` as its second argument:
``` js
init({
imports: {
someFunc: () => { /* ... */ }
}
}).then(() => { /* ... */ })
```
In the production build, `.wasm` files smaller than `assetInlineLimit` will be inlined as base64 strings. Otherwise, they will be copied to the dist directory as an asset and fetched on-demand.
### Inline Web Workers
> 1.0.0-beta.3+
A web worker script can be directly imported by appending `?worker` to the import request. The default export will be a custom worker constructor:
``` js
import MyWorker from './worker?worker'
const worker = new MyWorker()
```
In the production build, workers imported this way are inlined into the bundle as base64 strings.
The worker script can also use `import` statements instead of `importScripts()` - note during dev this relies on browser native support and currently only works in Chrome, but for the production build it is compiled away.
If you do not wish to inline the worker, you should place your worker scripts in `public` and initialize the worker via `new Worker('/worker.js')`.
### Config File
You can create a `vite.config.js` or `vite.config.ts` file in your project. Vite will automatically use it if one is found in the current working directory. You can also explicitly specify a config file via `vite --config my-config.js`.
In addition to options mapped from CLI flags, it also supports `alias`, `transforms`, and `plugins` (which is a subset of the config interface). For now, see [config.ts](https://github.com/vuejs/vite/blob/master/src/node/config.ts) for full details before more thorough documentation is available.
### Custom Blocks
[Custom blocks](https://vue-loader.vuejs.org/guide/custom-blocks.html) in Vue SFCs are also supported. To use custom blocks, specify transform functions for custom blocks using the `vueCustomBlockTransforms` option in the [config file](#config-file):
``` js
// vite.config.js
export default {
vueCustomBlockTransforms: {
i18n: ({ code }) => {
// return transformed code
}
}
}
```
### HTTPS/2
Starting the server with `--https` will automatically generate a self-signed cert and start the server with TLS and HTTP/2 enabled.
Custom certs can also be provided by using the `httpsOptions` option in the config file, which accepts `key`, `cert`, `ca` and `pfx` as in Node `https.ServerOptions`.
### Dev Server Proxy
You can use the `proxy` option in the config file to configure custom proxies for the dev server. Vite uses [`koa-proxies`](https://github.com/vagusX/koa-proxies) which in turn uses [`http-proxy`](https://github.com/http-party/node-http-proxy). Each key can be a path Full options [here](https://github.com/http-party/node-http-proxy#options).
Example:
``` js
// vite.config.js
export default {
proxy: {
// string shorthand
'/foo': 'http://localhost:4567/foo',
// with options
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
}
```
### Production Build
Vite does utilize bundling for production builds because native ES module imports result in waterfall network requests that are simply too punishing for page load time in production.
You can run `vite build` to bundle the app.
Internally, we use a highly opinionated Rollup config to generate the build. The build is configurable by passing on most options to Rollup - and most non-rollup string/boolean options have mapping flags in the CLI (see [build/index.ts](https://github.com/vuejs/vite/blob/master/src/node/build/index.ts) for full details).
### Modes and Environment Variables
The mode option is used to specify the value of `import.meta.env.MODE` and the corresponding environment variables files that needs to be loaded.
By default, there are two modes:
- `development` is used by `vite` and `vite serve`
- `production` is used by `vite build`
You can overwrite the default mode used for a command by passing the `--mode` option flag. For example, if you want to use development variables in the build command:
```bash
vite build --mode development
```
When running `vite`, environment variables are loaded from the following files in your project root:
```
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified env mode
.env.[mode].local # only loaded in specified env mode, ignored by git
```
**Note:** only variables prefixed with `VITE_` are exposed to your code. e.g. `VITE_SOME_KEY=123` will be exposed as `import.meta.env.VITE_SOME_KEY`, but `SOME_KEY=123` will not. This is because the `.env` files may be used by some users for server-side or build scripts and may contain sensitive information that should not be exposed in code shipped to browsers.
### Using Vite with Traditional Backend
If you want to serve the HTML using a traditional backend (e.g. Rails, Laravel) but use Vite for serving assets, here's what you can do:
1. In your Vite config, enable `cors` and `emitManifest`:
```js
// vite.config.js
export default {
cors: true,
emitManifest: true
}
```
2. For development, inject the following in your server's HTML template (substitute `http://localhost:3000` with the local URL Vite is running at):
```html
<!-- if development -->
<script type="module" src="http://localhost:3000/vite/client"></script>
<script type="module" src="http://localhost:3000/main.js"></script>
```
Also make sure the server is configured to serve static assets in the Viter working directory, otherwise assets such as images won't be loaded properly.
3. For production: after running `vite build`, a `manifest.json` file will be generated alongside other asset files. You can use this file to render links with hashed filenames (syntax here for explnatation only, substitute with your server templating language):
```html
<!-- if production -->
<link rel="stylesheet" href="/_assets/{{ maniest['style.css'] }}">
<script type="module" src="/_assets/{{ maniest['index.js] }}"></script>
```
## API
### Dev Server
You can customize the server using the API. The server can accept plugins which have access to the internal Koa app instance:
```js
const { createServer } = require('vite')
const myPlugin = ({
root, // project root directory, absolute path
app, // Koa app instance
server, // raw http server instance
watcher // chokidar file watcher instance
}) => {
app.use(async (ctx, next) => {
// You can do pre-processing here - this will be the raw incoming requests
// before vite touches it.
if (ctx.path.endsWith('.scss')) {
// Note vue <style lang="xxx"> are supported by
// default as long as the corresponding pre-processor is installed, so this
// only applies to <link ref="stylesheet" href="*.scss"> or js imports like
// `import '*.scss'`.
console.log('pre processing: ', ctx.url)
ctx.type = 'css'
ctx.body = 'body { border: 1px solid red }'
}
// ...wait for vite to do built-in transforms
await next()
// Post processing before the content is served. Note this includes parts
// compiled from `*.vue` files, where <template> and <script> are served as
// `application/javascript` and <style> are served as `text/css`.
if (ctx.response.is('js')) {
console.log('post processing: ', ctx.url)
console.log(ctx.body) // can be string or Readable stream
}
})
}
createServer({
configureServer: [myPlugin]
}).listen(3000)
```
### Build
Check out the full options interface in [build/index.ts](https://github.com/vuejs/vite/blob/master/src/node/build/index.ts).
```js
const { build } = require('vite')
;(async () => {
// All options are optional.
// check out `src/node/build/index.ts` for full options interface.
const result = await build({
rollupInputOptions: {
// https://rollupjs.org/guide/en/#big-list-of-options
},
rollupOutputOptions: {
// https://rollupjs.org/guide/en/#big-list-of-options
},
rollupPluginVueOptions: {
// https://github.com/vuejs/rollup-plugin-vue/tree/next#options
}
// ...
})
})()
```
## How and Why
### How is This Different from `vue-cli` or Other Bundler-based Solutions?
The primary difference is that for Vite there is no bundling during development. The ES Import syntax in your source code is served directly to the browser, and the browser parses them via native `<script module>` support, making HTTP requests for each import. The dev server intercepts the requests and performs code transforms if necessary. For example, an import to a `*.vue` file is compiled on the fly right before it's sent back to the browser.
There are a few advantages to this approach:
- Since there is no bundling work to be done, the server cold start is extremely fast.
- The code is compiled on-demand, so only code actually imported on the current screen is compiled. You don't have to wait until your entire app to be bundled to start developing. This can be a huge difference in apps with dozens of screens.
- Hot module replacement (HMR) performance is decoupled from the total number of modules. This makes HMR consistently fast no matter how big your app is.
Full page reload could be slightly slower than a bundler-based setup, since native ES imports result in network waterfalls with deep import chains. However, since this is local development, the difference should be trivial compared to actual compilation time. (There is no compile cost on page reload since already compiled files are cached in memory.)
Finally, because compilation is still done in Node, it can technically support any code transforms a bundler can, and nothing prevents you from eventually bundling the code for production. In fact, Vite provides a `vite build` command to do exactly that so the app doesn't suffer from network waterfall in production.
### How is This Different from [es-dev-server](https://open-wc.org/developing/es-dev-server.html)?
`es-dev-server` is a great project and we did take some inspiration from it when refactoring Vite in the early stages. That said, here is why Vite is different from `es-dev-server` and why we didn't just implement Vite as a middleware for `es-dev-server`:
- One of Vite's primary goal was to support Hot Module Replacement, but `es-dev-server` internals is a bit too opaque to get this working nicely via a middleware.
- Vite aims to be a single tool that integrates both the dev and the build process. You can use Vite to both serve and bundle the same source code, with zero configuration.
- Vite is more opinionated on how certain types of imports are handled, e.g. `.css` and static assets. The handling is similar to `vue-cli` for obvious reasons.
### How is This Different from [Snowpack](https://www.snowpack.dev/)?
Both Snowpack v2 and Vite offer native ES module import based dev servers. Vite's dependency pre-optimization is also heavily inspired by Snowpack v1. Both projects share similar performance characteristics when it comes to development feedback speed. Some notable differences are:
- Vite was created to tackle native ESM-based HMR. When Vite was first released with working ESM-based HMR, there was no other project actively trying to bring native ESM based HMR to production.
Snowpack v2 initially did not offer HMR support but added it in a later release, making the scope of two projects much closer. Vite and Snowpack have collaborated on a common API spec for ESM HMR, but due to the constraints of different implementation strategies, the two projects still ship slightly different APIs.
- Both solutions can also bundle the app for production, but Vite uses Rollup with built-in config while Snowpack delegates it to Parcel/webpack via additional plugins. Vite will in most cases build faster and produce smaller bundles. In addition, tighter integration with the bundler makes it easier to author Vite transforms and plugins that modify dev/build configs at the same.
- Vue support is a first-class feature in Vite. For example, Vite provides a much more fine-grained HMR integration with Vue, and the build config is fine tuned to produce the most efficient bundle.
## Contribution
See [Contributing Guide](https://github.com/vitejs/vite/tree/master/.github/contributing.md).
## Trivia
[vite](https://en.wiktionary.org/wiki/vite) is the french word for "fast" and is pronounced `/vit/`.
## License
MIT
[npm-img]: https://img.shields.io/npm/v/vite.svg
[npm-url]: https://npmjs.com/package/vite
[node-img]: https://img.shields.io/node/v/vite.svg
[node-url]: https://nodejs.org/en/about/releases/
[unix-ci-img]: https://circleci.com/gh/vitejs/vite.svg?style=shield
[unix-ci-url]: https://app.circleci.com/pipelines/github/vitejs/vite
[windows-ci-img]: https://ci.appveyor.com/api/projects/status/0q4j8062olbcs71l/branch/master?svg=true
[windows-ci-url]: https://ci.appveyor.com/project/yyx990803/vite/branch/master
[Read the Docs to Learn More](https://vitejs.dev).

58
node_modules/vite/bin/vite.js generated vendored
View File

@@ -1,2 +1,58 @@
#!/usr/bin/env node
require('../dist/node/cli')
if (!__dirname.includes('node_modules')) {
try {
// only available as dev dependency
require('source-map-support').install()
} catch (e) {}
}
global.__vite_start_time = Date.now()
// check debug mode first before requiring the CLI.
const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))
const filterIndex = process.argv.findIndex((arg) =>
/^(?:-f|--filter)$/.test(arg)
)
const profileIndex = process.argv.indexOf('--profile')
if (debugIndex > 0) {
let value = process.argv[debugIndex + 1]
if (!value || value.startsWith('-')) {
value = 'vite:*'
} else {
// support debugging multiple flags with comma-separated list
value = value
.split(',')
.map((v) => `vite:${v}`)
.join(',')
}
process.env.DEBUG = value
if (filterIndex > 0) {
const filter = process.argv[filterIndex + 1]
if (filter && !filter.startsWith('-')) {
process.env.VITE_DEBUG_FILTER = filter
}
}
}
function start() {
require('../dist/node/cli')
}
if (profileIndex > 0) {
process.argv.splice(profileIndex, 1)
const next = process.argv[profileIndex]
if (next && !next.startsWith('-')) {
process.argv.splice(profileIndex, 1)
}
const inspector = require('inspector')
const session = (global.__vite_profile_session = new inspector.Session())
session.connect()
session.post('Profiler.enable', () => {
session.post('Profiler.start', start)
})
} else {
start()
}

View File

@@ -1,15 +0,0 @@
export declare function updateStyle(id: string, content: string): void;
interface HotCallback {
deps: string | string[];
fn: (modules: object | object[]) => void;
}
export declare const createHotContext: (id: string) => {
readonly data: any;
accept(callback?: HotCallback['fn']): void;
acceptDeps(deps: HotCallback['deps'], callback?: HotCallback['fn']): void;
dispose(cb: (data: any) => void): void;
decline(): void;
invalidate(): void;
on(event: string, cb: () => void): void;
};
export {};

View File

@@ -1,26 +1,188 @@
// This file runs in the browser.
window.process = window.process || {};
window.process.env = window.process.env || {};
window.process.env.NODE_ENV = __MODE__;
const defines = __DEFINES__;
Object.keys(defines).forEach((key) => {
const segs = key.split('.');
let target = window;
for (let i = 0; i < segs.length; i++) {
const seg = segs[i];
if (i === segs.length - 1) {
target[seg] = defines[key];
import './env';
const template = /*html*/ `
<style>
:host {
position: fixed;
z-index: 99999;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow-y: scroll;
margin: 0;
background: rgba(0, 0, 0, 0.66);
--monospace: 'SFMono-Regular', Consolas,
'Liberation Mono', Menlo, Courier, monospace;
--red: #ff5555;
--yellow: #e2aa53;
--purple: #cfa4ff;
--cyan: #2dd9da;
--dim: #c9c9c9;
}
.window {
font-family: var(--monospace);
line-height: 1.5;
width: 800px;
color: #d8d8d8;
margin: 30px auto;
padding: 25px 40px;
position: relative;
background: #181818;
border-radius: 6px 6px 8px 8px;
box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
overflow: hidden;
border-top: 8px solid var(--red);
}
pre {
font-family: var(--monospace);
font-size: 16px;
margin-top: 0;
margin-bottom: 1em;
overflow-x: scroll;
scrollbar-width: none;
}
pre::-webkit-scrollbar {
display: none;
}
.message {
line-height: 1.3;
font-weight: 600;
white-space: pre-wrap;
}
.message-body {
color: var(--red);
}
.plugin {
color: var(--purple);
}
.file {
color: var(--cyan);
margin-bottom: 0;
white-space: pre-wrap;
word-break: break-all;
}
.frame {
color: var(--yellow);
}
.stack {
font-size: 13px;
color: var(--dim);
}
.tip {
font-size: 13px;
color: #999;
border-top: 1px dotted #999;
padding-top: 13px;
}
code {
font-size: 13px;
font-family: var(--monospace);
color: var(--yellow);
}
.file-link {
text-decoration: underline;
cursor: pointer;
}
</style>
<div class="window">
<pre class="message"><span class="plugin"></span><span class="message-body"></span></pre>
<pre class="file"></pre>
<pre class="frame"></pre>
<pre class="stack"></pre>
<div class="tip">
Click outside or fix the code to dismiss.<br>
You can also disable this overlay with
<code>hmr: { overlay: false }</code> in <code>vite.config.js.</code>
</div>
</div>
`;
const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
class ErrorOverlay extends HTMLElement {
constructor(err) {
var _a;
super();
this.root = this.attachShadow({ mode: 'open' });
this.root.innerHTML = template;
codeframeRE.lastIndex = 0;
const hasFrame = err.frame && codeframeRE.test(err.frame);
const message = hasFrame
? err.message.replace(codeframeRE, '')
: err.message;
if (err.plugin) {
this.text('.plugin', `[plugin:${err.plugin}] `);
}
this.text('.message-body', message.trim());
const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`);
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true);
}
else if (err.id) {
this.text('.file', file);
}
if (hasFrame) {
this.text('.frame', err.frame.trim());
}
this.text('.stack', err.stack, true);
this.root.querySelector('.window').addEventListener('click', (e) => {
e.stopPropagation();
});
this.addEventListener('click', () => {
this.close();
});
}
text(selector, text, linkFiles = false) {
const el = this.root.querySelector(selector);
if (!linkFiles) {
el.textContent = text;
}
else {
target = target[seg] || (target[seg] = {});
let curIndex = 0;
let match;
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match;
if (index != null) {
const frag = text.slice(curIndex, index);
el.appendChild(document.createTextNode(frag));
const link = document.createElement('a');
link.textContent = file;
link.className = 'file-link';
link.onclick = () => {
fetch('/__open-in-editor?file=' + encodeURIComponent(file));
};
el.appendChild(link);
curIndex += frag.length + file.length;
}
}
}
}
});
close() {
var _a;
(_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this);
}
}
const overlayId = 'vite-error-overlay';
customElements.define(overlayId, ErrorOverlay);
console.log('[vite] connecting...');
// use server configuration, then fallback to inference
const socketProtocol = __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws');
const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`;
const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr');
const base = __BASE__ || '/';
function warnFailedFetch(err, path) {
if (!err.message.match('fetch')) {
console.error(err);
@@ -31,66 +193,65 @@ function warnFailedFetch(err, path) {
}
// Listen for messages
socket.addEventListener('message', async ({ data }) => {
const payload = JSON.parse(data);
if (payload.type === 'multi') {
payload.updates.forEach(handleMessage);
}
else {
handleMessage(payload);
}
handleMessage(JSON.parse(data));
});
let isFirstUpdate = true;
async function handleMessage(payload) {
const { path, changeSrcPath, timestamp } = payload;
switch (payload.type) {
case 'connected':
console.log(`[vite] connected.`);
// proxy(nginx, docker) hmr ws maybe caused timeout,
// so send ping package let ws keep alive.
setInterval(() => socket.send('ping'), __HMR_TIMEOUT__);
break;
case 'vue-reload':
queueUpdate(import(`${path}?t=${timestamp}`)
.catch((err) => warnFailedFetch(err, path))
.then((m) => () => {
__VUE_HMR_RUNTIME__.reload(path, m.default);
console.log(`[vite] ${path} reloaded.`);
}));
break;
case 'vue-rerender':
const templatePath = `${path}?type=template`;
import(`${templatePath}&t=${timestamp}`).then((m) => {
__VUE_HMR_RUNTIME__.rerender(path, m.render);
console.log(`[vite] ${path} template updated.`);
case 'update':
// if this is the first update and there's already an error overlay, it
// means the page opened with existing server compile error and the whole
// module script failed to load (since one of the nested imports is 500).
// in this case a normal update won't work and a full reload is needed.
if (isFirstUpdate && hasErrorOverlay()) {
window.location.reload();
return;
}
else {
clearErrorOverlay();
isFirstUpdate = false;
}
payload.updates.forEach((update) => {
if (update.type === 'js-update') {
queueUpdate(fetchUpdate(update));
}
else {
// css-update
// this is only sent when a css file referenced with <link> is updated
let { path, timestamp } = update;
path = path.replace(/\?.*/, '');
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => e.href.includes(path));
if (el) {
const newPath = `${path}${path.includes('?') ? '&' : '?'}t=${timestamp}`;
el.href = new URL(newPath, el.href).href;
}
console.log(`[vite] css hot updated: ${path}`);
}
});
break;
case 'style-update':
// check if this is referenced in html via <link>
const el = document.querySelector(`link[href*='${path}']`);
if (el) {
el.setAttribute('href', `${path}${path.includes('?') ? '&' : '?'}t=${timestamp}`);
break;
}
// imported CSS
const importQuery = path.includes('?') ? '&import' : '?import';
await import(`${path}${importQuery}&t=${timestamp}`);
console.log(`[vite] ${path} updated.`);
break;
case 'style-remove':
removeStyle(payload.id);
break;
case 'js-update':
queueUpdate(updateModule(path, changeSrcPath, timestamp));
break;
case 'custom':
const cbs = customUpdateMap.get(payload.id);
const cbs = customListenersMap.get(payload.event);
if (cbs) {
cbs.forEach((cb) => cb(payload.customData));
cbs.forEach((cb) => cb(payload.data));
}
break;
case 'full-reload':
if (path.endsWith('.html')) {
if (payload.path && payload.path.endsWith('.html')) {
// if html file is edited, only reload the page if the browser is
// currently on that page.
const pagePath = location.pathname;
if (pagePath === path ||
(pagePath.endsWith('/') && pagePath + 'index.html' === path)) {
const payloadPath = base + payload.path.slice(1);
if (pagePath === payloadPath ||
(pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) {
location.reload();
}
return;
@@ -98,8 +259,48 @@ async function handleMessage(payload) {
else {
location.reload();
}
break;
case 'prune':
// After an HMR update, some modules are no longer imported on the page
// but they may have left behind side effects that need to be cleaned up
// (.e.g style injections)
// TODO Trigger their dispose callbacks.
payload.paths.forEach((path) => {
const fn = pruneMap.get(path);
if (fn) {
fn(dataMap.get(path));
}
});
break;
case 'error':
const err = payload.err;
if (enableOverlay) {
createErrorOverlay(err);
}
else {
console.error(`[vite] Internal Server Error\n${err.stack}`);
}
break;
default:
const check = payload;
return check;
}
}
const enableOverlay = __HMR_ENABLE_OVERLAY__;
function createErrorOverlay(err) {
if (!enableOverlay)
return;
clearErrorOverlay();
document.body.appendChild(new ErrorOverlay(err));
}
function clearErrorOverlay() {
document
.querySelectorAll(overlayId)
.forEach((n) => n.close());
}
function hasErrorOverlay() {
return document.querySelectorAll(overlayId).length;
}
let pending = false;
let queued = [];
/**
@@ -119,10 +320,12 @@ async function queueUpdate(p) {
}
}
// ping server
socket.addEventListener('close', () => {
socket.addEventListener('close', ({ wasClean }) => {
if (wasClean)
return;
console.log(`[vite] server connection lost. polling for restart...`);
setInterval(() => {
fetch('/')
fetch(`${base}__vite_ping`)
.then(() => {
location.reload();
})
@@ -131,34 +334,10 @@ socket.addEventListener('close', () => {
});
}, 1000);
});
// https://wicg.github.io/construct-stylesheets
const supportsConstructedSheet = (() => {
try {
new CSSStyleSheet();
return true;
}
catch (e) { }
return false;
})();
const sheetsMap = new Map();
export function updateStyle(id, content) {
function updateStyle(id, content) {
let style = sheetsMap.get(id);
if (supportsConstructedSheet && !content.includes('@import')) {
if (style && !(style instanceof CSSStyleSheet)) {
removeStyle(id);
style = undefined;
}
if (!style) {
style = new CSSStyleSheet();
style.replaceSync(content);
// @ts-ignore
document.adoptedStyleSheets = [...document.adoptedStyleSheets, style];
}
else {
style.replaceSync(content);
}
}
else {
{
if (style && !(style instanceof HTMLStyleElement)) {
removeStyle(id);
style = undefined;
@@ -180,7 +359,7 @@ function removeStyle(id) {
if (style) {
if (style instanceof CSSStyleSheet) {
// @ts-ignore
const index = document.adoptedStyleSheets.indexOf(style);
document.adoptedStyleSheets.indexOf(style);
// @ts-ignore
document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style);
}
@@ -190,45 +369,47 @@ function removeStyle(id) {
sheetsMap.delete(id);
}
}
async function updateModule(id, changedPath, timestamp) {
const mod = hotModulesMap.get(id);
async function fetchUpdate({ path, acceptedPath, timestamp }) {
const mod = hotModulesMap.get(path);
if (!mod) {
// In a code-spliting project,
// In a code-splitting project,
// it is common that the hot-updating module is not loaded yet.
// https://github.com/vitejs/vite/issues/721
return;
}
const moduleMap = new Map();
const isSelfUpdate = id === changedPath;
const isSelfUpdate = path === acceptedPath;
// make sure we only import each dep once
const modulesToUpdate = new Set();
if (isSelfUpdate) {
// self update - only update self
modulesToUpdate.add(id);
modulesToUpdate.add(path);
}
else {
// dep update
for (const { deps } of mod.callbacks) {
if (Array.isArray(deps)) {
deps.forEach((dep) => modulesToUpdate.add(dep));
}
else {
modulesToUpdate.add(deps);
}
deps.forEach((dep) => {
if (acceptedPath === dep) {
modulesToUpdate.add(dep);
}
});
}
}
// determine the qualified callbacks before we re-import the modules
const callbacks = mod.callbacks.filter(({ deps }) => {
return Array.isArray(deps)
? deps.some((dep) => modulesToUpdate.has(dep))
: modulesToUpdate.has(deps);
const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
return deps.some((dep) => modulesToUpdate.has(dep));
});
await Promise.all(Array.from(modulesToUpdate).map(async (dep) => {
const disposer = disposeMap.get(dep);
if (disposer)
await disposer(dataMap.get(dep));
const [path, query] = dep.split(`?`);
try {
const newMod = await import(dep + (dep.includes('?') ? '&' : '?') + `t=${timestamp}`);
const newMod = await import(
/* @vite-ignore */
base +
path.slice(1) +
`?import&t=${timestamp}${query ? `&${query}` : ''}`);
moduleMap.set(dep, newMod);
}
catch (e) {
@@ -236,63 +417,107 @@ async function updateModule(id, changedPath, timestamp) {
}
}));
return () => {
for (const { deps, fn } of callbacks) {
if (Array.isArray(deps)) {
fn(deps.map((dep) => moduleMap.get(dep)));
}
else {
fn(moduleMap.get(deps));
}
for (const { deps, fn } of qualifiedCallbacks) {
fn(deps.map((dep) => moduleMap.get(dep)));
}
console.log(`[vite]: js module hot updated: `, id);
const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
console.log(`[vite] hot updated: ${loggedPath}`);
};
}
const hotModulesMap = new Map();
const disposeMap = new Map();
const pruneMap = new Map();
const dataMap = new Map();
const customUpdateMap = new Map();
export const createHotContext = (id) => {
if (!dataMap.has(id)) {
dataMap.set(id, {});
const customListenersMap = new Map();
const ctxToListenersMap = new Map();
const createHotContext = (ownerPath) => {
if (!dataMap.has(ownerPath)) {
dataMap.set(ownerPath, {});
}
// when a file is hot updated, a new context is created
// clear its stale callbacks
const mod = hotModulesMap.get(id);
const mod = hotModulesMap.get(ownerPath);
if (mod) {
mod.callbacks = [];
}
// clear stale custom event listeners
const staleListeners = ctxToListenersMap.get(ownerPath);
if (staleListeners) {
for (const [event, staleFns] of staleListeners) {
const listeners = customListenersMap.get(event);
if (listeners) {
customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
}
}
}
const newListeners = new Map();
ctxToListenersMap.set(ownerPath, newListeners);
function acceptDeps(deps, callback = () => { }) {
const mod = hotModulesMap.get(ownerPath) || {
id: ownerPath,
callbacks: []
};
mod.callbacks.push({
deps,
fn: callback
});
hotModulesMap.set(ownerPath, mod);
}
const hot = {
get data() {
return dataMap.get(id);
return dataMap.get(ownerPath);
},
accept(callback = () => { }) {
hot.acceptDeps(id, callback);
accept(deps, callback) {
if (typeof deps === 'function' || !deps) {
// self-accept: hot.accept(() => {})
acceptDeps([ownerPath], ([mod]) => deps && deps(mod));
}
else if (typeof deps === 'string') {
// explicit deps
acceptDeps([deps], ([mod]) => callback && callback(mod));
}
else if (Array.isArray(deps)) {
acceptDeps(deps, callback);
}
else {
throw new Error(`invalid hot.accept() usage.`);
}
},
acceptDeps(deps, callback = () => { }) {
const mod = hotModulesMap.get(id) || {
id,
callbacks: []
};
mod.callbacks.push({
deps: deps,
fn: callback
});
hotModulesMap.set(id, mod);
acceptDeps() {
throw new Error(`hot.acceptDeps() is deprecated. ` +
`Use hot.accept() with the same signature instead.`);
},
dispose(cb) {
disposeMap.set(id, cb);
disposeMap.set(ownerPath, cb);
},
// noop, used for static analysis only
prune(cb) {
pruneMap.set(ownerPath, cb);
},
// TODO
decline() { },
invalidate() {
// TODO should tell the server to re-perform hmr propagation
// from this module as root
location.reload();
},
// custom events
on(event, cb) {
const existing = customUpdateMap.get(event) || [];
existing.push(cb);
customUpdateMap.set(event, existing);
const addToMap = (map) => {
const existing = map.get(event) || [];
existing.push(cb);
map.set(event, existing);
};
addToMap(customListenersMap);
addToMap(newListeners);
}
};
return hot;
};
function injectQuery(url, queryToInject) {
// can't use pathname from URL since it may be relative like ../
const pathname = url.replace(/#.*$/, '').replace(/\?.*$/, '');
const { search, hash } = new URL(url, 'http://vitejs.dev');
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
}
export { createHotContext, injectQuery, removeStyle, updateStyle };

View File

@@ -1,3 +0,0 @@
export declare function jsx(tag: any, props?: null, children?: any): import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>;

View File

@@ -1,13 +0,0 @@
import { createVNode, isVNode } from 'vue';
if (import.meta.env.MODE === 'development') {
console.log(`[vue tip] You are using an non-optimized version of Vue 3 JSX, ` +
`which does not take advantage of Vue 3's runtime fast paths. An improved ` +
`JSX transform will be provided at a later stage.`);
}
const slice = Array.prototype.slice;
export function jsx(tag, props = null, children = null) {
if (arguments.length > 3 || isVNode(children)) {
children = slice.call(arguments, 2);
}
return createVNode(tag, props, children);
}

View File

@@ -1,33 +0,0 @@
export declare type HMRPayload = ConnectedPayload | UpdatePayload | FullReloadPayload | StyleRemovePayload | SWBustCachePayload | CustomPayload | MultiUpdatePayload;
interface ConnectedPayload {
type: 'connected';
}
export interface UpdatePayload {
type: 'js-update' | 'vue-reload' | 'vue-rerender' | 'style-update';
path: string;
changeSrcPath: string;
timestamp: number;
}
interface StyleRemovePayload {
type: 'style-remove';
path: string;
id: string;
}
interface FullReloadPayload {
type: 'full-reload';
path: string;
}
interface SWBustCachePayload {
type: 'sw-bust-cache';
path: string;
}
interface CustomPayload {
type: 'custom';
id: string;
customData: any;
}
export interface MultiUpdatePayload {
type: 'multi';
updates: UpdatePayload[];
}
export {};

View File

@@ -1,3 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=hmrPayload.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"hmrPayload.js","sourceRoot":"","sources":["../src/hmrPayload.ts"],"names":[],"mappings":""}

View File

@@ -1,27 +0,0 @@
declare interface ImportMeta {
readonly hot?: {
readonly data: any
accept(): void
accept(cb: (mod: any) => void): void
acceptDeps(dep: string, cb: (mod: any) => void): void
acceptDeps(deps: readonly string[], cb: (mods: any[]) => void): void
dispose(cb: (data: any) => void): void
decline(): void
invalidate(): void
on(event: string, cb: (...args: any[]) => void): void
}
readonly env: ImportMetaEnv
}
declare interface ImportMetaEnv {
[key: string]: string | boolean | undefined
BASE_URL: string
MODE: string
DEV: boolean
PROD: boolean
}

View File

@@ -1,13 +0,0 @@
/// <reference types="node" />
import { Plugin, OutputBundle } from 'rollup';
import { InternalResolver } from '../resolver';
interface AssetCacheEntry {
content?: Buffer;
fileName?: string;
url: string | undefined;
}
export declare const injectAssetRe: RegExp;
export declare const resolveAsset: (id: string, root: string, publicBase: string, assetsDir: string, inlineLimit: number) => Promise<AssetCacheEntry>;
export declare const registerAssets: (assets: Map<string, Buffer>, bundle: OutputBundle) => void;
export declare const createBuildAssetPlugin: (root: string, resolver: InternalResolver, publicBase: string, assetsDir: string, inlineLimit: number) => Plugin;
export {};

View File

@@ -1,106 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuildAssetPlugin = exports.registerAssets = exports.resolveAsset = exports.injectAssetRe = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const utils_1 = require("../utils");
const slash_1 = __importDefault(require("slash"));
const mime_types_1 = __importDefault(require("mime-types"));
const debug = require('debug')('vite:build:asset');
const assetResolveCache = new Map();
const publicDirRE = /^public(\/|\\)/;
exports.injectAssetRe = /import.meta.ROLLUP_FILE_URL_(\w+)/;
exports.resolveAsset = async (id, root, publicBase, assetsDir, inlineLimit) => {
id = utils_1.cleanUrl(id);
const cached = assetResolveCache.get(id);
if (cached) {
return cached;
}
let resolved;
const relativePath = path_1.default.relative(root, id);
if (!fs_extra_1.default.existsSync(id)) {
// try resolving from public dir
const publicDirPath = path_1.default.join(root, 'public', relativePath);
if (fs_extra_1.default.existsSync(publicDirPath)) {
// file is resolved from public dir, it will be copied verbatim so no
// need to read content here.
resolved = {
url: publicBase + slash_1.default(relativePath)
};
}
}
if (!resolved) {
if (publicDirRE.test(relativePath)) {
resolved = {
url: publicBase + slash_1.default(relativePath.replace(publicDirRE, ''))
};
}
}
if (!resolved) {
let url;
let content = await fs_extra_1.default.readFile(id);
if (!id.endsWith(`.svg`) && content.length < Number(inlineLimit)) {
url = `data:${mime_types_1.default.lookup(id)};base64,${content.toString('base64')}`;
content = undefined;
}
resolved = {
content,
fileName: path_1.default.basename(id),
url
};
}
assetResolveCache.set(id, resolved);
return resolved;
};
exports.registerAssets = (assets, bundle) => {
for (const [fileName, source] of assets) {
bundle[fileName] = {
name: fileName,
isAsset: true,
type: 'asset',
fileName,
source
};
}
};
exports.createBuildAssetPlugin = (root, resolver, publicBase, assetsDir, inlineLimit) => {
const handleToIdMap = new Map();
return {
name: 'vite:asset',
async load(id) {
if (resolver.isAssetRequest(id)) {
let { fileName, content, url } = await exports.resolveAsset(id, root, publicBase, assetsDir, inlineLimit);
if (!url && fileName && content) {
const fileHandle = this.emitFile({
name: fileName,
type: 'asset',
source: content
});
url = 'import.meta.ROLLUP_FILE_URL_' + fileHandle;
handleToIdMap.set(fileHandle, id);
}
else if (url && url.startsWith(`data:`)) {
debug(`${id} -> base64 inlined`);
}
return `export default ${JSON.stringify(url)}`;
}
},
async renderChunk(code) {
let match;
while ((match = exports.injectAssetRe.exec(code))) {
const fileHandle = match[1];
const outputFilepath = publicBase + slash_1.default(path_1.default.join(assetsDir, this.getFileName(fileHandle)));
code = code.replace(match[0], outputFilepath);
const originalId = handleToIdMap.get(fileHandle);
if (originalId) {
debug(`${originalId} -> ${outputFilepath}`);
}
}
return { code, map: null };
}
};
};
//# sourceMappingURL=buildPluginAsset.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"buildPluginAsset.js","sourceRoot":"","sources":["../../../src/node/build/buildPluginAsset.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AACvB,wDAAyB;AAEzB,oCAAmC;AACnC,kDAAyB;AACzB,4DAA6B;AAG7B,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,kBAAkB,CAAC,CAAA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ig } from '../config';
import { SFCAsyncStyleCompileOptions } from '@vue/compiler-sfc';
import { CssPreprocessOptions } from '../config';
interface BuildCssOption {
root: string;
publicBase: string;
assetsDir: string;
minify?: BuildConfig['minify'];
inlineLimit?: number;
cssCodeSplit?: boolean;
preprocessOptions?: CssPreprocessOptions;
modulesOptions?: SFCAsyncStyleCompileOptions['modulesOptions'];
}
export declare const createBuildCssPlugin: ({ root, publicBase, assetsDir, minify, inlineLimit, cssCodeSplit, preprocessOptions, modulesOptions }: BuildCssOption) => Plugin;
export {};

View File

@@ -1,157 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuildCssPlugin = void 0;
const path_1 = __importDefault(require("path"));
const buildPluginAsset_1 = require("./buildPluginAsset");
const cssUtils_1 = require("../utils/cssUtils");
const chalk_1 = __importDefault(require("chalk"));
const pluginutils_1 = require("@rollup/pluginutils");
const slash_1 = __importDefault(require("slash"));
const debug = require('debug')('vite:build:css');
const cssInjectionMarker = `__VITE_CSS__`;
const cssInjectionRE = /__VITE_CSS__\(\)/g;
exports.createBuildCssPlugin = ({ root, publicBase, assetsDir, minify = false, inlineLimit = 0, cssCodeSplit = true, preprocessOptions, modulesOptions = {} }) => {
const styles = new Map();
let staticCss = '';
return {
name: 'vite:css',
async transform(css, id) {
if (cssUtils_1.isCSSRequest(id)) {
// if this is a Vue SFC style request, it's already processed by
// rollup-plugin-vue and we just need to rewrite URLs + collect it
const isVueStyle = /\?vue&type=style/.test(id);
const preprocessLang = (id.match(cssUtils_1.cssPreprocessLangRE) ||
[])[1];
const result = isVueStyle
? css
: await cssUtils_1.compileCss(root, id, {
id: '',
source: css,
filename: id,
scoped: false,
modules: cssUtils_1.cssModuleRE.test(id),
preprocessLang,
preprocessOptions,
modulesOptions
}, true);
let modules;
if (typeof result === 'string') {
css = result;
}
else {
if (result.errors.length) {
console.error(`[vite] error applying css transforms: `);
result.errors.forEach(console.error);
}
css = result.code;
modules = result.modules;
}
// process url() - register referenced files as assets
// and rewrite the url to the resolved public path
if (cssUtils_1.urlRE.test(css)) {
const fileDir = path_1.default.dirname(id);
css = await cssUtils_1.rewriteCssUrls(css, async (rawUrl) => {
const file = path_1.default.posix.isAbsolute(rawUrl)
? path_1.default.join(root, rawUrl)
: path_1.default.join(fileDir, rawUrl);
let { fileName, content, url } = await buildPluginAsset_1.resolveAsset(file, root, publicBase, assetsDir, inlineLimit);
if (!url && fileName && content) {
url =
'import.meta.ROLLUP_FILE_URL_' +
this.emitFile({
name: fileName,
type: 'asset',
source: content
});
}
debug(`url(${rawUrl}) -> ${url.startsWith('data:') ? `base64 inlined` : `${file}`}`);
return url;
});
}
styles.set(id, css);
return {
code: modules
? pluginutils_1.dataToEsm(modules, { namedExports: true })
: (cssCodeSplit
? // If code-splitting CSS, inject a fake marker to avoid the module
// from being tree-shaken. This preserves the .css file as a
// module in the chunk's metadata so that we can retrieve them in
// renderChunk.
`${cssInjectionMarker}()\n`
: ``) + `export default ${JSON.stringify(css)}`,
map: null,
// #795 css always has side effect
moduleSideEffects: true
};
}
},
async renderChunk(code, chunk) {
let chunkCSS = '';
for (const id in chunk.modules) {
if (styles.has(id)) {
chunkCSS += styles.get(id);
}
}
let match;
while ((match = buildPluginAsset_1.injectAssetRe.exec(chunkCSS))) {
const outputFilepath = publicBase + slash_1.default(path_1.default.join(assetsDir, this.getFileName(match[1])));
chunkCSS = chunkCSS.replace(match[0], outputFilepath);
}
if (cssCodeSplit) {
code = code.replace(cssInjectionRE, '');
// for each dynamic entry chunk, collect its css and inline it as JS
// strings.
if (chunk.isDynamicEntry && chunkCSS) {
chunkCSS = minifyCSS(chunkCSS);
code =
`let ${cssInjectionMarker} = document.createElement('style');` +
`${cssInjectionMarker}.innerHTML = ${JSON.stringify(chunkCSS)};` +
`document.head.appendChild(${cssInjectionMarker});` +
code;
}
else {
staticCss += chunkCSS;
}
return {
code,
map: null
};
}
else {
staticCss += chunkCSS;
return null;
}
},
async generateBundle(_options, bundle) {
// minify css
if (minify && staticCss) {
staticCss = minifyCSS(staticCss);
}
if (staticCss) {
this.emitFile({
name: 'style.css',
type: 'asset',
source: staticCss
});
}
}
};
};
let CleanCSS;
function minifyCSS(css) {
CleanCSS = CleanCSS || require('clean-css');
const res = new CleanCSS({ level: 2, rebase: false }).minify(css);
if (res.errors && res.errors.length) {
console.error(chalk_1.default.red(`[vite] error when minifying css:`));
console.error(res.errors);
}
if (res.warnings && res.warnings.length) {
console.error(chalk_1.default.yellow(`[vite] warnings when minifying css:`));
console.error(res.warnings);
}
return res.styles;
}
//# sourceMappingURL=buildPluginCss.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"buildPluginCss.js","sourceRoot":"","sources":["../../../src/node/build/buildPluginCss.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AAEvB,yDAAgE;AAEhE,gDAO0B;AAK1B,kDAAyB;AAEzB,qDAA+C;AAC/C,kDAAyB;AAEzB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,gBAAgB,CAAC,CAAA;AAEhD,MAAM,kBAAkB,GAAG,cAAc,CAAA;AACzC,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAa7B,QAAA,oBAAoB,GAAG,CAAC,EACnC,IAAI,EACJ,UAAU,EACV,SAAS,EACT,MAAM,GAAG,KAAK,EACd,WAAW,GAAG,CAAC,EACf,YAAY,GAAG,IAAI,EACnB,iBAAiB,EACjB,cAAc,GAAG,EAAE,EACJ,EAAU,EAAE;IAC3B,MAAM,MAAM,GAAwB,IAAI,GAAG,EAAE,CAAA;IAC7C,IAAI,SAAS,GAAG,EAAE,CAAA;IAElB,OAAO;QACL,IAAI,EAAE,UAAU;QAChB,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,EAAU;YACrC,IAAI,uBAAY,CAAC,EAAE,CAAC,EAAE;gBACpB,gEAAgE;gBAChE,kEAAkE;gBAClE,MAAM,UA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;YACb,IAAI,MAAM,IAAI,SAAS,EAAE;gBACvB,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC,CAAA;aACjC;YAED,IAAI,SAAS,EAAE;gBACb,IAAI,CAAC,QAAQ,CAAC;oBACZ,IAAI,EAAE,WAAW;oBACjB,IAAI,EAAE,OAAO;oBACb,MAAM,EAAE,SAAS;iBAClB,CAAC,CAAA;aACH;QACH,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,IAAI,QAAa,CAAA;AAEjB,SAAS,SAAS,CAAC,GAAW;IAC5B,QAAQ,GAAG,QAAQ,IAAI,OAAO,CAAC,WAAW,CAAC,CAAA;IAC3C,MAAM,GAAG,GAAG,IAAI,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IAEjE,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE;QACnC,OAAO,CAAC,KAAK,CAAC,eAAK,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC,CAAA;QAC5D,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;KAC1B;IAED,IAAI,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ,CAAC,MAAM,EAAE;QACvC,OAAO,CAAC,KAAK,CAAC,eAAK,CAAC,MAAM,CAAC,qCAAqC,CAAC,CAAC,CAAA;QAClE,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;KAC5B;IAED,OAAO,GAAG,CAAC,MAAM,CAAA;AACnB,CAAC"}

View File

@@ -1,4 +0,0 @@
import { Plugin } from 'rollup';
import { SharedConfig } from '../config';
export declare const createEsbuildPlugin: (jsx?: SharedConfig['jsx']) => Promise<Plugin>;
export declare const createEsbuildRenderChunkPlugin: (target: string, minify: boolean) => Plugin;

View File

@@ -1,45 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEsbuildRenderChunkPlugin = exports.createEsbuildPlugin = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const esbuildService_1 = require("../esbuildService");
exports.createEsbuildPlugin = async (jsx = 'vue') => {
const jsxConfig = esbuildService_1.resolveJsxOptions(jsx);
return {
name: 'vite:esbuild',
resolveId(id) {
if (id === esbuildService_1.vueJsxPublicPath) {
return esbuildService_1.vueJsxPublicPath;
}
},
load(id) {
if (id === esbuildService_1.vueJsxPublicPath) {
return fs_extra_1.default.readFileSync(esbuildService_1.vueJsxFilePath, 'utf-8');
}
},
async transform(code, id) {
const isVueTs = /\.vue\?/.test(id) && id.endsWith('lang.ts');
if (esbuildService_1.tjsxRE.test(id) || isVueTs) {
return esbuildService_1.transform(code, id, {
...jsxConfig,
...(isVueTs ? { loader: 'ts' } : null)
}, jsx);
}
}
};
};
exports.createEsbuildRenderChunkPlugin = (target, minify) => {
return {
name: 'vite:esbuild-transpile',
async renderChunk(code, chunk) {
return esbuildService_1.transform(code, chunk.fileName, {
target,
minify
});
}
};
};
//# sourceMappingURL=buildPluginEsbuild.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"buildPluginEsbuild.js","sourceRoot":"","sources":["../../../src/node/build/buildPluginEsbuild.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAyB;AAEzB,sDAM0B;AAGb,QAAA,mBAAmB,GAAG,KAAK,EACtC,MAA2B,KAAK,EACf,EAAE;IACnB,MAAM,SAAS,GAAG,kCAAiB,CAAC,GAAG,CAAC,CAAA;IAExC,OAAO;QACL,IAAI,EAAE,cAAc;QAEpB,SAAS,CAAC,EAAE;YACV,IAAI,EAAE,KAAK,iCAAgB,EAAE;gBAC3B,OAAO,iCAAgB,CAAA;aACxB;QACH,CAAC;QAED,IAAI,CAAC,EAAE;YACL,IAAI,EAAE,KAAK,iCAAgB,EAAE;gBAC3B,OAAO,kBAAE,CAAC,YAAY,CAAC,+BAAc,EAAE,OAAO,CAAC,CAAA;aAChD;QACH,CAAC;QAED,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE;YACtB,MAAM,OAAO,GAAG,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAA;YAC5D,IAAI,uBAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,OAAO,EAAE;gBAC9B,OAAO,0BAAS,CACd,IAAI,EACJ,EAAE,EACF;oBACE,GAAG,SAAS;oBACZ,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;iBACvC,EACD,GAAG,CACJ,CAAA;aACF;QACH,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAEY,QAAA,8BAA8B,GAAG,CAC5C,MAAc,EACd,MAAe,EACP,EAAE;IACV,OAAO;QACL,IAAI,EAAE,wBAAwB;QAC9B,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,KAAK;YAC3B,OAAO,0BAAS,CAAC,IAAI,EAAE,KAAK,CAAC,QAAQ,EAAE;gBACrC,MAAM;gBACN,MAAM;aACP,CAAC,CAAA;QACJ,CAAC;KACF,CAAA;AACH,CAAC,CAAA"}

View File

@@ -1,10 +0,0 @@
import { Plugin, OutputChunk, RollupOutput } from 'rollup';
import { InternalResolver } from '../resolver';
import { UserConfig } from '../config';
export declare const createBuildHtmlPlugin: (root: string, indexPath: string, publicBasePath: string, assetsDir: string, inlineLimit: number, resolver: InternalResolver, shouldPreload: ((chunk: OutputChunk) => boolean) | null, config: UserConfig) => Promise<{
renderIndex: () => string;
htmlPlugin: null;
} | {
renderIndex: (bundleOutput: RollupOutput['output']) => Promise<string>;
htmlPlugin: Plugin;
}>;

View File

@@ -1,181 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuildHtmlPlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const magic_string_1 = __importDefault(require("magic-string"));
const utils_1 = require("../utils");
const buildPluginAsset_1 = require("./buildPluginAsset");
exports.createBuildHtmlPlugin = async (root, indexPath, publicBasePath, assetsDir, inlineLimit, resolver, shouldPreload, config) => {
if (!fs_extra_1.default.existsSync(indexPath)) {
return {
renderIndex: () => '',
htmlPlugin: null
};
}
const rawHtml = await fs_extra_1.default.readFile(indexPath, 'utf-8');
const preprocessedHtml = await utils_1.transformIndexHtml(rawHtml, config.indexHtmlTransforms, 'pre', true);
const assets = new Map();
let { html: processedHtml, js } = await compileHtml(root, preprocessedHtml, publicBasePath, assetsDir, inlineLimit, resolver, assets);
const htmlPlugin = {
name: 'vite:html',
async load(id) {
if (id === indexPath) {
return js;
}
},
generateBundle(_options, bundle) {
buildPluginAsset_1.registerAssets(assets, bundle);
}
};
const injectCSS = (html, filename) => {
const tag = `<link rel="stylesheet" href="${publicBasePath}${path_1.default.posix.join(assetsDir, filename)}">`;
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${tag}\n</head>`);
}
else {
return tag + '\n' + html;
}
};
const injectScript = (html, filename) => {
filename = utils_1.isExternalUrl(filename)
? filename
: `${publicBasePath}${path_1.default.posix.join(assetsDir, filename)}`;
const tag = `<script type="module" src="${filename}"></script>`;
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${tag}\n</head>`);
}
else {
return html + '\n' + tag;
}
};
const injectPreload = (html, filename) => {
filename = utils_1.isExternalUrl(filename)
? filename
: `${publicBasePath}${path_1.default.posix.join(assetsDir, filename)}`;
const tag = `<link rel="modulepreload" href="${filename}" />`;
if (/<\/head>/.test(html)) {
return html.replace(/<\/head>/, `${tag}\n</head>`);
}
else {
return tag + '\n' + html;
}
};
const renderIndex = async (bundleOutput) => {
let result = processedHtml;
for (const chunk of bundleOutput) {
if (chunk.type === 'chunk') {
if (chunk.isEntry) {
// js entry chunk
result = injectScript(result, chunk.fileName);
}
else if (shouldPreload && shouldPreload(chunk)) {
// async preloaded chunk
result = injectPreload(result, chunk.fileName);
}
}
else {
// imported css chunks
if (chunk.fileName.endsWith('.css') &&
chunk.source &&
!assets.has(chunk.fileName)) {
result = injectCSS(result, chunk.fileName);
}
}
}
return await utils_1.transformIndexHtml(result, config.indexHtmlTransforms, 'post', true);
};
return {
renderIndex,
htmlPlugin
};
};
// this extends the config in @vue/compiler-sfc with <link href>
const assetAttrsConfig = {
link: ['href'],
video: ['src', 'poster'],
source: ['src'],
img: ['src'],
image: ['xlink:href', 'href'],
use: ['xlink:href', 'href']
};
// compile index.html to a JS module, importing referenced assets
// and scripts
const compileHtml = async (root, html, publicBasePath, assetsDir, inlineLimit, resolver, assets) => {
const { parse, transform } = require('@vue/compiler-dom');
// @vue/compiler-core doesn't like lowercase doctypes
html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
const ast = parse(html);
let js = '';
const s = new magic_string_1.default(html);
const assetUrls = [];
const viteHtmlTransform = (node) => {
if (node.type === 1 /* ELEMENT */) {
if (node.tag === 'script') {
let shouldRemove = false;
const srcAttr = node.props.find((p) => p.type === 6 /* ATTRIBUTE */ && p.name === 'src');
const typeAttr = node.props.find((p) => p.type === 6 /* ATTRIBUTE */ && p.name === 'type');
const isJsModule = typeAttr && typeAttr.value && typeAttr.value.content === 'module';
if (isJsModule) {
if (srcAttr && srcAttr.value) {
if (!utils_1.isExternalUrl(srcAttr.value.content)) {
// <script type="module" src="..."/>
// add it as an import
js += `\nimport ${JSON.stringify(srcAttr.value.content)}`;
shouldRemove = true;
}
}
else if (node.children.length) {
// <script type="module">...</script>
// add its content
// TODO: if there are multiple inline module scripts on the page,
// they should technically be turned into separate modules, but
// it's hard to imagine any reason for anyone to do that.
js += `\n` + node.children[0].content.trim() + `\n`;
shouldRemove = true;
}
}
if (shouldRemove) {
// remove the script tag from the html. we are going to inject new
// ones in the end.
s.remove(node.loc.start.offset, node.loc.end.offset);
}
}
// For asset references in index.html, also generate an import
// statement for each - this will be handled by the asset plugin
const assetAttrs = assetAttrsConfig[node.tag];
if (assetAttrs) {
for (const p of node.props) {
if (p.type === 6 /* ATTRIBUTE */ &&
p.value &&
assetAttrs.includes(p.name) &&
!utils_1.isExternalUrl(p.value.content) &&
!utils_1.isDataUrl(p.value.content)) {
assetUrls.push(p);
}
}
}
}
};
transform(ast, {
nodeTransforms: [viteHtmlTransform]
});
// for each encountered asset url, rewrite original html so that it
// references the post-build location.
for (const attr of assetUrls) {
const value = attr.value;
const { fileName, content, url } = await buildPluginAsset_1.resolveAsset(resolver.requestToFile(value.content), root, publicBasePath, assetsDir, utils_1.cleanUrl(value.content).endsWith('.css') ? 0 : inlineLimit);
s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`);
if (fileName && content) {
assets.set(fileName, content);
}
}
return {
html: s.toString(),
js
};
};
//# sourceMappingURL=buildPluginHtml.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,2 +0,0 @@
import { Plugin } from 'rollup';
export declare const createBuildManifestPlugin: () => Plugin;

View File

@@ -1,26 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuildManifestPlugin = void 0;
exports.createBuildManifestPlugin = () => {
const manifest = {};
return {
name: 'vite:manifest',
generateBundle(_options, bundle) {
for (const name in bundle) {
const chunk = bundle[name];
if (chunk.type === 'chunk') {
manifest[chunk.name + '.js'] = chunk.fileName;
}
else {
manifest[chunk.name] = chunk.fileName;
}
}
this.emitFile({
fileName: 'manifest.json',
type: 'asset',
source: JSON.stringify(manifest, null, 2)
});
}
};
};
//# sourceMappingURL=buildPluginManifest.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"buildPluginManifest.js","sourceRoot":"","sources":["../../../src/node/build/buildPluginManifest.ts"],"names":[],"mappings":";;;AAEa,QAAA,yBAAyB,GAAG,GAAW,EAAE;IACpD,MAAM,QAAQ,GAA2B,EAAE,CAAA;IAC3C,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,cAAc,CAAC,QAAQ,EAAE,MAAM;YAC7B,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE;gBACzB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAA;gBAC1B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE;oBAC1B,QAAQ,CAAC,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAA;iBAC9C;qBAAM;oBACL,QAAQ,CAAC,KAAK,CAAC,IAAK,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAA;iBACvC;aACF;YACD,IAAI,CAAC,QAAQ,CAAC;gBACZ,QAAQ,EAAE,eAAe;gBACzB,IAAI,EAAE,OAAO;gBACb,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;aAC1C,CAAC,CAAA;QACJ,CAAC;KACF,CAAA;AACH,CAAC,CAAA"}

View File

@@ -1,2 +0,0 @@
import { Plugin } from 'rollup';
export declare const createReplacePlugin: (test: (id: string) => boolean, replacements: Record<string, any>, sourcemap: boolean) => Plugin;

View File

@@ -1,42 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createReplacePlugin = void 0;
const magic_string_1 = __importDefault(require("magic-string"));
exports.createReplacePlugin = (test, replacements, sourcemap) => {
const pattern = new RegExp('\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
})
.join('|') +
')\\b', 'g');
return {
name: 'vite:replace',
transform(code, id) {
if (test(id)) {
const s = new magic_string_1.default(code);
let hasReplaced = false;
let match;
while ((match = pattern.exec(code))) {
hasReplaced = true;
const start = match.index;
const end = start + match[0].length;
const replacement = '' + replacements[match[1]];
s.overwrite(start, end, replacement);
}
if (!hasReplaced) {
return null;
}
const result = { code: s.toString() };
if (sourcemap) {
result.map = s.generateMap({ hires: true });
}
return result;
}
}
};
};
//# sourceMappingURL=buildPluginReplace.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"buildPluginReplace.js","sourceRoot":"","sources":["../../../src/node/build/buildPluginReplace.ts"],"names":[],"mappings":";;;;;;AACA,gEAAsC;AAEzB,QAAA,mBAAmB,GAAG,CACjC,IAA6B,EAC7B,YAAiC,EACjC,SAAkB,EACV,EAAE;IACV,MAAM,OAAO,GAAG,IAAI,MAAM,CACxB,MAAM;QACJ,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC;aACtB,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;YACX,OAAO,GAAG,CAAC,OAAO,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAA;QACrD,CAAC,CAAC;aACD,IAAI,CAAC,GAAG,CAAC;QACZ,MAAM,EACR,GAAG,CACJ,CAAA;IAED,OAAO;QACL,IAAI,EAAE,cAAc;QACpB,SAAS,CAAC,IAAI,EAAE,EAAE;YAChB,IAAI,IAAI,CAAC,EAAE,CAAC,EAAE;gBACZ,MAAM,CAAC,GAAG,IAAI,sBAAW,CAAC,IAAI,CAAC,CAAA;gBAC/B,IAAI,WAAW,GAAG,KAAK,CAAA;gBACvB,IAAI,KAAK,CAAA;gBAET,OAAO,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE;oBACnC,WAAW,GAAG,IAAI,CAAA;oBAClB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAA;oBACzB,MAAM,GAAG,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA;oBACnC,MAAM,WAAW,GAAG,EAAE,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;oBAC/C,CAAC,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,WAAW,CAAC,CAAA;iBACrC;gBAED,IAAI,CAAC,WAAW,EAAE;oBAChB,OAAO,IAAI,CAAA;iBACZ;gBAED,MAAM,MAAM,GAAoB,EAAE,IAAI,EAAE,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAA;gBACtD,IAAI,SAAS,EAAE;oBACb,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAA;iBAC5C;gBACD,OAAO,MAAM,CAAA;aACd;QACH,CAAC;KACF,CAAA;AACH,CAAC,CAAA"}

View File

@@ -1,3 +0,0 @@
import { Plugin } from 'rollup';
import { InternalResolver } from '../resolver';
export declare const createBuildResolvePlugin: (root: string, resolver: InternalResolver) => Plugin;

View File

@@ -1,41 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuildResolvePlugin = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const resolveVue_1 = require("../utils/resolveVue");
const utils_1 = require("../utils");
const debug = require('debug')('vite:build:resolve');
exports.createBuildResolvePlugin = (root, resolver) => {
return {
name: 'vite:resolve',
async resolveId(id, importer) {
const original = id;
id = resolver.alias(id) || id;
if (id === 'vue' || id.startsWith('@vue/')) {
const vuePaths = resolveVue_1.resolveVue(root);
if (id in vuePaths) {
return vuePaths[id];
}
}
if (utils_1.isExternalUrl(id)) {
return { id, external: true };
}
if (id.startsWith('/') && !id.startsWith(root)) {
const resolved = resolver.requestToFile(id);
if (fs_extra_1.default.existsSync(resolved)) {
debug(id, `-->`, resolved);
return resolved;
}
}
// fallback to node-resolve because alias
if (id !== original) {
const resolved = await this.resolve(id, importer, { skipSelf: true });
return resolved || { id };
}
}
};
};
//# sourceMappingURL=buildPluginResolve.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":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AAO,CAAC,EAAE,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAA;gBACrE,OAAO,QAAQ,IAAI,EAAE,EAAE,EAAE,CAAA;aAC1B;QACH,CAAC;KACF,CAAA;AACH,CAAC,CAAA"}

View File

@@ -1,2 +0,0 @@
import { Plugin } from 'rollup';
export declare const createBuildWasmPlugin: (root: string, publicBase: string, assetsDir: string, inlineLimit: number) => Plugin;

View File

@@ -1,65 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuildWasmPlugin = void 0;
const buildPluginAsset_1 = require("./buildPluginAsset");
const wasmHelperId = 'vite/wasm-helper';
const wasmHelper = (opts = {}, url) => {
let instance;
if (url.startsWith('data:')) {
// @ts-ignore
const binaryString = atob(url.replace(/^data:.*?base64,/, ''));
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// @ts-ignore
instance = WebAssembly.instantiate(bytes.buffer, opts);
}
else {
// https://github.com/mdn/webassembly-examples/issues/5
// WebAssembly.instantiateStreaming requires the server to provide the
// correct MIME type for .wasm files, which unfortunately doesn't work for
// a lot of static file servers, so we just work around it by getting the
// raw buffer.
// @ts-ignore
instance = fetch(url)
// @ts-ignore
.then((r) => r.arrayBuffer())
// @ts-ignore
.then((bytes) => WebAssembly.instantiate(bytes, opts));
}
return instance.then((i) => i.instance.exports);
};
const wasmHelperCode = wasmHelper.toString();
exports.createBuildWasmPlugin = (root, publicBase, assetsDir, inlineLimit) => {
return {
name: 'vite:wasm',
resolveId(id) {
if (id === wasmHelperId) {
return id;
}
},
async load(id) {
if (id === wasmHelperId) {
return `export default ${wasmHelperCode}`;
}
if (id.endsWith('.wasm')) {
let { fileName, content, url } = await buildPluginAsset_1.resolveAsset(id, root, publicBase, assetsDir, inlineLimit);
if (!url && fileName && content) {
url =
'import.meta.ROLLUP_FILE_URL_' +
this.emitFile({
name: fileName,
type: 'asset',
source: content
});
}
return `
import initWasm from "${wasmHelperId}"
export default opts => initWasm(opts, ${JSON.stringify(url)})
`;
}
}
};
};
//# sourceMappingURL=buildPluginWasm.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"buildPluginWasm.js","sourceRoot":"","sources":["../../../src/node/build/buildPluginWasm.ts"],"names":[],"mappings":";;;AACA,yDAAiD;AAEjD,MAAM,YAAY,GAAG,kBAAkB,CAAA;AAEvC,MAAM,UAAU,GAAG,CAAC,IAAI,GAAG,EAAE,EAAE,GAAW,EAAE,EAAE;IAC5C,IAAI,QAAQ,CAAA;IACZ,IAAI,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;QAC3B,aAAa;QACb,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,kBAAkB,EAAE,EAAE,CAAC,CAAC,CAAA;QAC9D,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC,CAAA;QACjD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC5C,KAAK,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAA;SACtC;QACD,aAAa;QACb,QAAQ,GAAG,WAAW,CAAC,WAAW,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;KACvD;SAAM;QACL,uDAAuD;QACvD,sEAAsE;QACtE,0EAA0E;QAC1E,yEAAyE;QACzE,cAAc;QACd,aAAa;QACb,QAAQ,GAAG,KAAK,CAAC,GAAG,CAAC;YACnB,aAAa;aACZ,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;YAC7B,aAAa;aACZ,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAA;KACzD;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAA;AACtD,CAAC,CAAA;AAED,MAAM,cAAc,GAAG,UAAU,CAAC,QAAQ,EAAE,CAAA;AAE/B,QAAA,qBAAqB,GAAG,CACnC,IAAY,EACZ,UAAkB,EAClB,SAAiB,EACjB,WAAmB,EACX,EAAE;IACV,OAAO;QACL,IAAI,EAAE,WAAW;QAEjB,SAAS,CAAC,EAAE;YACV,IAAI,EAAE,KAAK,YAAY,EAAE;gBACvB,OAAO,EAAE,CAAA;aACV;QACH,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,EAAE;YACX,IAAI,EAAE,KAAK,YAAY,EAAE;gBACvB,OAAO,kBAAkB,cAAc,EAAE,CAAA;aAC1C;YAED,IAAI,EAAE,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;gBACxB,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,+BAAY,CACjD,EAAE,EACF,IAAI,EACJ,UAAU,EACV,SAAS,EACT,WAAW,CACZ,CAAA;gBACD,IAAI,CAAC,GAAG,IAAI,QAAQ,IAAI,OAAO,EAAE;oBAC/B,GAAG;wBACD,8BAA8B;4BAC9B,IAAI,CAAC,QAAQ,CAAC;gCACZ,IAAI,EAAE,QAAQ;gCACd,IAAI,EAAE,OAAO;gCACb,MAAM,EAAE,OAAO;6BAChB,CAAC,CAAA;iBACL;gBAED,OAAO;wBACS,YAAY;wCACI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC;CAC1D,CAAA;aACM;QACH,CAAC;KACF,CAAA;AACH,CAAC,CAAA"}

View File

@@ -1,39 +0,0 @@
import { Ora } from 'ora';
import { Plugin, InputOption, InputOptions, OutputOptions, RollupOutput } from 'rollup';
import { InternalResolver } from '../resolver';
import { BuildConfig } from '../config';
interface Build extends InputOptions {
input: InputOption;
output: OutputOptions;
/** Runs before global post-build hooks. */
onResult?: PostBuildHook;
}
export interface BuildResult {
build: Build;
html: string;
assets: RollupOutput['output'];
}
/** For adding Rollup builds and mutating the Vite config. */
export declare type BuildPlugin = (config: BuildConfig, builds: Build[]) => PostBuildHook | void;
/** Returned by `configureBuild` hook to mutate a build's output. */
export declare type PostBuildHook = (result: BuildResult) => Promise<void> | void;
export declare function onRollupWarning(spinner: Ora | undefined, options: BuildConfig['optimizeDeps']): InputOptions['onwarn'];
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
export declare function createBaseRollupPlugins(root: string, resolver: InternalResolver, options: Partial<BuildConfig>): Promise<Plugin[]>;
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
export declare function build(options: Partial<BuildConfig>): Promise<BuildResult[]>;
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
export declare function ssrBuild(options: Partial<BuildConfig>): Promise<BuildResult[]>;
export {};

View File

@@ -1,530 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ssrBuild = exports.build = exports.createBaseRollupPlugins = exports.onRollupWarning = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const chalk_1 = __importDefault(require("chalk"));
const p_map_series_1 = __importDefault(require("p-map-series"));
const json_1 = require("klona/json");
const utils_1 = require("../utils");
const resolver_1 = require("../resolver");
const buildPluginResolve_1 = require("./buildPluginResolve");
const buildPluginHtml_1 = require("./buildPluginHtml");
const buildPluginCss_1 = require("./buildPluginCss");
const buildPluginAsset_1 = require("./buildPluginAsset");
const buildPluginEsbuild_1 = require("./buildPluginEsbuild");
const buildPluginReplace_1 = require("./buildPluginReplace");
const esbuildService_1 = require("../esbuildService");
const config_1 = require("../config");
const transform_1 = require("../transform");
const hash_sum_1 = __importDefault(require("hash-sum"));
const cssUtils_1 = require("../utils/cssUtils");
const buildPluginWasm_1 = require("./buildPluginWasm");
const buildPluginManifest_1 = require("./buildPluginManifest");
const writeColors = {
[0 /* JS */]: chalk_1.default.cyan,
[1 /* CSS */]: chalk_1.default.magenta,
[2 /* ASSET */]: chalk_1.default.green,
[3 /* HTML */]: chalk_1.default.blue,
[4 /* SOURCE_MAP */]: chalk_1.default.gray
};
const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`];
const dynamicImportWarningIgnoreList = [
`Unsupported expression`,
`statically analyzed`
];
const isBuiltin = require('isbuiltin');
function onRollupWarning(spinner, options) {
return (warning, warn) => {
if (warning.code === 'UNRESOLVED_IMPORT') {
let message;
const id = warning.source;
const importer = warning.importer;
if (isBuiltin(id)) {
let importingDep;
if (importer) {
const pkg = JSON.parse(utils_1.lookupFile(importer, ['package.json']) || `{}`);
if (pkg.name) {
importingDep = pkg.name;
}
}
const allowList = options.allowNodeBuiltins;
if (importingDep && allowList && allowList.includes(importingDep)) {
return;
}
const dep = importingDep
? `Dependency ${chalk_1.default.yellow(importingDep)}`
: `A dependency`;
message =
`${dep} is attempting to import Node built-in module ${chalk_1.default.yellow(id)}.\n` +
`This will not work in a browser environment.\n` +
`Imported by: ${chalk_1.default.gray(importer)}`;
}
else {
message =
`[vite]: Rollup failed to resolve import "${warning.source}" from "${warning.importer}".\n` +
`This is most likely unintended because it can break your application at runtime.\n` +
`If you do want to externalize this module explicitly add it to\n` +
`\`rollupInputOptions.external\``;
}
if (spinner) {
spinner.stop();
}
throw new Error(message);
}
if (warning.plugin === 'rollup-plugin-dynamic-import-variables' &&
dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg))) {
return;
}
if (!warningIgnoreList.includes(warning.code)) {
// ora would swallow the console.warn if we let it keep running
// https://github.com/sindresorhus/ora/issues/90
if (spinner) {
spinner.stop();
}
warn(warning);
if (spinner) {
spinner.start();
}
}
};
}
exports.onRollupWarning = onRollupWarning;
/**
* Creates non-application specific plugins that are shared between the main
* app and the dependencies. This is used by the `optimize` command to
* pre-bundle dependencies.
*/
async function createBaseRollupPlugins(root, resolver, options) {
const { transforms = [], vueCustomBlockTransforms = {}, enableEsbuild = true, enableRollupPluginVue = true } = options;
const { nodeResolve } = require('@rollup/plugin-node-resolve');
const dynamicImport = require('rollup-plugin-dynamic-import-variables');
return [
// vite:resolve
buildPluginResolve_1.createBuildResolvePlugin(root, resolver),
// vite:esbuild
enableEsbuild ? await buildPluginEsbuild_1.createEsbuildPlugin(options.jsx) : null,
// vue
enableRollupPluginVue ? await createVuePlugin(root, options) : null,
require('@rollup/plugin-json')({
preferConst: true,
indent: ' ',
compact: false,
namedExports: true
}),
// user transforms
...(transforms.length || Object.keys(vueCustomBlockTransforms).length
? [transform_1.createBuildJsTransformPlugin(transforms, vueCustomBlockTransforms)]
: []),
nodeResolve({
rootDir: root,
extensions: resolver_1.supportedExts,
preferBuiltins: false,
dedupe: options.rollupDedupe || [],
mainFields: resolver_1.mainFields
}),
require('@rollup/plugin-commonjs')({
extensions: ['.js', '.cjs']
}),
dynamicImport({
warnOnError: true,
include: [/\.js$/],
exclude: [/node_modules/]
})
].filter(Boolean);
}
exports.createBaseRollupPlugins = createBaseRollupPlugins;
async function createVuePlugin(root, { vueCustomBlockTransforms = {}, rollupPluginVueOptions, cssPreprocessOptions, cssModuleOptions, vueCompilerOptions, vueTransformAssetUrls = {}, vueTemplatePreprocessOptions = {} }) {
const { options: postcssOptions, plugins: postcssPlugins } = await cssUtils_1.resolvePostcssOptions(root, true);
if (typeof vueTransformAssetUrls === 'object') {
vueTransformAssetUrls = {
includeAbsolute: true,
...vueTransformAssetUrls
};
}
return require('rollup-plugin-vue')({
...rollupPluginVueOptions,
templatePreprocessOptions: {
...vueTemplatePreprocessOptions,
pug: {
doctype: 'html',
...(vueTemplatePreprocessOptions && vueTemplatePreprocessOptions.pug)
}
},
transformAssetUrls: vueTransformAssetUrls,
postcssOptions,
postcssPlugins,
preprocessStyles: true,
preprocessOptions: cssPreprocessOptions,
preprocessCustomRequire: (id) => require(utils_1.resolveFrom(root, id)),
compilerOptions: vueCompilerOptions,
cssModulesOptions: {
localsConvention: 'camelCase',
generateScopedName: (local, filename) => `${local}_${hash_sum_1.default(filename)}`,
...cssModuleOptions,
...(rollupPluginVueOptions && rollupPluginVueOptions.cssModulesOptions)
},
customBlocks: Object.keys(vueCustomBlockTransforms)
});
}
/**
* Clone the given config object and fill it with default values.
*/
function prepareConfig(config) {
const { alias = {}, assetsDir = '_assets', assetsInclude = utils_1.isStaticAsset, assetsInlineLimit = 4096, base = '/', cssCodeSplit = true, cssModuleOptions = {}, cssPreprocessOptions = {}, define = {}, emitAssets = true, emitIndex = true, enableEsbuild = true, enableRollupPluginVue = true, entry = 'index.html', env = {}, esbuildTarget = 'es2020', indexHtmlTransforms = [], jsx = 'vue', minify = true, mode = 'production', optimizeDeps = {}, outDir = 'dist', resolvers = [], rollupDedupe = [], rollupInputOptions = {}, rollupOutputOptions = {}, rollupPluginVueOptions = {}, root = process.cwd(), shouldPreload = null, silent = false, sourcemap = false, terserOptions = {}, transforms = [], vueCompilerOptions = {}, vueCustomBlockTransforms = {}, vueTransformAssetUrls = {}, vueTemplatePreprocessOptions = {}, write = true } = json_1.klona(config);
return {
...config,
alias,
assetsDir,
assetsInclude,
assetsInlineLimit,
base,
cssCodeSplit,
cssModuleOptions,
cssPreprocessOptions,
define,
emitAssets,
emitIndex,
enableEsbuild,
enableRollupPluginVue,
entry,
env,
esbuildTarget,
indexHtmlTransforms,
jsx,
minify,
mode,
optimizeDeps,
outDir,
resolvers,
rollupDedupe,
rollupInputOptions,
rollupOutputOptions,
rollupPluginVueOptions,
root,
shouldPreload,
silent,
sourcemap,
terserOptions,
transforms,
vueCompilerOptions,
vueCustomBlockTransforms,
vueTransformAssetUrls,
vueTemplatePreprocessOptions,
write
};
}
/**
* Bundles the app for production.
* Returns a Promise containing the build result.
*/
async function build(options) {
const builds = [];
const config = prepareConfig(options);
const postBuildHooks = utils_1.toArray(config.configureBuild)
.map((configureBuild) => configureBuild(config, builds))
.filter(Boolean);
const { root, assetsDir, assetsInlineLimit, emitAssets, minify, silent, sourcemap, shouldPreload, env, mode: configMode, define: userDefineReplacements, write } = config;
const isTest = process.env.NODE_ENV === 'test';
const resolvedMode = process.env.VITE_ENV || configMode;
const start = Date.now();
let spinner;
const msg = `Building ${configMode} bundle...`;
if (!silent) {
if (process.env.DEBUG || isTest) {
console.log(msg);
}
else {
spinner = require('ora')(msg + '\n').start();
}
}
const outDir = path_1.default.resolve(root, config.outDir);
const indexPath = path_1.default.resolve(root, 'index.html');
const publicDir = path_1.default.join(root, 'public');
const publicBasePath = config.base.replace(/([^/])$/, '$1/'); // ensure ending slash
const resolvedAssetsPath = path_1.default.join(outDir, assetsDir);
const resolver = resolver_1.createResolver(root, config.resolvers, config.alias, config.assetsInclude);
const { htmlPlugin, renderIndex } = await buildPluginHtml_1.createBuildHtmlPlugin(root, indexPath, publicBasePath, assetsDir, assetsInlineLimit, resolver, shouldPreload, options);
const basePlugins = await createBaseRollupPlugins(root, resolver, config);
// https://github.com/darionco/rollup-plugin-web-worker-loader
// configured to support `import Worker from './my-worker?worker'`
// this plugin relies on resolveId and must be placed before node-resolve
// since the latter somehow swallows ids with query strings since 8.x
basePlugins.splice(basePlugins.findIndex((p) => p.name.includes('node-resolve')), 0, require('rollup-plugin-web-worker-loader')({
targetPlatform: 'browser',
pattern: /(.+)\?worker$/,
extensions: resolver_1.supportedExts,
sourcemap: false // it's inlined so it bloats the bundle
}));
// user env variables loaded from .env files.
// only those prefixed with VITE_ are exposed.
const userClientEnv = {};
const userEnvReplacements = {};
Object.keys(env).forEach((key) => {
if (key.startsWith(`VITE_`)) {
userEnvReplacements[`import.meta.env.${key}`] = JSON.stringify(env[key]);
userClientEnv[key] = env[key];
}
});
const builtInClientEnv = {
BASE_URL: publicBasePath,
MODE: configMode,
DEV: resolvedMode !== 'production',
PROD: resolvedMode === 'production'
};
const builtInEnvReplacements = {};
Object.keys(builtInClientEnv).forEach((key) => {
builtInEnvReplacements[`import.meta.env.${key}`] = JSON.stringify(builtInClientEnv[key]);
});
Object.keys(userDefineReplacements).forEach((key) => {
userDefineReplacements[key] = JSON.stringify(userDefineReplacements[key]);
});
const { pluginsPreBuild = [], plugins = [], pluginsPostBuild = [], pluginsOptimizer, ...rollupInputOptions } = config.rollupInputOptions;
builds.unshift({
input: config.entry,
preserveEntrySignatures: false,
treeshake: { moduleSideEffects: 'no-external' },
...rollupInputOptions,
output: config.rollupOutputOptions,
plugins: [
...plugins,
...pluginsPreBuild,
...basePlugins,
// vite:html
htmlPlugin,
// we use a custom replacement plugin because @rollup/plugin-replace
// performs replacements twice, once at transform and once at renderChunk
// - which makes it impossible to exclude Vue templates from it since
// Vue templates are compiled into js and included in chunks.
buildPluginReplace_1.createReplacePlugin((id) => !/\?vue&type=template/.test(id) &&
// also exclude css and static assets for performance
!cssUtils_1.isCSSRequest(id) &&
!resolver.isAssetRequest(id), {
...config_1.defaultDefines,
...userDefineReplacements,
...userEnvReplacements,
...builtInEnvReplacements,
'import.meta.env.': `({}).`,
'import.meta.env': JSON.stringify({
...userClientEnv,
...builtInClientEnv
}),
'process.env.NODE_ENV': JSON.stringify(resolvedMode),
'process.env.': `({}).`,
'process.env': JSON.stringify({ NODE_ENV: resolvedMode }),
'import.meta.hot': `false`
}, !!sourcemap),
// vite:css
buildPluginCss_1.createBuildCssPlugin({
root,
publicBase: publicBasePath,
assetsDir,
minify,
inlineLimit: assetsInlineLimit,
cssCodeSplit: config.cssCodeSplit,
preprocessOptions: config.cssPreprocessOptions,
modulesOptions: config.cssModuleOptions
}),
// vite:wasm
buildPluginWasm_1.createBuildWasmPlugin(root, publicBasePath, assetsDir, assetsInlineLimit),
// vite:asset
buildPluginAsset_1.createBuildAssetPlugin(root, resolver, publicBasePath, assetsDir, assetsInlineLimit),
config.enableEsbuild &&
buildPluginEsbuild_1.createEsbuildRenderChunkPlugin(config.esbuildTarget, minify === 'esbuild'),
// minify with terser
// this is the default which has better compression, but slow
// the user can opt-in to use esbuild which is much faster but results
// in ~8-10% larger file size.
minify && minify !== 'esbuild'
? require('rollup-plugin-terser').terser(config.terserOptions)
: undefined,
// #728 user plugins should apply after `@rollup/plugin-commonjs`
// #471#issuecomment-683318951 user plugin after internal plugin
...pluginsPostBuild,
// vite:manifest
config.emitManifest ? buildPluginManifest_1.createBuildManifestPlugin() : undefined
].filter(Boolean)
});
// lazy require rollup so that we don't load it when only using the dev server
// importing it just for the types
const rollup = require('rollup').rollup;
// multiple builds are processed sequentially, in case a build
// depends on the output of a preceding build.
const results = await p_map_series_1.default(builds, async (build, i) => {
const { output: outputOptions, onResult, ...inputOptions } = build;
let result;
let indexHtml;
let indexHtmlPath = getIndexHtmlOutputPath(build);
const emitIndex = config.emitIndex && indexHtmlPath !== null;
try {
const bundle = await rollup({
onwarn: onRollupWarning(spinner, config.optimizeDeps),
...inputOptions,
plugins: [
...(inputOptions.plugins || []).filter(
// remove vite:emit in case this build copied another build's plugins
(plugin) => plugin.name !== 'vite:emit'),
// vite:emit
createEmitPlugin(emitAssets, async (assets) => {
indexHtml = emitIndex ? await renderIndex(assets) : '';
result = { build, assets, html: indexHtml };
if (onResult) {
await onResult(result);
}
// run post-build hooks sequentially
await postBuildHooks.reduce((queue, hook) => queue.then(() => hook(result)), Promise.resolve());
if (write) {
if (i === 0) {
await fs_extra_1.default.emptyDir(outDir);
}
if (emitIndex) {
indexHtmlPath = path_1.default.join(outDir, indexHtmlPath);
await fs_extra_1.default.writeFile(indexHtmlPath, indexHtml);
}
}
})
]
});
await bundle[write ? 'write' : 'generate']({
dir: resolvedAssetsPath,
format: 'es',
sourcemap,
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
assetFileNames: `[name].[hash].[ext]`,
...outputOptions
});
}
finally {
spinner && spinner.stop();
}
if (write && !silent) {
if (emitIndex) {
printFileInfo(indexHtmlPath, indexHtml, 3 /* HTML */);
}
for (const chunk of result.assets) {
if (chunk.type === 'chunk') {
const filePath = path_1.default.join(resolvedAssetsPath, chunk.fileName);
printFileInfo(filePath, chunk.code, 0 /* JS */);
if (chunk.map) {
printFileInfo(filePath + '.map', chunk.map.toString(), 4 /* SOURCE_MAP */);
}
}
else if (emitAssets && chunk.source)
printFileInfo(path_1.default.join(resolvedAssetsPath, chunk.fileName), chunk.source, chunk.fileName.endsWith('.css') ? 1 /* CSS */ : 2 /* ASSET */);
}
}
spinner && spinner.start();
return result;
});
// copy over /public if it exists
if (write && emitAssets && fs_extra_1.default.existsSync(publicDir)) {
for (const file of await fs_extra_1.default.readdir(publicDir)) {
await fs_extra_1.default.copy(path_1.default.join(publicDir, file), path_1.default.resolve(outDir, file));
}
}
spinner && spinner.stop();
if (!silent) {
console.log(`Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n`);
}
// stop the esbuild service after each build
await esbuildService_1.stopService();
return results;
}
exports.build = build;
/**
* Bundles the app in SSR mode.
* - All Vue dependencies are automatically externalized
* - Imports to dependencies are compiled into require() calls
* - Templates are compiled with SSR specific optimizations.
*/
async function ssrBuild(options) {
const { rollupInputOptions, rollupOutputOptions, rollupPluginVueOptions } = options;
return build({
outDir: 'dist-ssr',
...options,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...rollupInputOptions,
external: resolveExternal(rollupInputOptions && rollupInputOptions.external)
},
rollupOutputOptions: {
...rollupOutputOptions,
format: 'cjs',
exports: 'named',
entryFileNames: '[name].js',
// 764 add `Symbol.toStringTag` when build es module into cjs chunk
namespaceToStringTag: true
},
emitIndex: false,
emitAssets: false,
cssCodeSplit: false,
minify: false
});
}
exports.ssrBuild = ssrBuild;
function createEmitPlugin(emitAssets, emit) {
return {
name: 'vite:emit',
async generateBundle(_, output) {
// assume the first asset in `output` is an entry chunk
const assets = Object.values(output);
// process the output before writing
await emit(assets);
// write any assets injected by post-build hooks
for (const asset of assets) {
output[asset.fileName] = asset;
}
// remove assets from bundle if emitAssets is false
if (!emitAssets) {
for (const name in output) {
if (output[name].type === 'asset') {
delete output[name];
}
}
}
}
};
}
/**
* Resolve the output path of `index.html` for the given build (relative to
* `outDir` in Vite config).
*/
function getIndexHtmlOutputPath(build) {
const { input, output } = build;
return input === 'index.html' ? output.file || input : null;
}
function resolveExternal(userExternal) {
const required = ['vue', /^@vue\//];
if (!userExternal) {
return required;
}
if (Array.isArray(userExternal)) {
return [...required, ...userExternal];
}
else if (typeof userExternal === 'function') {
return (src, importer, isResolved) => {
if (src === 'vue' || /^@vue\//.test(src)) {
return true;
}
return userExternal(src, importer, isResolved);
};
}
else {
return [...required, userExternal];
}
}
function printFileInfo(filePath, content, type) {
const needCompression = type === 0 /* JS */ || type === 1 /* CSS */ || type === 3 /* HTML */;
const compressed = needCompression
? `, brotli: ${(require('brotli-size').sync(content) / 1024).toFixed(2)}kb`
: ``;
console.log(`${chalk_1.default.gray(`[write]`)} ${writeColors[type](path_1.default.relative(process.cwd(), filePath))} ${(content.length / 1024).toFixed(2)}kb${compressed}`);
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
export {};

14287
node_modules/vite/dist/node/cli.js generated vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,410 +0,0 @@
/// <reference types="node" />
import { DotenvParseOutput } from 'dotenv';
import { Options as RollupPluginVueOptions } from 'rollup-plugin-vue';
import { CompilerOptions, SFCStyleCompileOptions, SFCAsyncStyleCompileOptions, SFCTemplateCompileOptions } from '@vue/compiler-sfc';
import { InputOptions as RollupInputOptions, OutputOptions as RollupOutputOptions, Plugin as RollupPlugin, OutputChunk } from 'rollup';
import { BuildPlugin } from './build';
import { Context, ServerPlugin } from './server';
import { Resolver } from './resolver';
import { Transform, CustomBlockTransform, IndexHtmlTransform } from './transform';
import { DepOptimizationOptions } from './optimizer';
import { ServerOptions } from 'https';
import { Options as RollupTerserOptions } from 'rollup-plugin-terser';
import { ProxiesOptions } from './server/serverPluginProxy';
export declare type PreprocessLang = NonNullable<SFCStyleCompileOptions['preprocessLang']>;
export declare type PreprocessOptions = SFCStyleCompileOptions['preprocessOptions'];
export declare type CssPreprocessOptions = Partial<Record<PreprocessLang, PreprocessOptions>>;
/**
* https://github.com/koajs/cors#corsoptions
*/
export interface CorsOptions {
/**
* `Access-Control-Allow-Origin`, default is request Origin header
*/
origin?: string | ((ctx: Context) => string);
/**
* `Access-Control-Allow-Methods`, default is 'GET,HEAD,PUT,POST,DELETE,PATCH'
*/
allowMethods?: string | string[];
/**
* `Access-Control-Expose-Headers`
*/
exposeHeaders?: string | string[];
/**
* `Access-Control-Allow-Headers`
*/
allowHeaders?: string | string[];
/**
* `Access-Control-Max-Age` in seconds
*/
maxAge?: string | number;
/**
* `Access-Control-Allow-Credentials`, default is false
*/
credentials?: boolean | ((ctx: Context) => boolean);
/**
* Add set headers to `err.header` if an error is thrown
*/
keepHeadersOnError?: boolean;
}
export { Resolver, Transform };
/**
* Options shared between server and build.
*/
export interface SharedConfig {
/**
* Project root directory. Can be an absolute path, or a path relative from
* the location of the config file itself.
* @default process.cwd()
*/
root?: string;
/**
* Import alias. The entries can either be exact request -> request mappings
* (exact, no wildcard syntax), or request path -> fs directory mappings.
* When using directory mappings, the key **must start and end with a slash**.
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* alias: {
* // alias package names
* 'react': '@pika/react',
* 'react-dom': '@pika/react-dom'
*
* // alias a path to a fs directory
* // the key must start and end with a slash
* '/@foo/': path.resolve(__dirname, 'some-special-dir')
* }
* }
* ```
*/
alias?: Record<string, string>;
/**
* Function that tests a file path for inclusion as a static asset.
*/
assetsInclude?: (file: string) => boolean;
/**
* Custom file transforms.
*/
transforms?: Transform[];
/**
* Custom index.html transforms.
*/
indexHtmlTransforms?: IndexHtmlTransform[];
/**
* Define global variable replacements.
* Entries will be defined on `window` during dev and replaced during build.
*/
define?: Record<string, any>;
/**
* Resolvers to map dev server public path requests to/from file system paths,
* and optionally map module ids to public path requests.
*/
resolvers?: Resolver[];
/**
* Configure dep optimization behavior.
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* optimizeDeps: {
* exclude: ['dep-a', 'dep-b']
* }
* }
* ```
*/
optimizeDeps?: DepOptimizationOptions;
/**
* Options to pass to `@vue/compiler-dom`
*
* https://github.com/vuejs/vue-next/blob/master/packages/compiler-core/src/options.ts
*/
vueCompilerOptions?: CompilerOptions;
/**
* Configure what tags/attributes to trasnform into asset url imports,
* or disable the transform altogether with `false`.
*/
vueTransformAssetUrls?: SFCTemplateCompileOptions['transformAssetUrls'];
/**
* The options for template block preprocessor render.
*/
vueTemplatePreprocessOptions?: Record<string, SFCTemplateCompileOptions['preprocessOptions']>;
/**
* Transform functions for Vue custom blocks.
*
* Example `vue.config.js`:
* ``` js
* module.exports = {
* vueCustomBlockTransforms: {
* i18n: src => `export default Comp => { ... }`
* }
* }
* ```
*/
vueCustomBlockTransforms?: Record<string, CustomBlockTransform>;
/**
* Configure what to use for jsx factory and fragment.
* @default 'vue'
*/
jsx?: 'vue' | 'preact' | 'react' | {
factory?: string;
fragment?: string;
};
/**
* Environment mode
*/
mode?: string;
/**
* CSS preprocess options
*/
cssPreprocessOptions?: CssPreprocessOptions;
/**
* CSS modules options
*/
cssModuleOptions?: SFCAsyncStyleCompileOptions['modulesOptions'];
/**
* Enable esbuild
* @default true
*/
enableEsbuild?: boolean;
/**
* Environment variables parsed from .env files
* only ones starting with VITE_ are exposed on `import.meta.env`
* @internal
*/
env?: DotenvParseOutput;
}
export interface HmrConfig {
protocol?: string;
hostname?: string;
port?: number;
path?: string;
}
export interface ServerConfig extends SharedConfig {
/**
* Configure hmr websocket connection.
*/
hmr?: HmrConfig | boolean;
/**
* Configure dev server hostname.
*/
hostname?: string;
port?: number;
open?: boolean;
/**
* Configure https.
*/
https?: boolean;
httpsOptions?: ServerOptions;
/**
* Configure custom proxy rules for the dev server. Uses
* [`koa-proxies`](https://github.com/vagusX/koa-proxies) which in turn uses
* [`http-proxy`](https://github.com/http-party/node-http-proxy). Each key can
* be a path Full options
* [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxiesOptions>;
/**
* Configure CORS for the dev server.
* Uses [@koa/cors](https://github.com/koajs/cors).
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean;
/**
* A plugin function that configures the dev server. Receives a server plugin
* context object just like the internal server plugins. Can also be an array
* of multiple server plugin functions.
*/
configureServer?: ServerPlugin | ServerPlugin[];
}
export interface BuildConfig extends Required<SharedConfig> {
/**
* Entry. Use this to specify a js entry file in use cases where an
* `index.html` does not exist (e.g. serving vite assets from a different host)
* @default 'index.html'
*/
entry: string;
/**
* Base public path when served in production.
* @default '/'
*/
base: string;
/**
* Directory relative from `root` where build output will be placed. If the
* directory exists, it will be removed before the build.
* @default 'dist'
*/
outDir: string;
/**
* Directory relative from `outDir` where the built js/css/image assets will
* be placed.
* @default '_assets'
*/
assetsDir: string;
/**
* Static asset files smaller than this number (in bytes) will be inlined as
* base64 strings. Default limit is `4096` (4kb). Set to `0` to disable.
* @default 4096
*/
assetsInlineLimit: number;
/**
* Whether to code-split CSS. When enabled, CSS in async chunks will be
* inlined as strings in the chunk and inserted via dynamically created
* style tags when the chunk is loaded.
* @default true
*/
cssCodeSplit: boolean;
/**
* Whether to generate sourcemap
* @default false
*/
sourcemap: boolean | 'inline';
/**
* Set to `false` to disable minification, or specify the minifier to use.
* Available options are 'terser' or 'esbuild'.
* @default 'terser'
*/
minify: boolean | 'terser' | 'esbuild';
/**
* The option for `terser`
*/
terserOptions: RollupTerserOptions;
/**
* Transpile target for esbuild.
* @default 'es2020'
*/
esbuildTarget: string;
/**
* Build for server-side rendering, only as a CLI flag
* for programmatic usage, use `ssrBuild` directly.
* @internal
*/
ssr?: boolean;
/**
* Will be passed to rollup.rollup()
*
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupInputOptions: ViteRollupInputOptions;
/**
* Will be passed to bundle.generate()
*
* https://rollupjs.org/guide/en/#big-list-of-options
*/
rollupOutputOptions: RollupOutputOptions;
/**
* Will be passed to rollup-plugin-vue
*
* https://github.com/vuejs/rollup-plugin-vue/blob/next/src/index.ts
*/
rollupPluginVueOptions: Partial<RollupPluginVueOptions>;
/**
* Will be passed to @rollup/plugin-node-resolve
* https://github.com/rollup/plugins/tree/master/packages/node-resolve#dedupe
*/
rollupDedupe: string[];
/**
* Whether to log asset info to console
* @default false
*/
silent: boolean;
/**
* Whether to write bundle to disk
* @default true
*/
write: boolean;
/**
* Whether to emit index.html
* @default true
*/
emitIndex: boolean;
/**
* Whether to emit assets other than JavaScript
* @default true
*/
emitAssets: boolean;
/**
* Whether to emit a manifest.json under assets dir to map hash-less filenames
* to their hashed versions. Useful when you want to generate your own HTML
* instead of using the one generated by Vite.
*
* Example:
*
* ```json
* {
* "main.js": "main.68fe3fad.js",
* "style.css": "style.e6b63442.css"
* }
* ```
* @default false
*/
emitManifest?: boolean;
/**
* Predicate function that determines whether a link rel=modulepreload shall be
* added to the index.html for the chunk passed in
*/
shouldPreload: ((chunk: OutputChunk) => boolean) | null;
/**
* Enable 'rollup-plugin-vue'
* @default true
*/
enableRollupPluginVue?: boolean;
/**
* Plugin functions that mutate the Vite build config. The `builds` array can
* be added to if the plugin wants to add another Rollup build that Vite writes
* to disk. Return a function to gain access to each build's output.
* @internal
*/
configureBuild?: BuildPlugin | BuildPlugin[];
}
export interface ViteRollupInputOptions extends RollupInputOptions {
/**
* @deprecated use `pluginsPreBuild` or `pluginsPostBuild` instead
*/
plugins?: RollupPlugin[];
/**
* Rollup plugins that passed before Vite's transform plugins
*/
pluginsPreBuild?: RollupPlugin[];
/**
* Rollup plugins that passed after Vite's transform plugins
*/
pluginsPostBuild?: RollupPlugin[];
/**
* Rollup plugins for optimizer
*/
pluginsOptimizer?: RollupPlugin[];
}
export interface UserConfig extends Partial<BuildConfig>, ServerConfig {
plugins?: Plugin[];
}
export interface Plugin extends Pick<UserConfig, 'alias' | 'transforms' | 'indexHtmlTransforms' | 'define' | 'resolvers' | 'configureBuild' | 'configureServer' | 'vueCompilerOptions' | 'vueTransformAssetUrls' | 'vueTemplatePreprocessOptions' | 'vueCustomBlockTransforms' | 'rollupInputOptions' | 'rollupOutputOptions' | 'enableRollupPluginVue'> {
}
export declare type ResolvedConfig = UserConfig & {
/**
* Path of config file.
*/
__path?: string;
};
export declare function resolveConfig(mode: string, configPath?: string): Promise<ResolvedConfig | undefined>;
export declare const defaultDefines: {
__VUE_OPTIONS_API__: boolean;
__VUE_PROD_DEVTOOLS__: boolean;
};

257
node_modules/vite/dist/node/config.js generated vendored
View File

@@ -1,257 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultDefines = exports.resolveConfig = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const chalk_1 = __importDefault(require("chalk"));
const dotenv_1 = __importDefault(require("dotenv"));
const dotenv_expand_1 = __importDefault(require("dotenv-expand"));
const buildPluginEsbuild_1 = require("./build/buildPluginEsbuild");
const resolver_1 = require("./resolver");
const utils_1 = require("./utils");
const debug = require('debug')('vite:config');
async function resolveConfig(mode, configPath) {
const start = Date.now();
const cwd = process.cwd();
let config;
let resolvedPath;
let isTS = false;
if (configPath) {
resolvedPath = path_1.default.resolve(cwd, configPath);
}
else {
const jsConfigPath = path_1.default.resolve(cwd, 'vite.config.js');
if (fs_extra_1.default.existsSync(jsConfigPath)) {
resolvedPath = jsConfigPath;
}
else {
const tsConfigPath = path_1.default.resolve(cwd, 'vite.config.ts');
if (fs_extra_1.default.existsSync(tsConfigPath)) {
isTS = true;
resolvedPath = tsConfigPath;
}
}
}
if (!resolvedPath) {
// load environment variables
return {
env: loadEnv(mode, cwd)
};
}
try {
if (!isTS) {
try {
config = require(resolvedPath);
}
catch (e) {
if (!/Cannot use import statement|Unexpected token 'export'|Must use import to load ES Module/.test(e.message)) {
throw e;
}
}
}
if (!config) {
// 2. if we reach here, the file is ts or using es import syntax, or
// the user has type: "module" in their package.json (#917)
// transpile es import syntax to require syntax using rollup.
const rollup = require('rollup');
const esbuildPlugin = await buildPluginEsbuild_1.createEsbuildPlugin({});
const esbuildRenderChunkPlugin = buildPluginEsbuild_1.createEsbuildRenderChunkPlugin('es2019', false);
// use node-resolve to support .ts files
const nodeResolve = require('@rollup/plugin-node-resolve').nodeResolve({
extensions: resolver_1.supportedExts
});
const bundle = await rollup.rollup({
external: (id) => (id[0] !== '.' && !path_1.default.isAbsolute(id)) ||
id.slice(-5, id.length) === '.json',
input: resolvedPath,
treeshake: false,
plugins: [esbuildPlugin, nodeResolve, esbuildRenderChunkPlugin]
});
const { output: [{ code }] } = await bundle.generate({
exports: 'named',
format: 'cjs'
});
config = await loadConfigFromBundledFile(resolvedPath, code);
}
if (typeof config === 'function') {
config = config(mode);
}
// normalize config root to absolute
if (config.root && !path_1.default.isAbsolute(config.root)) {
config.root = path_1.default.resolve(path_1.default.dirname(resolvedPath), config.root);
}
if (typeof config.vueTransformAssetUrls === 'object') {
config.vueTransformAssetUrls = normalizeAssetUrlOptions(config.vueTransformAssetUrls);
}
// resolve plugins
if (config.plugins) {
for (const plugin of config.plugins) {
config = resolvePlugin(config, plugin);
}
}
config.env = {
...config.env,
...loadEnv(mode, config.root || cwd)
};
debug(`config resolved in ${Date.now() - start}ms`);
config.__path = resolvedPath;
return config;
}
catch (e) {
console.error(chalk_1.default.red(`[vite] failed to load config from ${resolvedPath}:`));
console.error(e);
process.exit(1);
}
}
exports.resolveConfig = resolveConfig;
async function loadConfigFromBundledFile(fileName, bundledCode) {
const extension = path_1.default.extname(fileName);
const defaultLoader = require.extensions[extension];
require.extensions[extension] = (module, filename) => {
if (filename === fileName) {
;
module._compile(bundledCode, filename);
}
else {
defaultLoader(module, filename);
}
};
delete require.cache[fileName];
const raw = require(fileName);
const config = raw.__esModule ? raw.default : raw;
require.extensions[extension] = defaultLoader;
return config;
}
function resolvePlugin(config, plugin) {
return {
...config,
...plugin,
alias: {
...plugin.alias,
...config.alias
},
define: {
...plugin.define,
...config.define
},
transforms: [...(config.transforms || []), ...(plugin.transforms || [])],
indexHtmlTransforms: [
...(config.indexHtmlTransforms || []),
...(plugin.indexHtmlTransforms || [])
],
resolvers: [...(config.resolvers || []), ...(plugin.resolvers || [])],
configureServer: [].concat(config.configureServer || [], plugin.configureServer || []),
configureBuild: [].concat(config.configureBuild || [], plugin.configureBuild || []),
vueCompilerOptions: {
...config.vueCompilerOptions,
...plugin.vueCompilerOptions
},
vueTransformAssetUrls: mergeAssetUrlOptions(config.vueTransformAssetUrls, plugin.vueTransformAssetUrls),
vueTemplatePreprocessOptions: {
...config.vueTemplatePreprocessOptions,
...plugin.vueTemplatePreprocessOptions
},
vueCustomBlockTransforms: {
...config.vueCustomBlockTransforms,
...plugin.vueCustomBlockTransforms
},
rollupInputOptions: mergeObjectOptions(config.rollupInputOptions, plugin.rollupInputOptions),
rollupOutputOptions: mergeObjectOptions(config.rollupOutputOptions, plugin.rollupOutputOptions),
enableRollupPluginVue: config.enableRollupPluginVue || plugin.enableRollupPluginVue
};
}
function mergeAssetUrlOptions(to, from) {
if (from === true) {
return to;
}
if (from === false) {
return from;
}
if (typeof to === 'boolean') {
return from || to;
}
return {
...normalizeAssetUrlOptions(to),
...normalizeAssetUrlOptions(from)
};
}
function normalizeAssetUrlOptions(o) {
if (o && Object.keys(o).some((key) => Array.isArray(o[key]))) {
return {
tags: o
};
}
else {
return o;
}
}
function mergeObjectOptions(to, from) {
if (!to)
return from;
if (!from)
return to;
const res = { ...to };
for (const key in from) {
const existing = res[key];
const toMerge = from[key];
if (Array.isArray(existing) || Array.isArray(toMerge)) {
res[key] = [].concat(existing, toMerge).filter(Boolean);
}
else {
res[key] = toMerge;
}
}
return res;
}
function loadEnv(mode, root) {
if (mode === 'local') {
throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
`the .local postfix for .env files.`);
}
debug(`env mode: ${mode}`);
const clientEnv = {};
const envFiles = [
/** mode local file */ `.env.${mode}.local`,
/** mode file */ `.env.${mode}`,
/** local file */ `.env.local`,
/** default file */ `.env`
];
for (const file of envFiles) {
const path = utils_1.lookupFile(root, [file], true);
if (path) {
// NOTE: this mutates process.env
const { parsed, error } = dotenv_1.default.config({
debug: !!process.env.DEBUG || undefined,
path
});
if (!parsed) {
throw error;
}
// NOTE: this mutates process.env
dotenv_expand_1.default({ parsed });
// set NODE_ENV under a different key so that we know this is set from
// vite-loaded .env files. Some users may have default NODE_ENV set in
// their system.
if (parsed.NODE_ENV) {
process.env.VITE_ENV = parsed.NODE_ENV;
}
// only keys that start with VITE_ are exposed.
for (const [key, value] of Object.entries(parsed)) {
if (key.startsWith(`VITE_`)) {
clientEnv[key] = value;
}
}
}
}
debug(`env: %O`, clientEnv);
return clientEnv;
}
// TODO move this into Vue plugin when we extract it
exports.defaultDefines = {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false
};
//# sourceMappingURL=config.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,14 +0,0 @@
import { TransformOptions } from 'esbuild';
import { SharedConfig } from './config';
export declare const tjsxRE: RegExp;
export declare const vueJsxPublicPath = "/vite/jsx";
export declare const vueJsxFilePath: string;
export declare function resolveJsxOptions(options?: SharedConfig['jsx']): Pick<TransformOptions, "jsxFactory" | "jsxFragment"> | undefined;
export declare const stopService: () => Promise<void>;
export declare const transform: (src: string, request: string, options?: TransformOptions, jsxOption?: SharedConfig['jsx']) => Promise<{
code: string;
map: string;
} | {
code: string;
map: undefined;
}>;

View File

@@ -1,114 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transform = exports.stopService = exports.resolveJsxOptions = exports.vueJsxFilePath = exports.vueJsxPublicPath = exports.tjsxRE = void 0;
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const esbuild_1 = require("esbuild");
const utils_1 = require("./utils");
const debug = require('debug')('vite:esbuild');
exports.tjsxRE = /\.(tsx?|jsx)$/;
exports.vueJsxPublicPath = '/vite/jsx';
exports.vueJsxFilePath = path_1.default.resolve(__dirname, '../client/vueJsxCompat.js');
const JsxPresets = {
vue: { jsxFactory: 'jsx', jsxFragment: 'Fragment' },
preact: { jsxFactory: 'h', jsxFragment: 'Fragment' },
react: {} // use esbuild default
};
function resolveJsxOptions(options = 'vue') {
if (typeof options === 'string') {
if (!(options in JsxPresets)) {
console.error(`[vite] unknown jsx preset: '${options}'.`);
}
return JsxPresets[options] || {};
}
else if (options) {
return {
jsxFactory: options.factory,
jsxFragment: options.fragment
};
}
}
exports.resolveJsxOptions = resolveJsxOptions;
// lazy start the service
let _servicePromise;
const ensureService = async () => {
if (!_servicePromise) {
_servicePromise = esbuild_1.startService();
}
return _servicePromise;
};
exports.stopService = async () => {
if (_servicePromise) {
const service = await _servicePromise;
service.stop();
_servicePromise = undefined;
}
};
// transform used in server plugins with a more friendly API
exports.transform = async (src, request, options = {}, jsxOption) => {
const service = await ensureService();
const file = utils_1.cleanUrl(request);
options = {
loader: options.loader || path_1.default.extname(file).slice(1),
sourcemap: true,
// ensure source file name contains full query
sourcefile: request,
target: 'es2020',
...options
};
try {
const result = await service.transform(src, options);
if (result.warnings.length) {
console.error(`[vite] warnings while transforming ${file} with esbuild:`);
result.warnings.forEach((m) => printMessage(m, src));
}
let code = result.js;
// if transpiling (j|t)sx file, inject the imports for the jsx helper and
// Fragment.
if (file.endsWith('x')) {
if (!jsxOption || jsxOption === 'vue') {
code +=
`\nimport { jsx } from '${exports.vueJsxPublicPath}'` +
`\nimport { Fragment } from 'vue'`;
}
if (jsxOption === 'preact') {
code += `\nimport { h, Fragment } from 'preact'`;
}
}
return {
code,
map: result.jsSourceMap
};
}
catch (e) {
console.error(chalk_1.default.red(`[vite] error while transforming ${file} with esbuild:`));
if (e.errors) {
e.errors.forEach((m) => printMessage(m, src));
}
else {
console.error(e);
}
debug(`options used: `, options);
return {
code: '',
map: undefined
};
}
};
function printMessage(m, code) {
console.error(chalk_1.default.yellow(m.text));
if (m.location) {
const lines = code.split(/\r?\n/g);
const line = Number(m.location.line);
const column = Number(m.location.column);
const offset = lines
.slice(0, line - 1)
.map((l) => l.length)
.reduce((total, l) => total + l + 1, 0) + column;
console.error(require('@vue/compiler-dom').generateCodeFrame(code, offset, offset + 1));
}
}
//# sourceMappingURL=esbuildService.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"esbuildService.js","sourceRoot":"","sources":["../../src/node/esbuildService.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AACvB,kDAAyB;AACzB,qCAMgB;AAEhB,mCAAkC;AAElC,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAA;AAEjC,QAAA,MAAM,GAAG,eAAe,CAAA;AAExB,QAAA,gBAAgB,GAAG,WAAW,CAAA;AAE9B,QAAA,cAAc,GAAG,cAAI,CAAC,OAAO,CACxC,SAAS,EACT,2BAA2B,CAC5B,CAAA;AAED,MAAM,UAAU,GAGZ;IACF,GAAG,EAAE,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE;IACnD,MAAM,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE;IACpD,KAAK,EAAE,EAAE,CAAC,sBAAsB;CACjC,CAAA;AAED,SAAgB,iBAAiB,CAAC,UAA+B,KAAK;IACpE,IAAI,OAAO,OAAO,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EAAE,IAAY;IAC5C,OAAO,CAAC,KAAK,CAAC,eAAK,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAA;IACnC,IAAI,CAAC,CAAC,QAAQ,EAAE;QACd,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QAClC,MAAM,IAAI,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;QACpC,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;QACxC,MAAM,MAAM,GACV,KAAK;aACF,KAAK,CAAC,CAAC,EAAE,IAAI,GAAG,CAAC,CAAC;aAClB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;aACpB,MAAM,CAAC,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAA;QACpD,OAAO,CAAC,KAAK,CACX,OAAO,CAAC,mBAAmB,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,CACzE,CAAA;KACF;AACH,CAAC"}

2417
node_modules/vite/dist/node/index.d.ts generated vendored

File diff suppressed because it is too large Load Diff

68
node_modules/vite/dist/node/index.js generated vendored
View File

@@ -1,24 +1,44 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.injectScriptToHtml = exports.isImportRequest = exports.isStaticAsset = exports.cachedRead = exports.readBody = void 0;
__exportStar(require("./server"), exports);
__exportStar(require("./build"), exports);
__exportStar(require("./optimizer"), exports);
__exportStar(require("./config"), exports);
var utils_1 = require("./utils");
Object.defineProperty(exports, "readBody", { enumerable: true, get: function () { return utils_1.readBody; } });
Object.defineProperty(exports, "cachedRead", { enumerable: true, get: function () { return utils_1.cachedRead; } });
Object.defineProperty(exports, "isStaticAsset", { enumerable: true, get: function () { return utils_1.isStaticAsset; } });
Object.defineProperty(exports, "isImportRequest", { enumerable: true, get: function () { return utils_1.isImportRequest; } });
Object.defineProperty(exports, "injectScriptToHtml", { enumerable: true, get: function () { return utils_1.injectScriptToHtml; } });
//# sourceMappingURL=index.js.map
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var build = require('./chunks/dep-1bdbec90.js');
require('os');
require('fs');
require('path');
require('tty');
require('util');
require('net');
require('events');
require('url');
require('http');
require('stream');
require('zlib');
require('resolve');
require('module');
require('readline');
require('crypto');
require('worker_threads');
require('assert');
require('https');
require('tls');
require('buffer');
require('child_process');
require('querystring');
exports.build = build.build;
exports.createLogger = build.createLogger;
exports.createServer = build.createServer;
exports.defineConfig = build.defineConfig;
exports.loadConfigFromFile = build.loadConfigFromFile;
exports.loadEnv = build.loadEnv;
exports.mergeConfig = build.mergeConfig;
exports.normalizePath = build.normalizePath;
exports.optimizeDeps = build.optimizeDeps;
exports.resolveConfig = build.resolveConfig;
exports.resolvePackageData = build.resolvePackageData;
exports.resolvePackageEntry = build.resolvePackageEntry;
exports.send = build.send;
exports.sortUserPlugins = build.sortUserPlugins;

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,2CAAwB;AACxB,0CAAuB;AACvB,8CAA2B;AAC3B,2CAAwB;AACxB,iCAMgB;AALd,iGAAA,QAAQ,OAAA;AACR,mGAAA,UAAU,OAAA;AACV,sGAAA,aAAa,OAAA;AACb,wGAAA,eAAe,OAAA;AACf,2GAAA,kBAAkB,OAAA"}

View File

@@ -1,33 +0,0 @@
import { ResolvedConfig } from '../config';
export interface DepOptimizationOptions {
/**
* Force optimize listed dependencies (supports deep paths).
*/
include?: string[];
/**
* Do not optimize these dependencies.
*/
exclude?: string[];
/**
* A list of linked dependencies that should be treated as source code.
* Use this to list linked packages in a monorepo so that their dependencies
* are also included for optimization.
*/
link?: string[];
/**
* A list of depdendencies that imports Node built-ins, but do not actually
* use them in browsers.
*/
allowNodeBuiltins?: string[];
/**
* Automatically run `vite optimize` on server start?
* @default true
*/
auto?: boolean;
}
export declare const OPTIMIZE_CACHE_DIR = "node_modules/.vite_opt_cache";
export declare function optimizeDeps(config: ResolvedConfig & {
force?: boolean;
}, asCommand?: boolean): Promise<void>;
export declare function getDepHash(root: string, configPath: string | undefined): string;
export declare function resolveOptimizedCacheDir(root: string, pkgPath?: string): string | null;

View File

@@ -1,306 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveOptimizedCacheDir = exports.getDepHash = exports.optimizeDeps = exports.OPTIMIZE_CACHE_DIR = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const crypto_1 = require("crypto");
const resolver_1 = require("../resolver");
const build_1 = require("../build");
const utils_1 = require("../utils");
const es_module_lexer_1 = require("es-module-lexer");
const chalk_1 = __importDefault(require("chalk"));
const pluginAssets_1 = require("./pluginAssets");
const debug = require('debug')('vite:optimize');
const KNOWN_IGNORE_LIST = new Set([
'vite',
'vitepress',
'tailwindcss',
'@tailwindcss/ui',
'@pika/react',
'@pika/react-dom'
]);
exports.OPTIMIZE_CACHE_DIR = `node_modules/.vite_opt_cache`;
async function optimizeDeps(config, asCommand = false) {
const log = asCommand ? console.log : debug;
const root = config.root || process.cwd();
// warn presence of web_modules
if (fs_extra_1.default.existsSync(path_1.default.join(root, 'web_modules'))) {
console.warn(chalk_1.default.yellow(`[vite] vite 0.15 has built-in dependency pre-bundling and resolving ` +
`from web_modules is no longer supported.`));
}
const pkgPath = utils_1.lookupFile(root, [`package.json`], true /* pathOnly */);
if (!pkgPath) {
log(`package.json not found. Skipping.`);
return;
}
const cacheDir = resolveOptimizedCacheDir(root, pkgPath);
const hashPath = path_1.default.join(cacheDir, 'hash');
const depHash = getDepHash(root, config.__path);
if (!config.force) {
let prevhash;
try {
prevhash = await fs_extra_1.default.readFile(hashPath, 'utf-8');
}
catch (e) { }
// hash is consistent, no need to re-bundle
if (prevhash === depHash) {
log('Hash is consistent. Skipping. Use --force to override.');
return;
}
}
await fs_extra_1.default.remove(cacheDir);
await fs_extra_1.default.ensureDir(cacheDir);
const options = config.optimizeDeps || {};
const resolver = resolver_1.createResolver(root, config.resolvers, config.alias, config.assetsInclude);
// Determine deps to optimize. The goal is to only pre-bundle deps that falls
// under one of the following categories:
// 1. Has imports to relative files (e.g. lodash-es, lit-html)
// 2. Has imports to bare modules that are not in the project's own deps
// (i.e. esm that imports its own dependencies, e.g. styled-components)
await es_module_lexer_1.init;
const { qualified, external } = resolveQualifiedDeps(root, options, resolver);
// Resolve deps from linked packages in a monorepo
if (options.link) {
options.link.forEach((linkedDep) => {
const depRoot = path_1.default.dirname(utils_1.resolveFrom(root, `${linkedDep}/package.json`));
const { qualified: q, external: e } = resolveQualifiedDeps(depRoot, options, resolver);
Object.keys(q).forEach((id) => {
if (!qualified[id]) {
qualified[id] = q[id];
}
});
e.forEach((id) => {
if (!external.includes(id)) {
external.push(id);
}
});
});
}
// Force included deps - these can also be deep paths
if (options.include) {
options.include.forEach((id) => {
const pkg = resolver_1.resolveNodeModule(root, id, resolver);
if (pkg && pkg.entryFilePath) {
qualified[id] = pkg.entryFilePath;
}
else {
const filePath = resolver_1.resolveNodeModuleFile(root, id);
if (filePath) {
qualified[id] = filePath;
}
}
});
}
if (!Object.keys(qualified).length) {
await fs_extra_1.default.writeFile(hashPath, depHash);
log(`No listed dependency requires optimization. Skipping.`);
return;
}
if (!asCommand) {
// This is auto run on server start - let the user know that we are
// pre-optimizing deps
console.log(chalk_1.default.greenBright(`[vite] Optimizable dependencies detected:`));
console.log(Object.keys(qualified)
.map((id) => chalk_1.default.yellow(id))
.join(`, `));
}
let spinner;
const msg = asCommand
? `Pre-bundling dependencies to speed up dev server page load...`
: `Pre-bundling them to speed up dev server page load...\n` +
`(this will be run only when your dependencies have changed)`;
if (process.env.DEBUG || process.env.NODE_ENV === 'test') {
console.log(msg);
}
else {
spinner = require('ora')(msg + '\n').start();
}
try {
const rollup = require('rollup');
const bundle = await rollup.rollup({
input: qualified,
external,
// treeshake: { moduleSideEffects: 'no-external' },
onwarn: build_1.onRollupWarning(spinner, options),
...config.rollupInputOptions,
plugins: [
pluginAssets_1.createDepAssetExternalPlugin(resolver),
...(await build_1.createBaseRollupPlugins(root, resolver, config)),
pluginAssets_1.createDepAssetPlugin(resolver, root),
...((config.rollupInputOptions &&
config.rollupInputOptions.pluginsOptimizer) ||
[])
]
});
const { output } = await bundle.generate({
...config.rollupOutputOptions,
format: 'es',
exports: 'named',
entryFileNames: '[name].js',
chunkFileNames: 'common/[name]-[hash].js'
});
spinner && spinner.stop();
for (const chunk of output) {
if (chunk.type === 'chunk') {
const fileName = chunk.fileName;
const filePath = path_1.default.join(cacheDir, fileName);
await fs_extra_1.default.ensureDir(path_1.default.dirname(filePath));
await fs_extra_1.default.writeFile(filePath, chunk.code);
}
}
await fs_extra_1.default.writeFile(hashPath, depHash);
}
catch (e) {
spinner && spinner.stop();
if (asCommand) {
throw e;
}
else {
console.error(chalk_1.default.red(`\n[vite] Dep optimization failed with error:`));
console.error(chalk_1.default.red(e.message));
if (e.code === 'PARSE_ERROR') {
console.error(chalk_1.default.cyan(path_1.default.relative(root, e.loc.file)));
console.error(chalk_1.default.dim(e.frame));
}
else if (e.message.match('Node built-in')) {
console.log();
console.log(chalk_1.default.yellow(`Tip:\nMake sure your "dependencies" only include packages that you\n` +
`intend to use in the browser. If it's a Node.js package, it\n` +
`should be in "devDependencies".\n\n` +
`If you do intend to use this dependency in the browser and the\n` +
`dependency does not actually use these Node built-ins in the\n` +
`browser, you can add the dependency (not the built-in) to the\n` +
`"optimizeDeps.allowNodeBuiltins" option in vite.config.js.\n\n` +
`If that results in a runtime error, then unfortunately the\n` +
`package is not distributed in a web-friendly format. You should\n` +
`open an issue in its repo, or look for a modern alternative.`)
// TODO link to docs once we have it
);
}
else {
console.error(e);
}
process.exit(1);
}
}
}
exports.optimizeDeps = optimizeDeps;
function resolveQualifiedDeps(root, options, resolver) {
const { include, exclude, link } = options;
const pkgContent = utils_1.lookupFile(root, ['package.json']);
if (!pkgContent) {
return {
qualified: {},
external: []
};
}
const pkg = JSON.parse(pkgContent);
const deps = Object.keys(pkg.dependencies || {});
const qualifiedDeps = deps.filter((id) => {
if (include && include.includes(id)) {
// already force included
return false;
}
if (exclude && exclude.includes(id)) {
debug(`skipping ${id} (excluded)`);
return false;
}
if (link && link.includes(id)) {
debug(`skipping ${id} (link)`);
return false;
}
if (KNOWN_IGNORE_LIST.has(id)) {
debug(`skipping ${id} (internal excluded)`);
return false;
}
// #804
if (id.startsWith('@types/')) {
debug(`skipping ${id} (ts declaration)`);
return false;
}
const pkgInfo = resolver_1.resolveNodeModule(root, id, resolver);
if (!pkgInfo || !pkgInfo.entryFilePath) {
debug(`skipping ${id} (cannot resolve entry)`);
console.log(root, id);
console.error(chalk_1.default.yellow(`[vite] cannot resolve entry for dependency ${chalk_1.default.cyan(id)}.`));
return false;
}
const { entryFilePath } = pkgInfo;
if (!resolver_1.supportedExts.includes(path_1.default.extname(entryFilePath))) {
debug(`skipping ${id} (entry is not js)`);
return false;
}
if (!fs_extra_1.default.existsSync(entryFilePath)) {
debug(`skipping ${id} (entry file does not exist)`);
console.error(chalk_1.default.yellow(`[vite] dependency ${id} declares non-existent entry file ${entryFilePath}.`));
return false;
}
const content = fs_extra_1.default.readFileSync(entryFilePath, 'utf-8');
const [imports, exports] = es_module_lexer_1.parse(content);
if (!exports.length && !/export\s+\*\s+from/.test(content)) {
debug(`optimizing ${id} (no exports, likely commonjs)`);
return true;
}
for (const { s, e } of imports) {
let i = content.slice(s, e).trim();
i = resolver.alias(i) || i;
if (i.startsWith('.')) {
debug(`optimizing ${id} (contains relative imports)`);
return true;
}
if (!deps.includes(i)) {
debug(`optimizing ${id} (imports sub dependencies)`);
return true;
}
}
debug(`skipping ${id} (single esm file, doesn't need optimization)`);
});
const qualified = {};
qualifiedDeps.forEach((id) => {
qualified[id] = resolver_1.resolveNodeModule(root, id, resolver).entryFilePath;
});
// mark non-optimized deps as external
const external = deps
.filter((id) => !qualifiedDeps.includes(id))
// make sure aliased deps are external
// https://github.com/vitejs/vite-plugin-react/issues/4
.map((id) => resolver.alias(id) || id);
return {
qualified,
external
};
}
const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
let cachedHash;
function getDepHash(root, configPath) {
if (cachedHash) {
return cachedHash;
}
let content = utils_1.lookupFile(root, lockfileFormats) || '';
const pkg = JSON.parse(utils_1.lookupFile(root, [`package.json`]) || '{}');
content += JSON.stringify(pkg.dependencies);
// also take config into account
if (configPath) {
content += fs_extra_1.default.readFileSync(configPath, 'utf-8');
}
return crypto_1.createHash('sha1').update(content).digest('base64');
}
exports.getDepHash = getDepHash;
const cacheDirCache = new Map();
function resolveOptimizedCacheDir(root, pkgPath) {
const cached = cacheDirCache.get(root);
if (cached !== undefined)
return cached;
pkgPath = pkgPath || utils_1.lookupFile(root, [`package.json`], true /* pathOnly */);
if (!pkgPath) {
return null;
}
const cacheDir = path_1.default.join(path_1.default.dirname(pkgPath), exports.OPTIMIZE_CACHE_DIR);
cacheDirCache.set(root, cacheDir);
return cacheDir;
}
exports.resolveOptimizedCacheDir = resolveOptimizedCacheDir;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +0,0 @@
import { Plugin } from 'rollup';
import { InternalResolver } from '../resolver';
export declare const createDepAssetExternalPlugin: (resolver: InternalResolver) => Plugin;
export declare const createDepAssetPlugin: (resolver: InternalResolver, root: string) => Plugin;

View File

@@ -1,64 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDepAssetPlugin = exports.createDepAssetExternalPlugin = void 0;
const es_module_lexer_1 = require("es-module-lexer");
const cssUtils_1 = require("../utils/cssUtils");
const magic_string_1 = __importDefault(require("magic-string"));
const utils_1 = require("../utils");
const path_1 = __importDefault(require("path"));
exports.createDepAssetExternalPlugin = (resolver) => ({
name: 'vite:optimize-dep-assets-external',
resolveId(id) {
if (cssUtils_1.isCSSRequest(id) || resolver.isAssetRequest(id)) {
return {
id,
external: true
};
}
}
});
exports.createDepAssetPlugin = (resolver, root) => {
return {
name: 'vite:optimize-dep-assets',
async transform(code, id) {
if (id.endsWith('.js')) {
await es_module_lexer_1.init;
const [imports] = es_module_lexer_1.parse(code);
if (imports.length) {
let s;
for (let i = 0; i < imports.length; i++) {
const { s: start, e: end, d: dynamicIndex, ss: statementStart, se: statementEnd } = imports[i];
if (dynamicIndex === -1) {
const importee = code.slice(start, end);
if (cssUtils_1.isCSSRequest(importee) || resolver.isAssetRequest(importee)) {
// replace css/asset imports to deep imports to their original
// location
s = s || new magic_string_1.default(code);
// #903 rollup-plugin-commonjs will inject proxy helper, it is unnecessary for assets
if (importee.endsWith('?commonjs-proxy')) {
s.remove(statementStart, statementEnd);
continue;
}
const deepPath = resolver.fileToRequest(utils_1.bareImportRE.test(importee)
? utils_1.resolveFrom(root, importee)
: path_1.default.resolve(path_1.default.dirname(id), importee));
s.overwrite(start, end, deepPath);
}
}
else {
// ignore dynamic import
}
}
if (s) {
return s.toString();
}
}
}
return null;
}
};
};
//# sourceMappingURL=pluginAssets.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"p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C,IAAI,QAAQ,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE;gCAC/D,8DAA8D;gCAC9D,WAAW;gCACX,CAAC,GAAG,CAAC,IAAI,IAAI,sBAAW,CAAC,IAAI,CAAC,CAAA;gCAC9B,qFAAqF;gCACrF,IAAI,QAAQ,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE;oCACxC,CAAC,CAAC,MAAM,CAAC,cAAc,EAAE,YAAY,CAAC,CAAA;oCACtC,SAAQ;iCACT;gCACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,aAAa,CACrC,oBAAY,CAAC,IAAI,CAAC,QAAQ,CAAC;oCACzB,CAAC,CAAC,mBAAW,CAAC,IAAI,EAAE,QAAQ,CAAC;oCAC7B,CAAC,CAAC,cAAI,CAAC,OAAO,CAAC,cAAI,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,QAAQ,CAAC,CAC7C,CAAA;gCACD,CAAC,CAAC,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAA;6BAClC;yBACF;6BAAM;4BACL,wBAAwB;yBACzB;qBACF;oBACD,IAAI,CAAC,EAAE;wBACL,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAA;qBACpB;iBACF;aACF;YACD,OAAO,IAAI,CAAA;QACb,CAAC;KACF,CAAA;AACH,CAAC,CAAA"}

View File

@@ -1,39 +0,0 @@
export interface Resolver {
requestToFile?(publicPath: string, root: string): string | undefined;
fileToRequest?(filePath: string, root: string): string | undefined;
alias?: ((id: string) => string | undefined) | Record<string, string>;
}
export interface InternalResolver {
requestToFile(publicPath: string): string;
fileToRequest(filePath: string): string;
normalizePublicPath(publicPath: string): string;
alias(id: string): string | undefined;
resolveRelativeRequest(publicPath: string, relativePublicPath: string): {
pathname: string;
query: string;
};
isPublicRequest(publicPath: string): boolean;
isAssetRequest(filePath: string): boolean;
}
export declare const supportedExts: string[];
export declare const mainFields: string[];
export declare function createResolver(root: string, resolvers?: Resolver[], userAlias?: Record<string, string>, assetsInclude?: (file: string) => boolean): InternalResolver;
export declare const jsSrcRE: RegExp;
/**
* Redirects a bare module request to a full path under /@modules/
* It resolves a bare node module id to its full entry path so that relative
* imports from the entry can be correctly resolved.
* e.g.:
* - `import 'foo'` -> `import '/@modules/foo/dist/index.js'`
* - `import 'foo/bar/baz'` -> `import '/@modules/foo/bar/baz.js'`
*/
export declare function resolveBareModuleRequest(root: string, id: string, importer: string, resolver: InternalResolver): string;
export declare function resolveOptimizedModule(root: string, id: string): string | undefined;
interface NodeModuleInfo {
entry: string | undefined;
entryFilePath: string | undefined;
pkg: any;
}
export declare function resolveNodeModule(root: string, id: string, resolver: InternalResolver): NodeModuleInfo | undefined;
export declare function resolveNodeModuleFile(root: string, id: string): string | undefined;
export {};

View File

@@ -1,484 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveNodeModuleFile = exports.resolveNodeModule = exports.resolveOptimizedModule = exports.resolveBareModuleRequest = exports.jsSrcRE = exports.createResolver = exports.mainFields = exports.supportedExts = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const slash_1 = __importDefault(require("slash"));
const utils_1 = require("./utils");
const serverPluginModuleResolve_1 = require("./server/serverPluginModuleResolve");
const optimizer_1 = require("./optimizer");
const serverPluginClient_1 = require("./server/serverPluginClient");
const cssUtils_1 = require("./utils/cssUtils");
const pathUtils_1 = require("./utils/pathUtils");
const chalk_1 = __importDefault(require("chalk"));
const debug = require('debug')('vite:resolve');
const isWin = require('os').platform() === 'win32';
const pathSeparator = isWin ? '\\' : '/';
exports.supportedExts = ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'];
exports.mainFields = ['module', 'jsnext', 'jsnext:main', 'browser', 'main'];
const defaultRequestToFile = (publicPath, root) => {
if (serverPluginModuleResolve_1.moduleRE.test(publicPath)) {
const id = publicPath.replace(serverPluginModuleResolve_1.moduleRE, '');
const cachedNodeModule = serverPluginModuleResolve_1.moduleIdToFileMap.get(id);
if (cachedNodeModule) {
return cachedNodeModule;
}
// try to resolve from optimized modules
const optimizedModule = resolveOptimizedModule(root, id);
if (optimizedModule) {
return optimizedModule;
}
// try to resolve from normal node_modules
const nodeModule = resolveNodeModuleFile(root, id);
if (nodeModule) {
serverPluginModuleResolve_1.moduleIdToFileMap.set(id, nodeModule);
return nodeModule;
}
}
const publicDirPath = path_1.default.join(root, 'public', publicPath.slice(1));
if (fs_extra_1.default.existsSync(publicDirPath)) {
return publicDirPath;
}
return path_1.default.join(root, publicPath.slice(1));
};
const defaultFileToRequest = (filePath, root) => serverPluginModuleResolve_1.moduleFileToIdMap.get(filePath) ||
'/' + slash_1.default(path_1.default.relative(root, filePath)).replace(/^public\//, '');
const isFile = (file) => {
try {
return fs_extra_1.default.statSync(file).isFile();
}
catch (e) {
return false;
}
};
/**
* this function resolve fuzzy file path. examples:
* /path/file is a fuzzy file path for /path/file.tsx
* /path/dir is a fuzzy file path for /path/dir/index.js
*
* returning undefined indicates the filePath is not fuzzy:
* it is already an exact file path, or it can't match any file
*/
const resolveFilePathPostfix = (filePath) => {
const cleanPath = utils_1.cleanUrl(filePath);
if (!isFile(cleanPath)) {
let postfix = '';
for (const ext of exports.supportedExts) {
if (isFile(cleanPath + ext)) {
postfix = ext;
break;
}
const defaultFilePath = `/index${ext}`;
if (isFile(path_1.default.join(cleanPath, defaultFilePath))) {
postfix = defaultFilePath;
break;
}
}
const queryMatch = filePath.match(/\?.*$/);
const query = queryMatch ? queryMatch[0] : '';
const resolved = cleanPath + postfix + query;
if (resolved !== filePath) {
debug(`(postfix) ${filePath} -> ${resolved}`);
return postfix;
}
}
};
const isDir = (p) => fs_extra_1.default.existsSync(p) && fs_extra_1.default.statSync(p).isDirectory();
function createResolver(root, resolvers = [], userAlias = {}, assetsInclude) {
resolvers = [...resolvers];
const literalAlias = {};
const literalDirAlias = {};
const resolveAlias = (alias) => {
for (const key in alias) {
let target = alias[key];
// aliasing a directory
if (key.startsWith('/') && key.endsWith('/') && path_1.default.isAbsolute(target)) {
// check first if this is aliasing to a path from root
const fromRoot = path_1.default.join(root, target);
if (isDir(fromRoot)) {
target = fromRoot;
}
else if (!isDir(target)) {
continue;
}
resolvers.push({
requestToFile(publicPath) {
if (publicPath.startsWith(key)) {
return path_1.default.join(target, publicPath.slice(key.length));
}
},
fileToRequest(filePath) {
if (filePath.startsWith(target + pathSeparator)) {
return slash_1.default(key + path_1.default.relative(target, filePath));
}
}
});
literalDirAlias[key] = target;
}
else {
literalAlias[key] = target;
}
}
};
resolvers.forEach(({ alias }) => {
if (alias && typeof alias === 'object') {
resolveAlias(alias);
}
});
resolveAlias(userAlias);
const requestToFileCache = new Map();
const fileToRequestCache = new Map();
const resolver = {
requestToFile(publicPath) {
publicPath = decodeURIComponent(publicPath);
if (requestToFileCache.has(publicPath)) {
return requestToFileCache.get(publicPath);
}
let resolved;
for (const r of resolvers) {
const filepath = r.requestToFile && r.requestToFile(publicPath, root);
if (filepath) {
resolved = filepath;
break;
}
}
if (!resolved) {
resolved = defaultRequestToFile(publicPath, root);
}
const postfix = resolveFilePathPostfix(resolved);
if (postfix) {
if (postfix[0] === '/') {
resolved = path_1.default.join(resolved, postfix);
}
else {
resolved += postfix;
}
}
requestToFileCache.set(publicPath, resolved);
return resolved;
},
fileToRequest(filePath) {
if (fileToRequestCache.has(filePath)) {
return fileToRequestCache.get(filePath);
}
for (const r of resolvers) {
const request = r.fileToRequest && r.fileToRequest(filePath, root);
if (request)
return request;
}
const res = defaultFileToRequest(filePath, root);
fileToRequestCache.set(filePath, res);
return res;
},
/**
* Given a fuzzy public path, resolve missing extensions and /index.xxx
*/
normalizePublicPath(publicPath) {
if (publicPath === serverPluginClient_1.clientPublicPath) {
return publicPath;
}
// preserve query
const queryMatch = publicPath.match(/\?.*$/);
const query = queryMatch ? queryMatch[0] : '';
const cleanPublicPath = utils_1.cleanUrl(publicPath);
const finalize = (result) => {
result += query;
if (resolver.requestToFile(result) !== resolver.requestToFile(publicPath)) {
throw new Error(`[vite] normalizePublicPath check fail. please report to vite.`);
}
return result;
};
if (!serverPluginModuleResolve_1.moduleRE.test(cleanPublicPath)) {
return finalize(resolver.fileToRequest(resolver.requestToFile(cleanPublicPath)));
}
const filePath = resolver.requestToFile(cleanPublicPath);
const cacheDir = optimizer_1.resolveOptimizedCacheDir(root);
if (cacheDir) {
const relative = path_1.default.relative(cacheDir, filePath);
if (!relative.startsWith('..')) {
return finalize(path_1.default.posix.join('/@modules/', slash_1.default(relative)));
}
}
// fileToRequest doesn't work with files in node_modules
// because of edge cases like symlinks or yarn-aliased-install
// or even aliased-symlinks
// example id: "@babel/runtime/helpers/esm/slicedToArray"
// see the test case: /playground/TestNormalizePublicPath.vue
const id = cleanPublicPath.replace(serverPluginModuleResolve_1.moduleRE, '');
const { scope, name, inPkgPath } = utils_1.parseNodeModuleId(id);
if (!inPkgPath)
return publicPath;
let filePathPostFix = '';
let findPkgFrom = filePath;
while (!filePathPostFix.startsWith(inPkgPath)) {
// some package contains multi package.json...
// for example: @babel/runtime@7.10.2/helpers/esm/package.json
const pkgPath = utils_1.lookupFile(findPkgFrom, ['package.json'], true);
if (!pkgPath) {
throw new Error(`[vite] can't find package.json for a node_module file: ` +
`"${publicPath}". something is wrong.`);
}
filePathPostFix = slash_1.default(path_1.default.relative(path_1.default.dirname(pkgPath), filePath));
findPkgFrom = path_1.default.join(path_1.default.dirname(pkgPath), '../');
}
return finalize(['/@modules', scope, name, filePathPostFix].filter(Boolean).join('/'));
},
alias(id) {
let aliased = literalAlias[id];
if (aliased) {
return aliased;
}
for (const { alias } of resolvers) {
aliased = alias && typeof alias === 'function' ? alias(id) : undefined;
if (aliased) {
return aliased;
}
}
},
resolveRelativeRequest(importer, importee) {
const queryMatch = importee.match(utils_1.queryRE);
let resolved = importee;
if (importee.startsWith('.')) {
resolved = path_1.default.posix.resolve(path_1.default.posix.dirname(importer), importee);
for (const alias in literalDirAlias) {
if (importer.startsWith(alias)) {
if (!resolved.startsWith(alias)) {
// resolved path is outside of alias directory, we need to use
// its full path instead
const importerFilePath = resolver.requestToFile(importer);
const importeeFilePath = path_1.default.resolve(path_1.default.dirname(importerFilePath), importee);
resolved = resolver.fileToRequest(importeeFilePath);
}
break;
}
}
}
return {
pathname: utils_1.cleanUrl(resolved) +
// path resolve strips ending / which should be preserved
(importee.endsWith('/') && !resolved.endsWith('/') ? '/' : ''),
query: queryMatch ? queryMatch[0] : ''
};
},
isPublicRequest(publicPath) {
return resolver
.requestToFile(publicPath)
.startsWith(path_1.default.resolve(root, 'public'));
},
isAssetRequest(filePath) {
return ((assetsInclude && assetsInclude(filePath)) || pathUtils_1.isStaticAsset(filePath));
}
};
return resolver;
}
exports.createResolver = createResolver;
exports.jsSrcRE = /\.(?:(?:j|t)sx?|vue)$|\.mjs$/;
const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
/**
* Redirects a bare module request to a full path under /@modules/
* It resolves a bare node module id to its full entry path so that relative
* imports from the entry can be correctly resolved.
* e.g.:
* - `import 'foo'` -> `import '/@modules/foo/dist/index.js'`
* - `import 'foo/bar/baz'` -> `import '/@modules/foo/bar/baz.js'`
*/
function resolveBareModuleRequest(root, id, importer, resolver) {
const optimized = resolveOptimizedModule(root, id);
if (optimized) {
// ensure optimized module requests always ends with `.js` - this is because
// optimized deps may import one another and in the built bundle their
// relative import paths ends with `.js`. If we don't append `.js` during
// rewrites, it may result in duplicated copies of the same dep.
return path_1.default.extname(id) === '.js' ? id : id + '.js';
}
let isEntry = false;
const basedir = path_1.default.dirname(resolver.requestToFile(importer));
const pkgInfo = resolveNodeModule(basedir, id, resolver);
if (pkgInfo) {
if (!pkgInfo.entry) {
console.error(chalk_1.default.yellow(`[vite] dependency ${id} does not have default entry defined in package.json.`));
}
else {
isEntry = true;
id = pkgInfo.entry;
}
}
if (!isEntry) {
const deepMatch = !isEntry && id.match(deepImportRE);
if (deepMatch) {
// deep import
const depId = deepMatch[1] || deepMatch[2];
// check if this is a deep import to an optimized dep.
if (resolveOptimizedModule(root, depId)) {
if (resolver.alias(depId) === id) {
// this is a deep import but aliased from a bare module id.
// redirect it the optimized copy.
return resolveBareModuleRequest(root, depId, importer, resolver);
}
if (!cssUtils_1.isCSSRequest(id) && !resolver.isAssetRequest(id)) {
// warn against deep imports to optimized dep
console.error(chalk_1.default.yellow(`\n[vite] Avoid deep import "${id}" (imported by ${importer})\n` +
`because "${depId}" has been pre-optimized by vite into a single file.\n` +
`Prefer importing directly from the module entry:\n` +
chalk_1.default.cyan(`\n import { ... } from "${depId}" \n\n`) +
`If the dependency requires deep import to function properly, \n` +
`add the deep path to ${chalk_1.default.cyan(`optimizeDeps.include`)} in vite.config.js.\n`));
}
}
// resolve ext for deepImport
const filePath = resolveNodeModuleFile(root, id);
if (filePath) {
const deepPath = id.replace(deepImportRE, '');
const normalizedFilePath = slash_1.default(filePath);
const postfix = normalizedFilePath.slice(normalizedFilePath.lastIndexOf(deepPath) + deepPath.length);
id += postfix;
}
}
}
// check and warn deep imports on optimized modules
const ext = path_1.default.extname(id);
if (!exports.jsSrcRE.test(ext)) {
// append import query for non-js deep imports
return id + (utils_1.queryRE.test(id) ? '&import' : '?import');
}
else {
return id;
}
}
exports.resolveBareModuleRequest = resolveBareModuleRequest;
const viteOptimizedMap = new Map();
function resolveOptimizedModule(root, id) {
const cacheKey = `${root}#${id}`;
const cached = viteOptimizedMap.get(cacheKey);
if (cached) {
return cached;
}
const cacheDir = optimizer_1.resolveOptimizedCacheDir(root);
if (!cacheDir)
return;
const tryResolve = (file) => {
file = path_1.default.join(cacheDir, file);
if (fs_extra_1.default.existsSync(file) && fs_extra_1.default.statSync(file).isFile()) {
viteOptimizedMap.set(cacheKey, file);
return file;
}
};
return tryResolve(id) || tryResolve(id + '.js');
}
exports.resolveOptimizedModule = resolveOptimizedModule;
const nodeModulesInfoMap = new Map();
const nodeModulesFileMap = new Map();
function resolveNodeModule(root, id, resolver) {
const cacheKey = `${root}#${id}`;
const cached = nodeModulesInfoMap.get(cacheKey);
if (cached) {
return cached;
}
let pkgPath;
try {
// see if the id is a valid package name
pkgPath = utils_1.resolveFrom(root, `${id}/package.json`);
}
catch (e) {
debug(`failed to resolve package.json for ${id}`);
}
if (pkgPath) {
// if yes, this is a entry import. resolve entry file
let pkg;
try {
pkg = fs_extra_1.default.readJSONSync(pkgPath);
}
catch (e) {
return;
}
let entryPoint;
// TODO properly support conditional exports
// https://nodejs.org/api/esm.html#esm_conditional_exports
// Note: this would require @rollup/plugin-node-resolve to support it too
// or we will have to implement that logic in vite's own resolve plugin.
if (!entryPoint) {
for (const field of exports.mainFields) {
if (typeof pkg[field] === 'string') {
entryPoint = pkg[field];
break;
}
}
}
if (!entryPoint) {
entryPoint = 'index.js';
}
// resolve object browser field in package.json
// https://github.com/defunctzombie/package-browser-field-spec
const { browser: browserField } = pkg;
if (entryPoint && browserField && typeof browserField === 'object') {
entryPoint = mapWithBrowserField(entryPoint, browserField);
}
debug(`(node_module entry) ${id} -> ${entryPoint}`);
// save resolved entry file path using the deep import path as key
// e.g. foo/dist/foo.js
// this is the path raw imports will be rewritten to, and is what will
// be passed to resolveNodeModuleFile().
let entryFilePath;
// respect user manual alias
const aliased = resolver.alias(id);
if (aliased && aliased !== id) {
entryFilePath = resolveNodeModuleFile(root, aliased);
}
if (!entryFilePath && entryPoint) {
// #284 some packages specify entry without extension...
entryFilePath = path_1.default.join(path_1.default.dirname(pkgPath), entryPoint);
const postfix = resolveFilePathPostfix(entryFilePath);
if (postfix) {
entryPoint += postfix;
entryFilePath += postfix;
}
entryPoint = path_1.default.posix.join(id, entryPoint);
// save the resolved file path now so we don't need to do it again in
// resolveNodeModuleFile()
nodeModulesFileMap.set(entryPoint, entryFilePath);
}
const result = {
entry: entryPoint,
entryFilePath,
pkg
};
nodeModulesInfoMap.set(cacheKey, result);
return result;
}
}
exports.resolveNodeModule = resolveNodeModule;
function resolveNodeModuleFile(root, id) {
const cacheKey = `${root}#${id}`;
const cached = nodeModulesFileMap.get(cacheKey);
if (cached) {
return cached;
}
try {
const resolved = utils_1.resolveFrom(root, id);
nodeModulesFileMap.set(cacheKey, resolved);
return resolved;
}
catch (e) {
// error will be reported downstream
}
}
exports.resolveNodeModuleFile = resolveNodeModuleFile;
const normalize = path_1.default.posix.normalize;
/**
* given a relative path in pkg dir,
* return a relative path in pkg dir,
* mapped with the "map" object
*/
function mapWithBrowserField(relativePathInPkgDir, map) {
const normalized = normalize(relativePathInPkgDir);
const foundEntry = Object.entries(map).find(([from]) => normalize(from) === normalized);
if (!foundEntry) {
return normalized;
}
const [, to] = foundEntry;
return normalize(to);
}
//# sourceMappingURL=resolver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,27 +0,0 @@
/// <reference types="node" />
import { Server } from 'http';
import Koa, { DefaultState, DefaultContext } from 'koa';
import { InternalResolver } from '../resolver';
import { HMRWatcher } from './serverPluginHmr';
import { ServerConfig } from '../config';
export { rewriteImports } from './serverPluginModuleRewrite';
import { SourceMap } from './serverPluginSourceMap';
export declare type ServerPlugin = (ctx: ServerPluginContext) => void;
export interface ServerPluginContext {
root: string;
app: Koa<State, Context>;
server: Server;
watcher: HMRWatcher;
resolver: InternalResolver;
config: ServerConfig & {
__path?: string;
};
port: number;
}
export interface State extends DefaultState {
}
export declare type Context = DefaultContext & ServerPluginContext & {
read: (filePath: string) => Promise<Buffer | string>;
map?: SourceMap | null;
};
export declare function createServer(config: ServerConfig): Server;

View File

@@ -1,149 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createServer = exports.rewriteImports = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const koa_1 = __importDefault(require("koa"));
const chokidar_1 = __importDefault(require("chokidar"));
const resolver_1 = require("../resolver");
const serverPluginModuleRewrite_1 = require("./serverPluginModuleRewrite");
const serverPluginModuleResolve_1 = require("./serverPluginModuleResolve");
const serverPluginVue_1 = require("./serverPluginVue");
const serverPluginHmr_1 = require("./serverPluginHmr");
const serverPluginServeStatic_1 = require("./serverPluginServeStatic");
const serverPluginJson_1 = require("./serverPluginJson");
const serverPluginCss_1 = require("./serverPluginCss");
const serverPluginAssets_1 = require("./serverPluginAssets");
const serverPluginEsbuild_1 = require("./serverPluginEsbuild");
const transform_1 = require("../transform");
const serverPluginHtml_1 = require("./serverPluginHtml");
const serverPluginProxy_1 = require("./serverPluginProxy");
const createCertificate_1 = require("../utils/createCertificate");
const utils_1 = require("../utils");
const serverPluginEnv_1 = require("./serverPluginEnv");
var serverPluginModuleRewrite_2 = require("./serverPluginModuleRewrite");
Object.defineProperty(exports, "rewriteImports", { enumerable: true, get: function () { return serverPluginModuleRewrite_2.rewriteImports; } });
const serverPluginSourceMap_1 = require("./serverPluginSourceMap");
const serverPluginWebWorker_1 = require("./serverPluginWebWorker");
const serverPluginWasm_1 = require("./serverPluginWasm");
const serverPluginClient_1 = require("./serverPluginClient");
function createServer(config) {
const { root = process.cwd(), configureServer = [], resolvers = [], alias = {}, transforms = [], vueCustomBlockTransforms = {}, optimizeDeps = {}, enableEsbuild = true, assetsInclude } = config;
const app = new koa_1.default();
const server = resolveServer(config, app.callback());
const watcher = chokidar_1.default.watch(root, {
ignored: [/node_modules/, /\.git/],
// #610
awaitWriteFinish: {
stabilityThreshold: 100,
pollInterval: 10
}
});
const resolver = resolver_1.createResolver(root, resolvers, alias, assetsInclude);
const context = {
root,
app,
server,
watcher,
resolver,
config,
// port is exposed on the context for hmr client connection
// in case the files are served under a different port
port: config.port || 3000
};
// attach server context to koa context
app.use((ctx, next) => {
Object.assign(ctx, context);
ctx.read = utils_1.cachedRead.bind(null, ctx);
return next();
});
// cors
if (config.cors) {
app.use(require('@koa/cors')(typeof config.cors === 'boolean' ? {} : config.cors));
}
const resolvedPlugins = [
// rewrite and source map plugins take highest priority and should be run
// after all other middlewares have finished
serverPluginSourceMap_1.sourceMapPlugin,
serverPluginModuleRewrite_1.moduleRewritePlugin,
serverPluginHtml_1.htmlRewritePlugin,
// user plugins
...utils_1.toArray(configureServer),
serverPluginEnv_1.envPlugin,
serverPluginModuleResolve_1.moduleResolvePlugin,
serverPluginProxy_1.proxyPlugin,
serverPluginClient_1.clientPlugin,
serverPluginHmr_1.hmrPlugin,
...(transforms.length || Object.keys(vueCustomBlockTransforms).length
? [
transform_1.createServerTransformPlugin(transforms, vueCustomBlockTransforms, resolver)
]
: []),
serverPluginVue_1.vuePlugin,
serverPluginCss_1.cssPlugin,
enableEsbuild ? serverPluginEsbuild_1.esbuildPlugin : null,
serverPluginJson_1.jsonPlugin,
serverPluginAssets_1.assetPathPlugin,
serverPluginWebWorker_1.webWorkerPlugin,
serverPluginWasm_1.wasmPlugin,
serverPluginServeStatic_1.serveStaticPlugin
];
resolvedPlugins.forEach((m) => m && m(context));
const listen = server.listen.bind(server);
server.listen = (async (port, ...args) => {
if (optimizeDeps.auto !== false) {
await require('../optimizer').optimizeDeps(config);
}
return listen(port, ...args);
});
server.once('listening', () => {
context.port = server.address().port;
});
return server;
}
exports.createServer = createServer;
function resolveServer({ https = false, httpsOptions = {}, proxy }, requestListener) {
if (https) {
if (proxy) {
// #484 fallback to http1 when proxy is needed.
return require('https').createServer(resolveHttpsConfig(httpsOptions), requestListener);
}
else {
return require('http2').createSecureServer({
...resolveHttpsConfig(httpsOptions),
allowHTTP1: true
}, requestListener);
}
}
else {
return require('http').createServer(requestListener);
}
}
function resolveHttpsConfig(httpsOption) {
const { ca, cert, key, pfx } = httpsOption;
Object.assign(httpsOption, {
ca: readFileIfExists(ca),
cert: readFileIfExists(cert),
key: readFileIfExists(key),
pfx: readFileIfExists(pfx)
});
if (!httpsOption.key || !httpsOption.cert) {
httpsOption.cert = httpsOption.key = createCertificate_1.createCertificate();
}
return httpsOption;
}
function readFileIfExists(value) {
if (value && !Buffer.isBuffer(value)) {
try {
return fs_extra_1.default.readFileSync(path_1.default.resolve(value));
}
catch (e) {
return value;
}
}
return value;
}
//# sourceMappingURL=index.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/node/server/index.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AACvB,wDAAyB;AAGzB,8CAAuD;AACvD,wDAA+B;AAC/B,0CAA8D;AAC9D,2EAAiE;AACjE,2EAAiE;AACjE,uDAA6C;AAC7C,uDAAyD;AACzD,uEAA6D;AAC7D,yDAA+C;AAC/C,uDAA6C;AAC7C,6DAAsD;AACtD,+DAAqD;AAErD,4CAA0D;AAC1D,yDAAsD;AACtD,2DAAiD;AACjD,kEAA8D;AAC9D,oCAA8C;AAC9C,uDAA6C;AAC7C,yEAA4D;AAAnD,2HAAA,cAAc,OAAA;AACvB,mEAAoE;AACpE,mEAAyD;AACzD,yDAA+C;AAC/C,6DAAmD;AAuBnD,SAAgB,YAAY,CAAC,MAAoB;IAC/C,MAAM,EACJ,IAAI,GAAG,OAAO,CAAC,GAAG,EAAE,EACpB,eAAe,GAAG,EAAE,EACpB,SAAS,GAAG,EAAE,EACd,KAAK,GAAG,EAAE,EACV,UAAU,GAAG,EAAE,EACf,wBAAwB,GAAG,EAAE,EAC7B,YAAY,GAAG,EAAE,EACjB,aAAa,GAAG,IAAI,EACpB,aAAa,EACd,GAAG,MAAM,CAAA;IAEV,MAAM,GAAG,GAAG,IAAI,aAAG,EAAkB,CAAA;IACrC,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAA;IACpD,MAAM,OAAO,GAAG,kBAAQ,CAAC,KAAK,CAAC,IAAI,EAAE;QACnC,OAAO,EAAE,CAAC,cAAc,EAAE,OAAO,CAAC;QAClC,OAAO;QACP,gBAAgB,EAAE;YAChB,kBAAkB,EAAE,GAAG;YACvB,YAAY,EAAE,EAAE;SACjB;KACF,CAAe,CAAA;IAChB,M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F;SAAM;QACL,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,YAAY,CAAC,eAAe,CAAC,CAAA;KACrD;AACH,CAAC;AAED,SAAS,kBAAkB,CAAC,WAA0B;IACpD,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,WAAW,CAAA;IAC1C,MAAM,CAAC,MAAM,CAAC,WAAW,EAAE;QACzB,EAAE,EAAE,gBAAgB,CAAC,EAAE,CAAC;QACxB,IAAI,EAAE,gBAAgB,CAAC,IAAI,CAAC;QAC5B,GAAG,EAAE,gBAAgB,CAAC,GAAG,CAAC;QAC1B,GAAG,EAAE,gBAAgB,CAAC,GAAG,CAAC;KAC3B,CAAC,CAAA;IACF,IAAI,CAAC,WAAW,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE;QACzC,WAAW,CAAC,IAAI,GAAG,WAAW,CAAC,GAAG,GAAG,qCAAiB,EAAE,CAAA;KACzD;IACD,OAAO,WAAW,CAAA;AACpB,CAAC;AAED,SAAS,gBAAgB,CAAC,KAA6B;IACrD,IAAI,KAAK,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE;QACpC,IAAI;YACF,OAAO,kBAAE,CAAC,YAAY,CAAC,cAAI,CAAC,OAAO,CAAC,KAAe,CAAC,CAAC,CAAA;SACtD;QAAC,OAAO,CAAC,EAAE;YACV,OAAO,KAAK,CAAA;SACb;KACF;IACD,OAAO,KAAK,CAAA;AACd,CAAC"}

View File

@@ -1,2 +0,0 @@
import { ServerPlugin } from '.';
export declare const assetPathPlugin: ServerPlugin;

View File

@@ -1,15 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assetPathPlugin = void 0;
const utils_1 = require("../utils");
exports.assetPathPlugin = ({ app, resolver }) => {
app.use(async (ctx, next) => {
if (resolver.isAssetRequest(ctx.path) && utils_1.isImportRequest(ctx)) {
ctx.type = 'js';
ctx.body = `export default ${JSON.stringify(ctx.path)}`;
return;
}
return next();
});
};
//# sourceMappingURL=serverPluginAssets.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginAssets.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginAssets.ts"],"names":[],"mappings":";;;AACA,oCAA0C;AAE7B,QAAA,eAAe,GAAiB,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE;IACjE,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,IAAI,QAAQ,CAAC,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,uBAAe,CAAC,GAAG,CAAC,EAAE;YAC7D,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG,kBAAkB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAA;YACvD,OAAM;SACP;QACD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,4 +0,0 @@
import { ServerPlugin } from '.';
export declare const clientFilePath: string;
export declare const clientPublicPath = "/vite/client";
export declare const clientPlugin: ServerPlugin;

View File

@@ -1,53 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.clientPlugin = exports.clientPublicPath = exports.clientFilePath = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const config_1 = require("../config");
exports.clientFilePath = path_1.default.resolve(__dirname, '../../client/client.js');
exports.clientPublicPath = `/vite/client`;
const legacyPublicPath = '/vite/hmr';
exports.clientPlugin = ({ app, config }) => {
const clientCode = fs_1.default
.readFileSync(exports.clientFilePath, 'utf-8')
.replace(`__MODE__`, JSON.stringify(config.mode || 'development'))
.replace(`__DEFINES__`, JSON.stringify({
...config_1.defaultDefines,
...config.define
}));
app.use(async (ctx, next) => {
if (ctx.path === exports.clientPublicPath) {
let socketPort = ctx.port;
// infer on client by default
let socketProtocol = null;
let socketHostname = null;
if (config.hmr && typeof config.hmr === 'object') {
// hmr option has highest priory
socketProtocol = config.hmr.protocol || null;
socketHostname = config.hmr.hostname || null;
socketPort = config.hmr.port || ctx.port;
if (config.hmr.path) {
socketPort = `${socketPort}/${config.hmr.path}`;
}
}
ctx.type = 'js';
ctx.status = 200;
ctx.body = clientCode
.replace(`__HMR_PROTOCOL__`, JSON.stringify(socketProtocol))
.replace(`__HMR_HOSTNAME__`, JSON.stringify(socketHostname))
.replace(`__HMR_PORT__`, JSON.stringify(socketPort));
}
else {
if (ctx.path === legacyPublicPath) {
console.error(chalk_1.default.red(`[vite] client import path has changed from "/vite/hmr" to "/vite/client". ` +
`please update your code accordingly.`));
}
return next();
}
});
};
//# sourceMappingURL=serverPluginClient.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginClient.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginClient.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAmB;AACnB,gDAAuB;AACvB,kDAAyB;AAEzB,sCAA0C;AAE7B,QAAA,cAAc,GAAG,cAAI,CAAC,OAAO,CAAC,SAAS,EAAE,wBAAwB,CAAC,CAAA;AAElE,QAAA,gBAAgB,GAAG,cAAc,CAAA;AAE9C,MAAM,gBAAgB,GAAG,WAAW,CAAA;AAEvB,QAAA,YAAY,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE;IAC5D,MAAM,UAAU,GAAG,YAAE;SAClB,YAAY,CAAC,sBAAc,EAAE,OAAO,CAAC;SACrC,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,IAAI,aAAa,CAAC,CAAC;SACjE,OAAO,CACN,aAAa,EACb,IAAI,CAAC,SAAS,CAAC;QACb,GAAG,uBAA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,CACP,4EAA4E;oBAC1E,sCAAsC,CACzC,CACF,CAAA;aACF;YACD,OAAO,IAAI,EAAE,CAAA;SACd;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,4 +0,0 @@
import { ServerPlugin } from '.';
export declare const debugCSS: any;
export declare const cssPlugin: ServerPlugin;
export declare function codegenCss(id: string, css: string, modules?: Record<string, string>): string;

View File

@@ -1,165 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.codegenCss = exports.cssPlugin = exports.debugCSS = void 0;
const path_1 = require("path");
const hash_sum_1 = __importDefault(require("hash-sum"));
const utils_1 = require("../utils");
const serverPluginVue_1 = require("./serverPluginVue");
const cssUtils_1 = require("../utils/cssUtils");
const querystring_1 = __importDefault(require("querystring"));
const chalk_1 = __importDefault(require("chalk"));
const serverPluginClient_1 = require("./serverPluginClient");
const pluginutils_1 = require("@rollup/pluginutils");
exports.debugCSS = require('debug')('vite:css');
exports.cssPlugin = ({ root, app, watcher, resolver }) => {
app.use(async (ctx, next) => {
await next();
// handle .css imports
if (cssUtils_1.isCSSRequest(ctx.path) &&
// note ctx.body could be null if upstream set status to 304
ctx.body) {
const id = JSON.stringify(hash_sum_1.default(ctx.path));
if (utils_1.isImportRequest(ctx)) {
const { css, modules } = await processCss(root, ctx);
ctx.type = 'js';
// we rewrite css with `?import` to a js module that inserts a style
// tag linking to the actual raw url
ctx.body = codegenCss(id, css, modules);
}
}
});
watcher.on('change', (filePath) => {
if (cssUtils_1.isCSSRequest(filePath)) {
const publicPath = resolver.fileToRequest(filePath);
/** filter unused files */
if (!cssUtils_1.cssImporterMap.has(filePath) &&
!processedCSS.has(publicPath) &&
!serverPluginVue_1.srcImportMap.has(filePath)) {
return exports.debugCSS(`${path_1.basename(publicPath)} has changed, but it is not currently in use`);
}
if (serverPluginVue_1.srcImportMap.has(filePath)) {
// handle HMR for <style src="xxx.css">
// it cannot be handled as simple css import because it may be scoped
const styleImport = serverPluginVue_1.srcImportMap.get(filePath);
serverPluginVue_1.vueCache.del(filePath);
vueStyleUpdate(styleImport);
return;
}
// handle HMR for module css
// it cannot be handled as normal css because the js exports may change
if (filePath.includes('.module')) {
moduleCssUpdate(filePath, resolver);
}
const boundaries = cssUtils_1.getCssImportBoundaries(filePath);
if (boundaries.size) {
boundaryCssUpdate(boundaries);
return;
}
// no boundaries
normalCssUpdate(publicPath);
}
else if (cssUtils_1.cssImporterMap.has(filePath)) {
const boundaries = cssUtils_1.getCssImportBoundaries(filePath);
if (boundaries.size) {
boundaryCssUpdate(boundaries);
}
}
});
function boundaryCssUpdate(boundaries) {
for (let boundary of boundaries) {
if (boundary.includes('.module')) {
moduleCssUpdate(boundary, resolver);
}
else if (boundary.includes('.vue')) {
serverPluginVue_1.vueCache.del(utils_1.cleanUrl(boundary));
vueStyleUpdate(resolver.fileToRequest(boundary));
}
else {
normalCssUpdate(resolver.fileToRequest(boundary));
}
}
}
function vueStyleUpdate(styleImport) {
const publicPath = utils_1.cleanUrl(styleImport);
const index = querystring_1.default.parse(styleImport.split('?', 2)[1]).index;
const path = `${publicPath}?type=style&index=${index}`;
console.log(chalk_1.default.green(`[vite:hmr] `) + `${publicPath} updated. (style)`);
watcher.send({
type: 'style-update',
path,
changeSrcPath: path,
timestamp: Date.now()
});
}
function moduleCssUpdate(filePath, resolver) {
// bust process cache
processedCSS.delete(resolver.fileToRequest(filePath));
watcher.handleJSReload(filePath);
}
function normalCssUpdate(publicPath) {
// bust process cache
processedCSS.delete(publicPath);
watcher.send({
type: 'style-update',
path: publicPath,
changeSrcPath: publicPath,
timestamp: Date.now()
});
}
// processed CSS is cached in case the user ticks "disable cache" during dev
// which can lead to unnecessary processing on page reload
const processedCSS = new Map();
async function processCss(root, ctx) {
// source didn't change (marker added by cachedRead)
// just use previously cached result
if (ctx.__notModified && processedCSS.has(ctx.path)) {
return processedCSS.get(ctx.path);
}
const css = (await utils_1.readBody(ctx.body));
const filePath = resolver.requestToFile(ctx.path);
const preprocessLang = (ctx.path.match(cssUtils_1.cssPreprocessLangRE) || [])[1];
const result = await cssUtils_1.compileCss(root, ctx.path, {
id: '',
source: css,
filename: filePath,
scoped: false,
modules: ctx.path.includes('.module'),
preprocessLang,
preprocessOptions: ctx.config.cssPreprocessOptions,
modulesOptions: ctx.config.cssModuleOptions
});
if (typeof result === 'string') {
const res = { css: await cssUtils_1.rewriteCssUrls(css, ctx.path) };
processedCSS.set(ctx.path, res);
return res;
}
cssUtils_1.recordCssImportChain(result.dependencies, filePath);
if (result.errors.length) {
console.error(`[vite] error applying css transforms: `);
result.errors.forEach(console.error);
}
const res = {
css: await cssUtils_1.rewriteCssUrls(result.code, ctx.path),
modules: result.modules
};
processedCSS.set(ctx.path, res);
return res;
}
};
function codegenCss(id, css, modules) {
let code = `import { updateStyle } from "${serverPluginClient_1.clientPublicPath}"\n` +
`const css = ${JSON.stringify(css)}\n` +
`updateStyle(${JSON.stringify(id)}, css)\n`;
if (modules) {
code += pluginutils_1.dataToEsm(modules, { namedExports: true });
}
else {
code += `export default css`;
}
return code;
}
exports.codegenCss = codegenCss;
//# sourceMappingURL=serverPluginCss.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +0,0 @@
import { ServerPlugin } from '.';
export declare const envPublicPath = "/vite/env";
export declare const envPlugin: ServerPlugin;

View File

@@ -1,27 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.envPlugin = exports.envPublicPath = void 0;
exports.envPublicPath = '/vite/env';
exports.envPlugin = ({ app, config }) => {
// configMode = mode of the .env{.mode} file that was loaded
const configMode = config.mode || 'development';
// resolvedMode = potentially overwritten by NODE_ENV inside the .env
// (which is set as VITE_ENV to avoid system default NODE_ENV)
const resolvedMode = process.env.VITE_ENV || configMode;
const env = JSON.stringify({
...config.env,
BASE_URL: '/',
MODE: configMode,
DEV: resolvedMode !== 'production',
PROD: resolvedMode === 'production'
});
app.use((ctx, next) => {
if (ctx.path === exports.envPublicPath) {
ctx.type = 'js';
ctx.body = `export default ${env}`;
return;
}
return next();
});
};
//# sourceMappingURL=serverPluginEnv.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginEnv.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginEnv.ts"],"names":[],"mappings":";;;AAEa,QAAA,aAAa,GAAG,WAAW,CAAA;AAE3B,QAAA,SAAS,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE;IACzD,4DAA4D;IAC5D,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,IAAI,aAAa,CAAA;IAC/C,qEAAqE;IACrE,8DAA8D;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,UAAU,CAAA;IACvD,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC;QACzB,GAAG,MAAM,CAAC,GAAG;QACb,QAAQ,EAAE,GAAG;QACb,IAAI,EAAE,UAAU;QAChB,GAAG,EAAE,YAAY,KAAK,YAAY;QAClC,IAAI,EAAE,YAAY,KAAK,YAAY;KACpC,CAAC,CAAA;IAEF,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;QACpB,IAAI,GAAG,CAAC,IAAI,KAAK,qBAAa,EAAE;YAC9B,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG,kBAAkB,GAAG,EAAE,CAAA;YAClC,OAAM;SACP;QACD,OAAO,IAAI,EAAE,CAAA;IACf,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,2 +0,0 @@
import { ServerPlugin } from '.';
export declare const esbuildPlugin: ServerPlugin;

View File

@@ -1,29 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.esbuildPlugin = void 0;
const esbuildService_1 = require("../esbuildService");
const utils_1 = require("../utils");
exports.esbuildPlugin = ({ app, config, resolver }) => {
const jsxConfig = esbuildService_1.resolveJsxOptions(config.jsx);
app.use(async (ctx, next) => {
// intercept and return vue jsx helper import
if (ctx.path === esbuildService_1.vueJsxPublicPath) {
await ctx.read(esbuildService_1.vueJsxFilePath);
}
await next();
if (!esbuildService_1.tjsxRE.test(ctx.path) ||
!ctx.body ||
ctx.type === 'text/html' ||
resolver.isPublicRequest(ctx.path)) {
return;
}
ctx.type = 'js';
const src = await utils_1.readBody(ctx.body);
const { code, map } = await esbuildService_1.transform(src, resolver.requestToFile(utils_1.cleanUrl(ctx.url)), jsxConfig, config.jsx);
ctx.body = code;
if (map) {
ctx.map = JSON.parse(map);
}
});
};
//# sourceMappingURL=serverPluginEsbuild.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginEsbuild.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginEsbuild.ts"],"names":[],"mappings":";;;AACA,sDAM0B;AAC1B,oCAA6C;AAEhC,QAAA,aAAa,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,EAAE;IACvE,MAAM,SAAS,GAAG,kCAAiB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IAE/C,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,6CAA6C;QAC7C,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAgB,EAAE;YACjC,MAAM,GAAG,CAAC,IAAI,CAAC,+BAAc,CAAC,CAAA;SAC/B;QAED,MAAM,IAAI,EAAE,CAAA;QAEZ,IACE,CAAC,uBAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;YACtB,CAAC,GAAG,CAAC,IAAI;YACT,GAAG,CAAC,IAAI,KAAK,WAAW;YACxB,QAAQ,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,EAClC;YACA,OAAM;SACP;QAED,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;QACf,MAAM,GAAG,GAAG,MAAM,gBAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;QACpC,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,MAAM,0BAAS,CACnC,GAAI,EACJ,QAAQ,CAAC,aAAa,CAAC,gBAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,EACzC,SAAS,EACT,MAAM,CAAC,GAAG,CACX,CAAA;QACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;QACf,IAAI,GAAG,EAAE;YACP,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;SAC1B;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,23 +0,0 @@
import { ServerPlugin } from '.';
import { FSWatcher } from 'chokidar';
import MagicString from 'magic-string';
import { InternalResolver } from '../resolver';
import LRUCache from 'lru-cache';
import { HMRPayload } from '../../hmrPayload';
export declare const debugHmr: any;
export declare type HMRWatcher = FSWatcher & {
handleVueReload: (filePath: string, timestamp?: number, content?: string) => void;
handleJSReload: (filePath: string, timestamp?: number) => void;
send: (payload: HMRPayload) => void;
};
declare type HMRStateMap = Map<string, Set<string>>;
export declare const hmrAcceptanceMap: HMRStateMap;
export declare const hmrDeclineSet: Set<string>;
export declare const importerMap: HMRStateMap;
export declare const importeeMap: HMRStateMap;
export declare const hmrDirtyFilesMap: LRUCache<string, Set<string>>;
export declare const latestVersionsMap: Map<string, string>;
export declare const hmrPlugin: ServerPlugin;
export declare function ensureMapEntry(map: HMRStateMap, key: string): Set<string>;
export declare function rewriteFileWithHMR(root: string, source: string, importer: string, resolver: InternalResolver, s: MagicString): void;
export {};

View File

@@ -1,296 +0,0 @@
"use strict";
// How HMR works
// 1. `.vue` files are transformed into `.js` files before being served
// 2. All `.js` files, before being served, are parsed to detect their imports
// (this is done in `./serverPluginModuleRewrite.ts`) for module import rewriting.
// During this we also record the importer/importee relationships which can be used for
// HMR analysis (we do both at the same time to avoid double parse costs)
// 3. When a file changes, it triggers an HMR graph analysis, where we try to
// walk its importer chains and see if we reach a "HMR boundary". An HMR
// boundary is a file that explicitly indicated that it accepts hot updates
// (by calling `import.meta.hot` APIs)
// 4. If any parent chain exhausts without ever running into an HMR boundary,
// it's considered a "dead end". This causes a full page reload.
// 5. If a boundary is encountered, we check if the boundary's current
// child importer is in the accepted list of the boundary (recorded while
// parsing the file for HRM rewrite). If yes, record current child importer
// in the `hmrBoundaries` Set.
// 6. If the graph walk finished without running into dead ends, send the
// client to update all `hmrBoundaries`.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteFileWithHMR = exports.ensureMapEntry = exports.hmrPlugin = exports.latestVersionsMap = exports.hmrDirtyFilesMap = exports.importeeMap = exports.importerMap = exports.hmrDeclineSet = exports.hmrAcceptanceMap = exports.debugHmr = void 0;
const ws_1 = __importDefault(require("ws"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const serverPluginVue_1 = require("./serverPluginVue");
const serverPluginModuleRewrite_1 = require("./serverPluginModuleRewrite");
const babelParse_1 = require("../utils/babelParse");
const lru_cache_1 = __importDefault(require("lru-cache"));
const slash_1 = __importDefault(require("slash"));
const cssUtils_1 = require("../utils/cssUtils");
const utils_1 = require("../utils");
const serverPluginClient_1 = require("./serverPluginClient");
exports.debugHmr = require('debug')('vite:hmr');
exports.hmrAcceptanceMap = new Map();
exports.hmrDeclineSet = new Set();
exports.importerMap = new Map();
exports.importeeMap = new Map();
// files that are dirty (i.e. in the import chain between the accept boundary
// and the actual changed file) for an hmr update at a given timestamp.
exports.hmrDirtyFilesMap = new lru_cache_1.default({ max: 10 });
exports.latestVersionsMap = new Map();
exports.hmrPlugin = ({ root, app, server, watcher, resolver, config }) => {
app.use((ctx, next) => {
if (ctx.query.t) {
exports.latestVersionsMap.set(ctx.path, ctx.query.t);
}
return next();
});
// start a websocket server to send hmr notifications to the client
const wss = new ws_1.default.Server({ noServer: true });
server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] === 'vite-hmr') {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
}
});
wss.on('connection', (socket) => {
exports.debugHmr('ws client connected');
socket.send(JSON.stringify({ type: 'connected' }));
});
wss.on('error', (e) => {
if (e.code !== 'EADDRINUSE') {
console.error(chalk_1.default.red(`[vite] WebSocket server error:`));
console.error(e);
}
});
const send = (watcher.send = (payload) => {
const stringified = JSON.stringify(payload, null, 2);
exports.debugHmr(`update: ${stringified}`);
wss.clients.forEach((client) => {
if (client.readyState === ws_1.default.OPEN) {
client.send(stringified);
}
});
});
const handleJSReload = (watcher.handleJSReload = (filePath, timestamp = Date.now()) => {
// normal js file, but could be compiled from anything.
// bust the vue cache in case this is a src imported file
if (serverPluginVue_1.srcImportMap.has(filePath)) {
exports.debugHmr(`busting Vue cache for ${filePath}`);
serverPluginVue_1.vueCache.del(filePath);
}
const publicPath = resolver.fileToRequest(filePath);
const importers = exports.importerMap.get(publicPath);
if (importers || isHmrAccepted(publicPath, publicPath)) {
const hmrBoundaries = new Set();
const dirtyFiles = new Set();
dirtyFiles.add(publicPath);
const hasDeadEnd = walkImportChain(publicPath, importers || new Set(), hmrBoundaries, dirtyFiles);
// record dirty files - this is used when HMR requests coming in with
// timestamp to determine what files need to be force re-fetched
exports.hmrDirtyFilesMap.set(String(timestamp), dirtyFiles);
const relativeFile = '/' + slash_1.default(path_1.default.relative(root, filePath));
if (hasDeadEnd) {
send({
type: 'full-reload',
path: publicPath
});
console.log(chalk_1.default.green(`[vite] `) + `page reloaded.`);
}
else {
const boundaries = [...hmrBoundaries];
const file = boundaries.length === 1 ? boundaries[0] : `${boundaries.length} files`;
console.log(chalk_1.default.green(`[vite:hmr] `) +
`${file} hot updated due to change in ${relativeFile}.`);
send({
type: 'multi',
updates: boundaries.map((boundary) => {
return {
type: boundary.endsWith('vue') ? 'vue-reload' : 'js-update',
path: boundary,
changeSrcPath: publicPath,
timestamp
};
})
});
}
}
else {
exports.debugHmr(`no importers for ${publicPath}.`);
}
});
watcher.on('change', (file) => {
if (!(file.endsWith('.vue') || cssUtils_1.isCSSRequest(file))) {
// everything except plain .css are considered HMR dependencies.
// plain css has its own HMR logic in ./serverPluginCss.ts.
handleJSReload(file);
}
});
};
function walkImportChain(importee, importers, hmrBoundaries, dirtyFiles, currentChain = []) {
if (exports.hmrDeclineSet.has(importee)) {
// module explicitly declines HMR = dead end
return true;
}
if (isHmrAccepted(importee, importee)) {
// self-accepting module.
hmrBoundaries.add(importee);
dirtyFiles.add(importee);
return false;
}
for (const importer of importers) {
if (importer.endsWith('.vue') ||
// explicitly accepted by this importer
isHmrAccepted(importer, importee) ||
// importer is a self accepting module
isHmrAccepted(importer, importer)) {
// vue boundaries are considered dirty for the reload
if (importer.endsWith('.vue')) {
dirtyFiles.add(importer);
}
hmrBoundaries.add(importer);
currentChain.forEach((file) => dirtyFiles.add(file));
}
else {
const parentImpoters = exports.importerMap.get(importer);
if (!parentImpoters) {
return true;
}
else if (!currentChain.includes(importer)) {
if (walkImportChain(importer, parentImpoters, hmrBoundaries, dirtyFiles, currentChain.concat(importer))) {
return true;
}
}
}
}
return false;
}
function isHmrAccepted(importer, dep) {
const deps = exports.hmrAcceptanceMap.get(importer);
return deps ? deps.has(dep) : false;
}
function ensureMapEntry(map, key) {
let entry = map.get(key);
if (!entry) {
entry = new Set();
map.set(key, entry);
}
return entry;
}
exports.ensureMapEntry = ensureMapEntry;
function rewriteFileWithHMR(root, source, importer, resolver, s) {
let hasDeclined = false;
const registerDep = (e) => {
const deps = ensureMapEntry(exports.hmrAcceptanceMap, importer);
const depPublicPath = serverPluginModuleRewrite_1.resolveImport(root, importer, e.value, resolver);
deps.add(depPublicPath);
exports.debugHmr(` ${importer} accepts ${depPublicPath}`);
ensureMapEntry(exports.importerMap, depPublicPath).add(importer);
s.overwrite(e.start, e.end, JSON.stringify(depPublicPath));
};
const checkHotCall = (node, isTopLevel, isDevBlock) => {
if (node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
isMetaHot(node.callee.object)) {
if (isTopLevel) {
const { generateCodeFrame } = utils_1.resolveCompiler(root);
console.warn(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: import.meta.hot.accept() ` +
`should be wrapped in \`if (import.meta.hot) {}\` conditional ` +
`blocks so that they can be tree-shaken in production.`));
console.warn(chalk_1.default.yellow(generateCodeFrame(source, node.start, node.end)));
}
const method = node.callee.property.type === 'Identifier' && node.callee.property.name;
if (method === 'accept' || method === 'acceptDeps') {
if (!isDevBlock) {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: import.meta.hot.${method}() ` +
`cannot be conditional except for \`if (import.meta.hot)\` check ` +
`because the server relies on static analysis to construct the HMR graph.`));
}
// register the accepted deps
const accepted = node.arguments[0];
if (accepted && accepted.type === 'ArrayExpression') {
if (method !== 'acceptDeps') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.accept() only accepts ` +
`a single callback. Use hot.acceptDeps() to handle dep updates.`));
}
// import.meta.hot.accept(['./foo', './bar'], () => {})
accepted.elements.forEach((e) => {
if (e && e.type !== 'StringLiteral') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.accept() deps ` +
`list can only contain string literals.`));
}
else if (e) {
registerDep(e);
}
});
}
else if (accepted && accepted.type === 'StringLiteral') {
if (method !== 'acceptDeps') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.accept() only accepts ` +
`a single callback. Use hot.acceptDeps() to handle dep updates.`));
}
// import.meta.hot.accept('./foo', () => {})
registerDep(accepted);
}
else if (!accepted || accepted.type.endsWith('FunctionExpression')) {
if (method !== 'accept') {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: hot.acceptDeps() ` +
`expects a dependency or an array of dependencies. ` +
`Use hot.accept() for handling self updates.`));
}
// self accepting
// import.meta.hot.accept() OR import.meta.hot.accept(() => {})
ensureMapEntry(exports.hmrAcceptanceMap, importer).add(importer);
exports.debugHmr(`${importer} self accepts`);
}
else {
console.error(chalk_1.default.yellow(`[vite] HMR syntax error in ${importer}: ` +
`import.meta.hot.accept() expects a dep string, an array of ` +
`deps, or a callback.`));
}
}
if (method === 'decline') {
hasDeclined = true;
exports.hmrDeclineSet.add(importer);
}
}
};
const checkStatements = (node, isTopLevel, isDevBlock) => {
if (node.type === 'ExpressionStatement') {
// top level hot.accept() call
checkHotCall(node.expression, isTopLevel, isDevBlock);
}
// if (import.meta.hot) ...
if (node.type === 'IfStatement') {
const isDevBlock = isMetaHot(node.test);
if (node.consequent.type === 'BlockStatement') {
node.consequent.body.forEach((s) => checkStatements(s, false, isDevBlock));
}
if (node.consequent.type === 'ExpressionStatement') {
checkHotCall(node.consequent.expression, false, isDevBlock);
}
}
};
const ast = babelParse_1.parse(source);
ast.forEach((s) => checkStatements(s, true, false));
// inject import.meta.hot
s.prepend(`import { createHotContext } from "${serverPluginClient_1.clientPublicPath}"; ` +
`import.meta.hot = createHotContext(${JSON.stringify(importer)}); `);
// clear decline state
if (!hasDeclined) {
exports.hmrDeclineSet.delete(importer);
}
}
exports.rewriteFileWithHMR = rewriteFileWithHMR;
function isMetaHot(node) {
return (node.type === 'MemberExpression' &&
node.object.type === 'MetaProperty' &&
node.property.type === 'Identifier' &&
node.property.name === 'hot');
}
//# sourceMappingURL=serverPluginHmr.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,2 +0,0 @@
import { ServerPlugin } from './index';
export declare const htmlRewritePlugin: ServerPlugin;

View File

@@ -1,75 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.htmlRewritePlugin = void 0;
const index_1 = require("./index");
const serverPluginHmr_1 = require("./serverPluginHmr");
const serverPluginClient_1 = require("./serverPluginClient");
const es_module_lexer_1 = require("es-module-lexer");
const utils_1 = require("../utils");
const lru_cache_1 = __importDefault(require("lru-cache"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const debug = require('debug')('vite:rewrite');
const rewriteHtmlPluginCache = new lru_cache_1.default({ max: 20 });
exports.htmlRewritePlugin = ({ root, app, watcher, resolver, config }) => {
const devInjectionCode = `\n<script type="module">import "${serverPluginClient_1.clientPublicPath}"</script>\n`;
const scriptRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)([\s\S]*?)<\/script>/gm;
const srcRE = /\bsrc=(?:"([^"]+)"|'([^']+)'|([^'"\s]+)\b)/;
async function rewriteHtml(importer, html) {
await es_module_lexer_1.init;
html = await utils_1.transformIndexHtml(html, config.indexHtmlTransforms, 'pre', false);
html = html.replace(scriptRE, (matched, openTag, script) => {
if (script) {
return `${openTag}${index_1.rewriteImports(root, script, importer, resolver)}</script>`;
}
else {
const srcAttr = openTag.match(srcRE);
if (srcAttr) {
// register script as a import dep for hmr
const importee = resolver.normalizePublicPath(utils_1.cleanUrl(path_1.default.posix.resolve('/', srcAttr[1] || srcAttr[2])));
serverPluginHmr_1.debugHmr(` ${importer} imports ${importee}`);
serverPluginHmr_1.ensureMapEntry(serverPluginHmr_1.importerMap, importee).add(importer);
}
return matched;
}
});
const processedHtml = utils_1.injectScriptToHtml(html, devInjectionCode);
return await utils_1.transformIndexHtml(processedHtml, config.indexHtmlTransforms, 'post', false);
}
app.use(async (ctx, next) => {
await next();
if (ctx.status === 304) {
return;
}
if (ctx.response.is('html') && ctx.body) {
const importer = ctx.path;
const html = await utils_1.readBody(ctx.body);
if (rewriteHtmlPluginCache.has(html)) {
debug(`${ctx.path}: serving from cache`);
ctx.body = rewriteHtmlPluginCache.get(html);
}
else {
if (!html)
return;
ctx.body = await rewriteHtml(importer, html);
rewriteHtmlPluginCache.set(html, ctx.body);
}
return;
}
});
watcher.on('change', (file) => {
const path = resolver.fileToRequest(file);
if (path.endsWith('.html')) {
debug(`${path}: cache busted`);
watcher.send({
type: 'full-reload',
path
});
console.log(chalk_1.default.green(`[vite] `) + ` ${path} page reloaded.`);
}
});
};
//# sourceMappingURL=serverPluginHtml.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginHtml.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginHtml.ts"],"names":[],"mappings":";;;;;;AAAA,mCAAsD;AACtD,uDAAyE;AACzE,6DAAuD;AACvD,qDAAmD;AACnD,oCAKiB;AACjB,0DAAgC;AAChC,gDAAuB;AACvB,kDAAyB;AAEzB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAA;AAE9C,MAAM,sBAAsB,GAAG,IAAI,mBAAQ,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAA;AAE3C,QAAA,iBAAiB,GAAiB,CAAC,EAC9C,IAAI,EACJ,GAAG,EACH,OAAO,EACP,QAAQ,EACR,MAAM,EACP,EAAE,EAAE;IACH,MAAM,gBAAgB,GAAG,mCAAmC,qCAAgB,cAAc,CAAA;IAC1F,MAAM,QAAQ,GAAG,8EAA8E,CAAA;IAC/F,MAAM,KAAK,GAAG,4CAA4C,CAAA;IAE1D,KAAK,UAAU,WAAW,CAAC,QAAgB,EAAE,IAAY;QACvD,MAAM,sBAAS,CAAA;QACf,IAAI,GAAG,MAAM,0BAAkB,CAC7B,IAAI,EACJ,MAAM,CAAC,mBAAmB,EAC1B,KAAK,EACL,KAAK,CACN,CAAA;QACD,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE;YACzD,IAAI,MAAM,EAAE;gBACV,OAAO,GAAG,OAAO,GAAG,sBAAc,CAChC,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,QAAQ,CACT,WAAW,CAAA;aACb;iBAAM;gBACL,MAAM,OAAO,GAAG,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AI,CAAC,CAAA;aAC5C;iBAAM;gBACL,IAAI,CAAC,IAAI;oBAAE,OAAM;gBACjB,GAAG,CAAC,IAAI,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;gBAC5C,sBAAsB,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,CAAC,CAAA;aAC3C;YACD,OAAM;SACP;IACH,CAAC,CAAC,CAAA;IAEF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE;QAC5B,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,CAAA;QACzC,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;YAC1B,KAAK,CAAC,GAAG,IAAI,gBAAgB,CAAC,CAAA;YAC9B,OAAO,CAAC,IAAI,CAAC;gBACX,IAAI,EAAE,aAAa;gBACnB,IAAI;aACL,CAAC,CAAA;YACF,OAAO,CAAC,GAAG,CAAC,eAAK,CAAC,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,IAAI,iBAAiB,CAAC,CAAA;SAChE;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,2 +0,0 @@
import { ServerPlugin } from '.';
export declare const jsonPlugin: ServerPlugin;

View File

@@ -1,20 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonPlugin = void 0;
const utils_1 = require("../utils");
const pluginutils_1 = require("@rollup/pluginutils");
exports.jsonPlugin = ({ app }) => {
app.use(async (ctx, next) => {
await next();
// handle .json imports
// note ctx.body could be null if upstream set status to 304
if (ctx.path.endsWith('.json') && utils_1.isImportRequest(ctx) && ctx.body) {
ctx.type = 'js';
ctx.body = pluginutils_1.dataToEsm(JSON.parse((await utils_1.readBody(ctx.body))), {
namedExports: true,
preferConst: true
});
}
});
};
//# sourceMappingURL=serverPluginJson.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginJson.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginJson.ts"],"names":[],"mappings":";;;AACA,oCAAoD;AACpD,qDAA+C;AAElC,QAAA,UAAU,GAAiB,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE;IAClD,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,MAAM,IAAI,EAAE,CAAA;QACZ,uBAAuB;QACvB,4DAA4D;QAC5D,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,uBAAe,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE;YAClE,GAAG,CAAC,IAAI,GAAG,IAAI,CAAA;YACf,GAAG,CAAC,IAAI,GAAG,uBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,gBAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAE,CAAC,EAAE;gBAC5D,YAAY,EAAE,IAAI;gBAClB,WAAW,EAAE,IAAI;aAClB,CAAC,CAAA;SACH;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,5 +0,0 @@
import { ServerPlugin } from '.';
export declare const moduleIdToFileMap: Map<any, any>;
export declare const moduleFileToIdMap: Map<any, any>;
export declare const moduleRE: RegExp;
export declare const moduleResolvePlugin: ServerPlugin;

View File

@@ -1,87 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.moduleResolvePlugin = exports.moduleRE = exports.moduleFileToIdMap = exports.moduleIdToFileMap = void 0;
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const utils_1 = require("../utils");
const url_1 = require("url");
const resolver_1 = require("../resolver");
const debug = require('debug')('vite:resolve');
exports.moduleIdToFileMap = new Map();
exports.moduleFileToIdMap = new Map();
exports.moduleRE = /^\/@modules\//;
const getDebugPath = (root, p) => {
const relative = path_1.default.relative(root, p);
return relative.startsWith('..') ? p : relative;
};
// plugin for resolving /@modules/:id requests.
exports.moduleResolvePlugin = ({ root, app, resolver }) => {
const vueResolved = utils_1.resolveVue(root);
app.use(async (ctx, next) => {
if (!exports.moduleRE.test(ctx.path)) {
return next();
}
// path maybe contain encode chars
const id = decodeURIComponent(ctx.path.replace(exports.moduleRE, ''));
ctx.type = 'js';
const serve = async (id, file, type) => {
exports.moduleIdToFileMap.set(id, file);
exports.moduleFileToIdMap.set(file, ctx.path);
debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`);
await ctx.read(file);
return next();
};
// special handling for vue runtime in case it's not installed
if (!vueResolved.isLocal && id in vueResolved) {
return serve(id, vueResolved[id], 'non-local vue');
}
// already resolved and cached
const cachedPath = exports.moduleIdToFileMap.get(id);
if (cachedPath) {
return serve(id, cachedPath, 'cached');
}
// resolve from vite optimized modules
const optimized = resolver_1.resolveOptimizedModule(root, id);
if (optimized) {
return serve(id, optimized, 'optimized');
}
const referer = ctx.get('referer');
let importer;
// this is a map file request from browser dev tool
const isMapFile = ctx.path.endsWith('.map');
if (referer) {
importer = new url_1.URL(referer).pathname;
}
else if (isMapFile) {
// for some reason Chrome doesn't provide referer for source map requests.
// do our best to reverse-infer the importer.
importer = ctx.path.replace(/\.map$/, '');
}
const importerFilePath = importer ? resolver.requestToFile(importer) : root;
// #829 node package has sub-package(has package.json), should check it before `resolveNodeModuleFile`
const nodeModuleInfo = resolver_1.resolveNodeModule(root, id, resolver);
if (nodeModuleInfo) {
return serve(id, nodeModuleInfo.entryFilePath, 'node_modules');
}
const nodeModuleFilePath = resolver_1.resolveNodeModuleFile(importerFilePath, id);
if (nodeModuleFilePath) {
return serve(id, nodeModuleFilePath, 'node_modules');
}
if (isMapFile && importer) {
// the resolveNodeModuleFile doesn't work with linked pkg
// our last try: infer from the dir of importer
const inferMapPath = path_1.default.join(path_1.default.dirname(importerFilePath), path_1.default.basename(ctx.path));
if (fs_extra_1.default.existsSync(inferMapPath)) {
return serve(id, inferMapPath, 'map file in linked pkg');
}
}
console.error(chalk_1.default.red(`[vite] Failed to resolve module import "${id}". ` +
`(imported by ${importer || 'unknown'})`));
ctx.status = 404;
});
};
//# sourceMappingURL=serverPluginModuleResolve.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginModuleResolve.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginModuleResolve.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAuB;AACvB,kDAAyB;AACzB,wDAAyB;AAEzB,oCAAqC;AACrC,6BAAyB;AACzB,0CAIoB;AAEpB,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAA;AAEjC,QAAA,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAA;AAC7B,QAAA,iBAAiB,GAAG,IAAI,GAAG,EAAE,CAAA;AAE7B,QAAA,QAAQ,GAAG,eAAe,CAAA;AAEvC,MAAM,YAAY,GAAG,CAAC,IAAY,EAAE,CAAS,EAAE,EAAE;IAC/C,MAAM,QAAQ,GAAG,cAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IACvC,OAAO,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAA;AACjD,CAAC,CAAA;AAED,+CAA+C;AAClC,QAAA,mBAAmB,GAAiB,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE;IAC3E,MAAM,WAAW,GAAG,kBAAU,CAAC,IAAI,CAAC,CAAA;IAEpC,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC1B,IAAI,CAAC,gBAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YAC5B,OAAO,IAAI,EAAE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GAAG,CACP,2CAA2C,EAAE,KAAK;YAChD,gBAAgB,QAAQ,IAAI,SAAS,GAAG,CAC3C,CACF,CAAA;QACD,GAAG,CAAC,MAAM,GAAG,GAAG,CAAA;IAClB,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,5 +0,0 @@
import { ServerPlugin } from '.';
import { InternalResolver } from '../resolver';
export declare const moduleRewritePlugin: ServerPlugin;
export declare function rewriteImports(root: string, source: string, importer: string, resolver: InternalResolver, timestamp?: string): string;
export declare const resolveImport: (root: string, importer: string, id: string, resolver: InternalResolver, timestamp?: string | undefined) => string;

View File

@@ -1,220 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveImport = exports.rewriteImports = exports.moduleRewritePlugin = void 0;
const path_1 = __importDefault(require("path"));
const lru_cache_1 = __importDefault(require("lru-cache"));
const magic_string_1 = __importDefault(require("magic-string"));
const es_module_lexer_1 = require("es-module-lexer");
const resolver_1 = require("../resolver");
const serverPluginHmr_1 = require("./serverPluginHmr");
const serverPluginClient_1 = require("./serverPluginClient");
const utils_1 = require("../utils");
const chalk_1 = __importDefault(require("chalk"));
const cssUtils_1 = require("../utils/cssUtils");
const serverPluginEnv_1 = require("./serverPluginEnv");
const fs_extra_1 = __importDefault(require("fs-extra"));
const debug = require('debug')('vite:rewrite');
const rewriteCache = new lru_cache_1.default({ max: 1024 });
// Plugin for rewriting served js.
// - Rewrites named module imports to `/@modules/:id` requests, e.g.
// "vue" => "/@modules/vue"
// - Rewrites files containing HMR code (reference to `import.meta.hot`) to
// inject `import.meta.hot` and track HMR boundary accept whitelists.
// - Also tracks importer/importee relationship graph during the rewrite.
// The graph is used by the HMR plugin to perform analysis on file change.
exports.moduleRewritePlugin = ({ root, app, watcher, resolver }) => {
app.use(async (ctx, next) => {
await next();
if (ctx.status === 304) {
return;
}
// we are doing the js rewrite after all other middlewares have finished;
// this allows us to post-process javascript produced by user middlewares
// regardless of the extension of the original files.
const publicPath = ctx.path;
if (ctx.body &&
ctx.response.is('js') &&
!cssUtils_1.isCSSRequest(ctx.path) &&
!ctx.url.endsWith('.map') &&
!resolver.isPublicRequest(ctx.path) &&
// skip internal client
publicPath !== serverPluginClient_1.clientPublicPath &&
// need to rewrite for <script>\<template> part in vue files
!((ctx.path.endsWith('.vue') || ctx.vue) && ctx.query.type === 'style')) {
const content = await utils_1.readBody(ctx.body);
const cacheKey = publicPath + content;
const isHmrRequest = !!ctx.query.t;
if (!isHmrRequest && rewriteCache.has(cacheKey)) {
debug(`(cached) ${ctx.url}`);
ctx.body = rewriteCache.get(cacheKey);
}
else {
await es_module_lexer_1.init;
// dynamic import may contain extension-less path,
// (.e.g import(runtimePathString))
// so we need to normalize importer to ensure it contains extension
// before we perform hmr analysis.
// on the other hand, static import is guaranteed to have extension
// because they must all have gone through module rewrite.
const importer = utils_1.removeUnRelatedHmrQuery(resolver.normalizePublicPath(ctx.url));
ctx.body = rewriteImports(root, content, importer, resolver, ctx.query.t);
if (!isHmrRequest) {
rewriteCache.set(cacheKey, ctx.body);
}
}
}
else {
debug(`(skipped) ${ctx.url}`);
}
});
// bust module rewrite cache on file change
watcher.on('change', async (filePath) => {
const publicPath = resolver.fileToRequest(filePath);
// #662 use fs.read instead of cacheRead, avoid cache hit when request file
// and caused pass `notModified` into transform is always true
const cacheKey = publicPath + (await fs_extra_1.default.readFile(filePath)).toString();
debug(`${publicPath}: cache busted`);
rewriteCache.del(cacheKey);
});
};
function rewriteImports(root, source, importer, resolver, timestamp) {
// #806 strip UTF-8 BOM
if (source.charCodeAt(0) === 0xfeff) {
source = source.slice(1);
}
try {
let imports = [];
try {
imports = es_module_lexer_1.parse(source)[0];
}
catch (e) {
console.error(chalk_1.default.yellow(`[vite] failed to parse ${chalk_1.default.cyan(importer)} for import rewrite.\nIf you are using ` +
`JSX, make sure to named the file with the .jsx extension.`));
}
const hasHMR = source.includes('import.meta.hot');
const hasEnv = source.includes('import.meta.env');
if (imports.length || hasHMR || hasEnv) {
debug(`${importer}: rewriting`);
const s = new magic_string_1.default(source);
let hasReplaced = false;
const prevImportees = serverPluginHmr_1.importeeMap.get(importer);
const currentImportees = new Set();
serverPluginHmr_1.importeeMap.set(importer, currentImportees);
for (let i = 0; i < imports.length; i++) {
const { s: start, e: end, d: dynamicIndex } = imports[i];
let id = source.substring(start, end);
let hasLiteralDynamicId = false;
if (dynamicIndex >= 0) {
// #998 remove comment
id = id.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '');
const literalIdMatch = id.match(/^\s*(?:'([^']+)'|"([^"]+)")\s*$/);
if (literalIdMatch) {
hasLiteralDynamicId = true;
id = literalIdMatch[1] || literalIdMatch[2];
}
}
if (dynamicIndex === -1 || hasLiteralDynamicId) {
// do not rewrite external imports
if (utils_1.isExternalUrl(id)) {
continue;
}
const resolved = exports.resolveImport(root, importer, id, resolver, timestamp);
if (resolved !== id) {
debug(` "${id}" --> "${resolved}"`);
s.overwrite(start, end, hasLiteralDynamicId ? `'${resolved}'` : resolved);
hasReplaced = true;
}
// save the import chain for hmr analysis
const importee = utils_1.cleanUrl(resolved);
if (importee !== importer &&
// no need to track hmr client or module dependencies
importee !== serverPluginClient_1.clientPublicPath) {
currentImportees.add(importee);
serverPluginHmr_1.debugHmr(` ${importer} imports ${importee}`);
serverPluginHmr_1.ensureMapEntry(serverPluginHmr_1.importerMap, importee).add(importer);
}
}
else if (id !== 'import.meta' &&
!/\/\*\s*@vite-ignore\s*\*\//.test(id)) {
console.warn(chalk_1.default.yellow(`[vite] ignored dynamic import(${id}) in ${importer}.`));
}
}
if (hasHMR) {
serverPluginHmr_1.debugHmr(`rewriting ${importer} for HMR.`);
serverPluginHmr_1.rewriteFileWithHMR(root, source, importer, resolver, s);
hasReplaced = true;
}
if (hasEnv) {
debug(` injecting import.meta.env for ${importer}`);
s.prepend(`import __VITE_ENV__ from "${serverPluginEnv_1.envPublicPath}"; ` +
`import.meta.env = __VITE_ENV__; `);
hasReplaced = true;
}
// since the importees may have changed due to edits,
// check if we need to remove this importer from certain importees
if (prevImportees) {
prevImportees.forEach((importee) => {
if (!currentImportees.has(importee)) {
const importers = serverPluginHmr_1.importerMap.get(importee);
if (importers) {
importers.delete(importer);
}
}
});
}
if (!hasReplaced) {
debug(` nothing needs rewriting.`);
}
return hasReplaced ? s.toString() : source;
}
else {
debug(`${importer}: no imports found.`);
}
return source;
}
catch (e) {
console.error(`[vite] Error: module imports rewrite failed for ${importer}.\n`, e);
debug(source);
return source;
}
}
exports.rewriteImports = rewriteImports;
exports.resolveImport = (root, importer, id, resolver, timestamp) => {
id = resolver.alias(id) || id;
if (utils_1.bareImportRE.test(id)) {
// directly resolve bare module names to its entry path so that relative
// imports from it (including source map urls) can work correctly
id = `/@modules/${resolver_1.resolveBareModuleRequest(root, id, importer, resolver)}`;
}
else {
// 1. relative to absolute
// ./foo -> /some/path/foo
let { pathname, query } = resolver.resolveRelativeRequest(importer, id);
// 2. resolve dir index and extensions.
pathname = resolver.normalizePublicPath(pathname);
// 3. mark non-src imports
if (!query && path_1.default.extname(pathname) && !resolver_1.jsSrcRE.test(pathname)) {
query += `?import`;
}
id = pathname + query;
}
// 4. force re-fetch dirty imports by appending timestamp
if (timestamp) {
const dirtyFiles = serverPluginHmr_1.hmrDirtyFilesMap.get(timestamp);
const cleanId = utils_1.cleanUrl(id);
// only rewrite if:
if (dirtyFiles && dirtyFiles.has(cleanId)) {
// 1. this is a marked dirty file (in the import chain of the changed file)
id += `${id.includes(`?`) ? `&` : `?`}t=${timestamp}`;
}
else if (serverPluginHmr_1.latestVersionsMap.has(cleanId)) {
// 2. this file was previously hot-updated and has an updated version
id += `${id.includes(`?`) ? `&` : `?`}t=${serverPluginHmr_1.latestVersionsMap.get(cleanId)}`;
}
}
return id;
};
//# sourceMappingURL=serverPluginModuleRewrite.js.map

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +0,0 @@
import { ServerPlugin } from '.';
import { IKoaProxiesOptions } from 'koa-proxies';
export declare type ProxiesOptions = IKoaProxiesOptions & {
ws: boolean;
};
export declare const proxyPlugin: ServerPlugin;

View File

@@ -1,33 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.proxyPlugin = void 0;
const url_1 = require("url");
exports.proxyPlugin = ({ app, config, server }) => {
if (!config.proxy) {
return;
}
const debug = require('debug')('vite:proxy');
const proxy = require('koa-proxies');
const options = config.proxy;
Object.keys(options).forEach((path) => {
let opts = options[path];
if (typeof opts === 'string') {
opts = { target: opts };
}
opts.logs = (ctx, target) => {
debug(`${ctx.req.method} ${ctx.req.oldPath} proxy to -> ${new url_1.URL(ctx.req.url, target)}`);
};
app.use(proxy(path, opts));
});
server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] !== 'vite-hmr') {
for (const path in options) {
let opts = options[path];
if (typeof opts === 'object' && opts.ws) {
proxy.proxy.ws(req, socket, head, opts);
}
}
}
});
};
//# sourceMappingURL=serverPluginProxy.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginProxy.js","sourceRoot":"","sources":["../../../src/node/server/serverPluginProxy.ts"],"names":[],"mappings":";;;AACA,6BAAyB;AAKZ,QAAA,WAAW,GAAiB,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE;IACnE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE;QACjB,OAAM;KACP;IAED,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,YAAY,CAAC,CAAA;IAC5C,MAAM,KAAK,GAAG,OAAO,CAAC,aAAa,CAAC,CAAA;IACpC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAA;IAC5B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QACpC,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;QACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;YAC5B,IAAI,GAAG,EAAE,MAAM,EAAE,IAAI,EAAoB,CAAA;SAC1C;QACD,IAAI,CAAC,IAAI,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YAC1B,KAAK,CACH,GAAG,GAAG,CAAC,GAAG,CAAC,MAAM,IAAK,GAAG,CAAC,GAAW,CAAC,OAAO,gBAAgB,IAAI,SAAG,CAClE,GAAG,CAAC,GAAG,CAAC,GAAI,EACZ,MAAM,CACP,EAAE,CACJ,CAAA;QACH,CAAC,CAAA;QACD,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;IAC5B,CAAC,CAAC,CAAA;IAEF,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE;QACzC,IAAI,GAAG,CAAC,OAAO,CAAC,wBAAwB,CAAC,KAAK,UAAU,EAAE;YACxD,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;gBAC1B,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;gBACxB,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,EAAE,EAAE;oBACvC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;iBACxC;aACF;SACF;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,3 +0,0 @@
import { ServerPlugin } from '.';
export declare const seenUrls: Set<unknown>;
export declare const serveStaticPlugin: ServerPlugin;

View File

@@ -1,77 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.serveStaticPlugin = exports.seenUrls = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const send = require('koa-send');
const debug = require('debug')('vite:history');
exports.seenUrls = new Set();
exports.serveStaticPlugin = ({ root, app, resolver, config }) => {
app.use(async (ctx, next) => {
// short circuit requests that have already been explicitly handled
if (ctx.body || ctx.status !== 404) {
return;
}
// warn non-root references to assets under /public/
if (ctx.path.startsWith('/public/') && resolver.isAssetRequest(ctx.path)) {
console.error(chalk_1.default.yellow(`[vite] files in the public directory are served at the root path.\n` +
` ${chalk_1.default.blue(ctx.path)} should be changed to ${chalk_1.default.blue(ctx.path.replace(/^\/public\//, '/'))}.`));
}
// handle possible user request -> file aliases
const expectsHtml = ctx.headers.accept && ctx.headers.accept.includes('text/html');
if (!expectsHtml) {
const filePath = resolver.requestToFile(ctx.path);
if (filePath !== ctx.path &&
fs_1.default.existsSync(filePath) &&
fs_1.default.statSync(filePath).isFile()) {
await ctx.read(filePath);
}
}
await next();
// the first request to the server should never 304
if (exports.seenUrls.has(ctx.url) && ctx.fresh) {
ctx.status = 304;
}
exports.seenUrls.add(ctx.url);
});
app.use(require('koa-etag')());
app.use(require('koa-static')(root));
app.use(require('koa-static')(path_1.default.join(root, 'public')));
// history API fallback
app.use(async (ctx, next) => {
if (ctx.status !== 404) {
return next();
}
if (ctx.method !== 'GET') {
debug(`not redirecting ${ctx.url} (not GET)`);
return next();
}
const accept = ctx.headers && ctx.headers.accept;
if (typeof accept !== 'string') {
debug(`not redirecting ${ctx.url} (no headers.accept)`);
return next();
}
if (accept.includes('application/json')) {
debug(`not redirecting ${ctx.url} (json)`);
return next();
}
if (!accept.includes('text/html')) {
debug(`not redirecting ${ctx.url} (not accepting html)`);
return next();
}
debug(`redirecting ${ctx.url} to /index.html`);
try {
await send(ctx, `index.html`, { root });
}
catch (e) {
ctx.url = '/index.html';
ctx.status = 404;
return next();
}
});
};
//# sourceMappingURL=serverPluginServeStatic.js.map

View File

@@ -1 +0,0 @@
{"version":3,"file":"serverPluginServeStatic.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AG,sBAAsB,CAAC,CAAA;YACvD,OAAO,IAAI,EAAE,CAAA;SACd;QAED,IAAI,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;YACvC,KAAK,CAAC,mBAAmB,GAAG,CAAC,GAAG,SAAS,CAAC,CAAA;YAC1C,OAAO,IAAI,EAAE,CAAA;SACd;QAED,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE;YACjC,KAAK,CAAC,mBAAmB,GAAG,CAAC,GAAG,uBAAuB,CAAC,CAAA;YACxD,OAAO,IAAI,EAAE,CAAA;SACd;QAED,KAAK,CAAC,eAAe,GAAG,CAAC,GAAG,iBAAiB,CAAC,CAAA;QAC9C,IAAI;YACF,MAAM,IAAI,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,CAAC,CAAA;SACxC;QAAC,OAAO,CAAC,EAAE;YACV,GAAG,CAAC,GAAG,GAAG,aAAa,CAAA;YACvB,GAAG,CAAC,MAAM,GAAG,GAAG,CAAA;YAChB,OAAO,IAAI,EAAE,CAAA;SACd;IACH,CAAC,CAAC,CAAA;AACJ,CAAC,CAAA"}

View File

@@ -1,6 +0,0 @@
import { ServerPlugin } from '.';
import { ExistingRawSourceMap } from 'rollup';
import { RawSourceMap } from 'source-map';
export declare type SourceMap = ExistingRawSourceMap | RawSourceMap;
export declare function mergeSourceMap(oldMap: SourceMap | null | undefined, newMap: SourceMap): SourceMap;
export declare const sourceMapPlugin: ServerPlugin;

Some files were not shown because too many files have changed in this diff Show More