提交 e9585a8e 编写于 作者: fxy060608's avatar fxy060608

refactor: remove mpType=page (#3020)

上级 2b215b0f
......@@ -7,6 +7,8 @@ import {
parseManifestJsonOnce,
uniConsolePlugin,
UNI_EASYCOM_EXCLUDE,
isVueSfcFile,
isUniPageFile,
} from '@dcloudio/uni-cli-shared'
import { plugins as nvuePlugins } from '@dcloudio/uni-cli-nvue'
import { uniAppPlugin } from './plugin'
......@@ -20,19 +22,20 @@ import { uniStatsPlugin } from './plugins/stats'
import { uniEasycomPlugin } from './plugins/easycom'
import { uniConfusionPlugin } from './plugins/confusion'
function initUniCssScopedPluginOptions() {
const styleIsolation = getAppStyleIsolation(
parseManifestJsonOnce(process.env.UNI_INPUT_DIR)
)
function initUniCssScopedPluginFilter(
inputDir: string
): void | ((id: string) => boolean) {
const styleIsolation = getAppStyleIsolation(parseManifestJsonOnce(inputDir))
if (styleIsolation === 'shared') {
return
}
if (styleIsolation === 'isolated') {
// isolated: 对所有非 App.vue 增加 scoped
return {}
return (id) => isVueSfcFile(id) && !id.endsWith('App.vue')
}
// apply-shared: 仅对非页面组件增加 scoped
return { exclude: /mpType=page/ }
return (id) =>
isVueSfcFile(id) && !id.endsWith('App.vue') && !isUniPageFile(id, inputDir)
}
const plugins = [
......@@ -58,11 +61,12 @@ const plugins = [
uniConfusionPlugin(),
]
const uniCssScopedPluginOptions = initUniCssScopedPluginOptions()
if (uniCssScopedPluginOptions) {
plugins.unshift(uniCssScopedPlugin(uniCssScopedPluginOptions))
const filter = initUniCssScopedPluginFilter(process.env.UNI_INPUT_DIR)
if (filter) {
plugins.unshift(uniCssScopedPlugin({ filter }))
}
if (process.env.UNI_NVUE_COMPILER !== 'vue') {
plugins.push(...nvuePlugins)
}
export default plugins
......@@ -10,6 +10,7 @@ import {
resolveMainPathOnce,
normalizePath,
removeExt,
isUniPageFile,
} from '@dcloudio/uni-cli-shared'
let appCss = ''
......@@ -21,14 +22,15 @@ function normalizeCssChunkFilename(id: string) {
)
}
export const configResolved: Plugin['configResolved'] = (config) => {
const mainPath = resolveMainPathOnce(process.env.UNI_INPUT_DIR)
const inputDir = process.env.UNI_INPUT_DIR
const mainPath = resolveMainPathOnce(inputDir)
removePlugins('vite:import-analysis', config)
injectCssPlugin(config)
injectCssPostPlugin(config, {
chunkCssFilename(id: string) {
if (id === mainPath) {
return 'app.css'
} else if (id.includes('mpType=page')) {
} else if (isUniPageFile(id, inputDir)) {
return normalizeCssChunkFilename(id)
}
},
......
......@@ -14,11 +14,11 @@ export function definePageCode(pagesJson: Record<string, any>) {
if (process.env.UNI_APP_CODE_SPLITING) {
// 拆分页面
importPagesCode.push(
`const ${pageIdentifier} = ()=>import('./${pagePathWithExtname}?mpType=page')`
`const ${pageIdentifier} = ()=>import('./${pagePathWithExtname}')`
)
} else {
importPagesCode.push(
`import ${pageIdentifier} from './${pagePathWithExtname}?mpType=page'`
`import ${pageIdentifier} from './${pagePathWithExtname}'`
)
}
definePagesCode.push(`__definePage('${pagePath}',${pageIdentifier})`)
......
import path from 'path'
import { extend } from '@vue/shared'
import { ComponentJson, PageWindowOptions, UsingComponents } from './types'
import { removeExt, normalizeNodeModules } from '../../utils'
import { removeExt, normalizePath, normalizeNodeModules } from '../../utils'
import { relativeFile } from '../../resolve'
import { isVueSfcFile } from '../../vue/utils'
let appJsonCache: Record<string, any> = {}
const jsonFilesCache = new Map<string, string>()
......@@ -9,10 +11,17 @@ const jsonPagesCache = new Map<string, PageWindowOptions>()
const jsonComponentsCache = new Map<string, ComponentJson>()
const jsonUsingComponentsCache = new Map<string, UsingComponents>()
export function isPageFile(file: string) {
export function isMiniProgramPageFile(file: string, inputDir?: string) {
if (inputDir && path.isAbsolute(file)) {
file = normalizePath(path.relative(inputDir, file))
}
return jsonPagesCache.has(removeExt(file))
}
export function isMiniProgramPageSfcFile(file: string, inputDir?: string) {
return isVueSfcFile(file) && isMiniProgramPageFile(file, inputDir)
}
export function hasJsonFile(filename: string) {
return (
filename === 'app' ||
......
......@@ -2,8 +2,28 @@ import fs from 'fs'
import path from 'path'
import { extend, hasOwn, isArray, isPlainObject } from '@vue/shared'
import { addLeadingSlash, once, TABBAR_HEIGHT } from '@dcloudio/uni-shared'
import { normalizePath } from '../utils'
import { removeExt, normalizePath } from '../utils'
import { parseJson } from './json'
import { isVueSfcFile } from '../vue/utils'
const pagesCacheSet: Set<string> = new Set()
export function isUniPageFile(
file: string,
inputDir: string = process.env.UNI_INPUT_DIR
) {
if (inputDir && path.isAbsolute(file)) {
file = normalizePath(path.relative(inputDir, file))
}
return pagesCacheSet.has(removeExt(file))
}
export function isUniPageSfcFile(
file: string,
inputDir: string = process.env.UNI_INPUT_DIR
) {
return isVueSfcFile(file) && isUniPageFile(file, inputDir)
}
export const parsePagesJson = (
inputDir: string,
......@@ -18,7 +38,13 @@ export const parsePagesJson = (
}
export const parsePagesJsonOnce = once(parsePagesJson)
/**
* 目前 App 和 H5 使用了该方法
* @param jsonStr
* @param platform
* @param param2
* @returns
*/
export function normalizePagesJson(
jsonStr: string,
platform: UniApp.PLATFORM,
......@@ -74,6 +100,10 @@ export function normalizePagesJson(
delete pagesJson.tabBar
}
}
// 缓存页面列表
pagesCacheSet.clear()
pagesJson.pages.forEach((page) => pagesCacheSet.add(page.path))
return pagesJson
}
......
import path from 'path'
import debug from 'debug'
import type { Plugin } from 'vite'
import { parseVueRequest } from '../utils'
import { EXTNAME_VUE } from '../../constants'
import { createFilter, FilterPattern } from '@rollup/pluginutils'
import { preHtml, preJs } from '../../preprocess'
const debugScoped = debug('vite:uni:scoped')
......@@ -18,34 +16,22 @@ function addScoped(code: string) {
}
interface UniCssScopedPluginOptions {
include?: FilterPattern
exclude?: FilterPattern
filter: (id: string) => boolean
}
export function uniCssScopedPlugin(
options: UniCssScopedPluginOptions = {}
{ filter }: UniCssScopedPluginOptions = { filter: () => false }
): Plugin {
const filter = createFilter(options.include, options.exclude)
return {
name: 'vite:uni-css-scoped',
enforce: 'pre',
transform(code, id) {
if (id.endsWith('App.vue')) {
return
}
if (!filter(id)) return null
const { filename, query } = parseVueRequest(id)
if (query.vue) {
return
}
if (EXTNAME_VUE.includes(path.extname(filename))) {
debugScoped(id)
return {
code: addScoped(code),
map: null,
}
}
},
// 仅 h5
handleHotUpdate(ctx) {
......
......@@ -9,7 +9,6 @@ export interface VueQuery {
index?: number
lang?: string
raw?: boolean
mpType?: 'page'
}
export function parseVueRequest(id: string) {
......
......@@ -17,10 +17,17 @@ import {
} from '@vue/compiler-core'
import { createAssetUrlTransformWithOptions } from './transforms/templateTransformAssetUrl'
import { createSrcsetTransformWithOptions } from './transforms/templateTransformSrcset'
import { parseVueRequest } from '../vite/utils/url'
import { EXTNAME_VUE_RE } from '../constants'
export const VUE_REF = 'r'
export const VUE_REF_IN_FOR = 'r-i-f'
export function isVueSfcFile(id: string) {
const { filename, query } = parseVueRequest(id)
return EXTNAME_VUE_RE.test(filename) && !query.vue
}
export function isUserComponent(
node: RootNode | TemplateChildNode,
context: {
......
import {
isVueSfcFile,
uniCssScopedPlugin,
UNI_EASYCOM_EXCLUDE,
} from '@dcloudio/uni-cli-shared'
......@@ -16,7 +17,9 @@ import { uniSSRPlugin } from './plugins/ssr'
export default [
uniEasycomPlugin({ exclude: UNI_EASYCOM_EXCLUDE }),
uniCssScopedPlugin(),
uniCssScopedPlugin({
filter: (id) => isVueSfcFile(id) && !id.endsWith('App.vue'),
}),
uniResolveIdPlugin(),
uniMainJsPlugin(),
uniManifestJsonPlugin(),
......
......@@ -181,7 +181,7 @@ function generatePageDefineCode(pageOptions: UniApp.PagesJsonPageOptions) {
pagePathWithExtname = pageOptions.path + '.vue'
}
const pageIdent = normalizeIdentifier(pageOptions.path)
return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}?mpType=page')
return `const ${pageIdent}Loader = ()=>import('./${pagePathWithExtname}')
const ${pageIdent} = defineAsyncComponent(extend({loader:${pageIdent}Loader},AsyncComponentOptions))`
}
......
......@@ -5,6 +5,7 @@ import {
EXTNAME_JS_RE,
normalizePath,
parseVueRequest,
isUniPageSfcFile,
} from '@dcloudio/uni-cli-shared'
const debugSetup = debug('vite:uni:setup')
......@@ -27,7 +28,7 @@ export function uniSetupPlugin(): Plugin {
`;import { setupApp } from '@dcloudio/uni-h5';setupApp(_sfc_main);`
)
}
if (query.mpType === 'page') {
if (isUniPageSfcFile(id)) {
debugSetup(filename)
// js,ts,jsx,tsx
const isJs = EXTNAME_JS_RE.test(filename)
......
......@@ -62,7 +62,7 @@ export function uniEntryPlugin({
)
this.addWatchFile(filepath)
return {
code: `import MiniProgramPage from '${filepath}?mpType=page'
code: `import MiniProgramPage from '${filepath}'
${global}.createPage(MiniProgramPage)`,
}
} else if (isUniComponentUrl(id)) {
......
import { OutputAsset, OutputChunk } from 'rollup'
import type { Plugin } from 'vite'
import { isPageFile, relativeFile } from '@dcloudio/uni-cli-shared'
import { isMiniProgramPageFile, relativeFile } from '@dcloudio/uni-cli-shared'
import { UniMiniProgramPluginOptions } from '../plugin'
export function uniSubpackagePlugin({
......@@ -16,7 +16,7 @@ export function uniSubpackagePlugin({
const appJsFile = 'app.js'
const appCssFile = 'app' + extname
Object.keys(bundle).forEach((name) => {
if (!isPageFile(name)) {
if (!isMiniProgramPageFile(name)) {
return
}
// 仅页面级 wxss 需要补充 app.wxss
......
......@@ -8,7 +8,7 @@ import {
normalizeMiniProgramFilename,
addMiniProgramUsingComponents,
removeExt,
isPageFile,
isMiniProgramPageFile,
} from '@dcloudio/uni-cli-shared'
import { virtualComponentPath, virtualPagePath } from './entry'
......@@ -52,11 +52,7 @@ export function uniUsingComponentsPlugin(
export function dynamicImport(name: string, value: string) {
// 开发者可能将页面作为组件来引用
const relativePath = normalizeMiniProgramFilename(
value,
process.env.UNI_INPUT_DIR
)
if (isPageFile(relativePath)) {
if (isMiniProgramPageFile(value)) {
return `const ${name} = ()=>import('${virtualPagePath(value)}')`
}
return `const ${name} = ()=>import('${virtualComponentPath(value)}')`
......
# [1.2.0](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.8...plugin-vue-jsx@1.2.0) (2021-09-29)
### Bug Fixes
* **deps:** update all non-major dependencies ([#4545](https://github.com/vitejs/vite/issues/4545)) ([a44fd5d](https://github.com/vitejs/vite/commit/a44fd5d38679da0be2536103e83af730cda73a95))
* normalize internal plugin names ([#4976](https://github.com/vitejs/vite/issues/4976)) ([37f0b2f](https://github.com/vitejs/vite/commit/37f0b2fff74109d381513ed052a32b43655ee11d))
## [1.1.8](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.7...plugin-vue-jsx@1.1.8) (2021-09-07)
### Bug Fixes
* hmr doesn't work when modifying the code of jsx in sfc ([#4563](https://github.com/vitejs/vite/issues/4563)) ([1012367](https://github.com/vitejs/vite/commit/101236794c5d6d28591302d5552cb1c0ab8f4115))
## [1.1.7](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.6...plugin-vue-jsx@1.1.7) (2021-07-27)
### Bug Fixes
* **deps:** update all non-major dependencies ([#4387](https://github.com/vitejs/vite/issues/4387)) ([2f900ba](https://github.com/vitejs/vite/commit/2f900ba4d4ad8061e0046898e8d1de3129e7f784))
## [1.1.6](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.5...plugin-vue-jsx@1.1.6) (2021-06-27)
### Bug Fixes
* **deps:** update all non-major dependencies ([#3791](https://github.com/vitejs/vite/issues/3791)) ([74d409e](https://github.com/vitejs/vite/commit/74d409eafca8d74ec4a6ece621ea2895bc1f2a32))
* **plugin-vue-jsx:** replace default export with helper during SSR ([#3966](https://github.com/vitejs/vite/issues/3966)) ([bc86464](https://github.com/vitejs/vite/commit/bc86464d3c6591eae96e070a1724a3f21874c8ce))
* **ssr:** normalize manifest filenames ([#3706](https://github.com/vitejs/vite/issues/3706)) ([aa8ca3f](https://github.com/vitejs/vite/commit/aa8ca3f35218c9fb48f87d3f6f4681d379ee45ca)), closes [#3303](https://github.com/vitejs/vite/issues/3303)
### Features
* **plugin-vue-jsx:** jsx plugin should have extra babel plugins option ([#3923](https://github.com/vitejs/vite/issues/3923)) ([aada0c5](https://github.com/vitejs/vite/commit/aada0c5e71e4826cf049596f3459d48b386ea4da))
## [1.1.5](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.4...plugin-vue-jsx@1.1.5) (2021-06-01)
### Bug Fixes
* include/exclude options for vue-jsx .d.ts ([#3573](https://github.com/vitejs/vite/issues/3573)) ([82ec0ca](https://github.com/vitejs/vite/commit/82ec0ca69c1f077cf518073edca4e6580ebd4892))
## [1.1.4](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.3...plugin-vue-jsx@1.1.4) (2021-05-03)
### Features
* include/exclude options for vue-jsx plugin ([#1953](https://github.com/vitejs/vite/issues/1953)) ([fbecf1e](https://github.com/vitejs/vite/commit/fbecf1e5349ea5da8ff6f194efdcb152e2995398))
## [1.1.3](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.2...plugin-vue-jsx@1.1.3) (2021-03-31)
### Bug Fixes
* ignore babelrc ([#2766](https://github.com/vitejs/vite/issues/2766)) ([23c4114](https://github.com/vitejs/vite/commit/23c41149ddf74261f7615d22e59b39a017b79509)), closes [#2722](https://github.com/vitejs/vite/issues/2722)
## [1.1.2](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.1...plugin-vue-jsx@1.1.2) (2021-02-24)
## [1.1.1](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.1.0...plugin-vue-jsx@1.1.1) (2021-02-24)
### Bug Fixes
* **plugin-vue-jsx:** do not read babel configuration ([#2181](https://github.com/vitejs/vite/issues/2181)) ([8f0dc25](https://github.com/vitejs/vite/commit/8f0dc25e943ff490eefa0ed3663205a14e8eed9e))
# [1.1.0](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.3...plugin-vue-jsx@1.1.0) (2021-02-09)
### Features
* **plugin-vue-jsx:** register jsx module during ssr ([7a6aa2a](https://github.com/vitejs/vite/commit/7a6aa2ad2689bf8221389924a608876866db7b0a))
## [1.0.3](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.2...plugin-vue-jsx@1.0.3) (2021-02-08)
### Bug Fixes
* **plugin-vue-jsx:** support ssr ([30e92a1](https://github.com/vitejs/vite/commit/30e92a150e060e8bedcb6f0c477dcaa87e7996d6)), closes [#1939](https://github.com/vitejs/vite/issues/1939)
## [1.0.2](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.1...plugin-vue-jsx@1.0.2) (2021-01-12)
### Bug Fixes
* **plugin-vue-jsx:** files should include `index.d.ts` ([#1473](https://github.com/vitejs/vite/issues/1473)) [skip ci] ([f3ab497](https://github.com/vitejs/vite/commit/f3ab497b762e267721ace628bc6c7c5695b0d431))
* **plugin-vue-jsx:** fix define call check ([#1480](https://github.com/vitejs/vite/issues/1480)) ([4ea065f](https://github.com/vitejs/vite/commit/4ea065f6278f30c022ed291bfb0412a674b18dd4))
* **plugin-vue-jsx:** fix vue jsx hmr ([#1495](https://github.com/vitejs/vite/issues/1495)) ([6bdc3eb](https://github.com/vitejs/vite/commit/6bdc3eb2d004a28d2934946e33602f832b1ad8f2))
### Performance Improvements
* **plugin-vue-jsx:** only gen source map when necessary ([bfa8530](https://github.com/vitejs/vite/commit/bfa8530fc60deada634c38cfd6a23ab8ca05d47c))
## [1.0.1](https://github.com/vitejs/vite/compare/plugin-vue-jsx@1.0.0...plugin-vue-jsx@1.0.1) (2021-01-04)
### Bug Fixes
* still let esbuild handle ts ([5903554](https://github.com/vitejs/vite/commit/59035546db7ff4b7020242ba994a5395aac92802))
# 2.0.0-beta.4 (2021-01-04)
# 1.0.0 (2021-01-04)
### Features
* vue-jsx support ([e756c48](https://github.com/vitejs/vite/commit/e756c48ed4c7372d4c8e26016ba4b91880e7e248))
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
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.
# @vitejs/plugin-vue-jsx [![npm](https://img.shields.io/npm/v/@vitejs/plugin-vue-jsx.svg)](https://npmjs.com/package/@vitejs/plugin-vue-jsx)
Provides Vue 3 JSX & TSX support with HMR.
```js
// vite.config.js
import vueJsx from '@vitejs/plugin-vue-jsx'
export default {
plugins: [
vueJsx({
// options are passed on to @vue/babel-plugin-jsx
})
]
}
```
## Options
See [@vue/babel-plugin-jsx](https://github.com/vuejs/jsx-next).
## HMR Detection
This plugin supports HMR of Vue JSX components. The detection requirements are:
- The component must be exported.
- The component must be declared by calling `defineComponent` via a root-level statement, either variable declaration or export declaration.
### Supported patterns
```jsx
import { defineComponent } from 'vue'
// named exports w/ variable declaration: ok
export const Foo = defineComponent({})
// named exports referencing variable declaration: ok
const Bar = defineComponent({ render() { return <div>Test</div> }})
export { Bar }
// default export call: ok
export default defineComponent({ render() { return <div>Test</div> }})
// default export referencing variable declaration: ok
const Baz = defineComponent({ render() { return <div>Test</div> }})
export default Baz
```
### Non-supported patterns
```jsx
// not using `defineComponent` call
export const Bar = { ... }
// not exported
const Foo = defineComponent(...)
```
import { Plugin } from 'vite'
import { VueJSXPluginOptions } from '@vue/babel-plugin-jsx'
import { FilterPattern } from '@rollup/pluginutils'
declare interface FilterOptions {
include?: FilterPattern
exclude?: FilterPattern
}
declare function createPlugin(
options?: VueJSXPluginOptions & FilterOptions & { babelPlugins?: any[] }
): Plugin
export default createPlugin
// @ts-check
const babel = require('@babel/core')
const jsx = require('@vue/babel-plugin-jsx')
const importMeta = require('@babel/plugin-syntax-import-meta')
const { createFilter, normalizePath } = require('@rollup/pluginutils')
const hash = require('hash-sum')
const path = require('path')
const ssrRegisterHelperId = '/__vue-jsx-ssr-register-helper'
const ssrRegisterHelperCode =
`import { useSSRContext } from "vue"\n` +
`export ${ssrRegisterHelper.toString()}`
/**
* This function is serialized with toString() and evaluated as a virtual
* module during SSR
* @param {import('vue').ComponentOptions} comp
* @param {string} filename
*/
function ssrRegisterHelper(comp, filename) {
const setup = comp.setup
comp.setup = (props, ctx) => {
// @ts-ignore
const ssrContext = useSSRContext()
;(ssrContext.modules || (ssrContext.modules = new Set())).add(filename)
if (setup) {
return setup(props, ctx)
}
}
}
/**
* @typedef { import('@rollup/pluginutils').FilterPattern} FilterPattern
* @typedef { { include?: FilterPattern, exclude?: FilterPattern, babelPlugins?: any[] } } CommonOptions
*/
/**
*
* @param {import('@vue/babel-plugin-jsx').VueJSXPluginOptions & CommonOptions} options
* @returns {import('vite').Plugin}
*/
function vueJsxPlugin(options = {}) {
let root = ''
let needHmr = false
let needSourceMap = true
return {
name: 'vite:vue-jsx',
config(config) {
return {
// only apply esbuild to ts files
// since we are handling jsx and tsx now
esbuild: {
include: /\.ts$/
},
define: {
__VUE_OPTIONS_API__: true,
__VUE_PROD_DEVTOOLS__: false,
...config.define
}
}
},
configResolved(config) {
needHmr = config.command === 'serve' && !config.isProduction
needSourceMap = config.command === 'serve' || !!config.build.sourcemap
root = config.root
},
resolveId(id) {
if (id === ssrRegisterHelperId) {
return id
}
},
load(id) {
if (id === ssrRegisterHelperId) {
return ssrRegisterHelperCode
}
},
transform(code, id, opt) {
const ssr = typeof opt === 'boolean' ? opt : (opt && opt.ssr) === true
const {
include,
exclude,
babelPlugins = [],
...babelPluginOptions
} = options
// fixed by xxxxxx
const filter = createFilter(include || /\.[jt]sx/, exclude)
if (filter(id)) {
const plugins = [importMeta, [jsx, babelPluginOptions], ...babelPlugins]
// fixed by xxxxxx
if (id.includes('.tsx')) {
plugins.push([
require('@babel/plugin-transform-typescript'),
// @ts-ignore
{ isTSX: true, allowExtensions: true }
])
}
const result = babel.transformSync(code, {
babelrc: false,
ast: true,
plugins,
sourceMaps: needSourceMap,
sourceFileName: id,
configFile: false
})
if (!ssr && !needHmr) {
return {
code: result.code,
map: result.map
}
}
// check for hmr injection
/**
* @type {{ name: string }[]}
*/
const declaredComponents = []
/**
* @type {{
* local: string,
* exported: string,
* id: string,
* }[]}
*/
const hotComponents = []
let hasDefault = false
for (const node of result.ast.program.body) {
if (node.type === 'VariableDeclaration') {
const names = parseComponentDecls(node, code)
if (names.length) {
declaredComponents.push(...names)
}
}
if (node.type === 'ExportNamedDeclaration') {
if (
node.declaration &&
node.declaration.type === 'VariableDeclaration'
) {
hotComponents.push(
...parseComponentDecls(node.declaration, code).map(
({ name }) => ({
local: name,
exported: name,
id: hash(id + name)
})
)
)
} else if (node.specifiers.length) {
for (const spec of node.specifiers) {
if (
spec.type === 'ExportSpecifier' &&
spec.exported.type === 'Identifier'
) {
const matched = declaredComponents.find(
({ name }) => name === spec.local.name
)
if (matched) {
hotComponents.push({
local: spec.local.name,
exported: spec.exported.name,
id: hash(id + spec.exported.name)
})
}
}
}
}
}
if (node.type === 'ExportDefaultDeclaration') {
if (node.declaration.type === 'Identifier') {
const _name = node.declaration.name
const matched = declaredComponents.find(
({ name }) => name === _name
)
if (matched) {
hotComponents.push({
local: node.declaration.name,
exported: 'default',
id: hash(id + 'default')
})
}
} else if (isDefineComponentCall(node.declaration)) {
hasDefault = true
hotComponents.push({
local: '__default__',
exported: 'default',
id: hash(id + 'default')
})
}
}
}
if (hotComponents.length) {
if (hasDefault && (needHmr || ssr)) {
result.code =
result.code.replace(
/export default defineComponent/g,
`const __default__ = defineComponent`
) + `\nexport default __default__`
}
if (needHmr && !ssr && !/\?vue&type=script/.test(id)) {
let code = result.code
let callbackCode = ``
for (const { local, exported, id } of hotComponents) {
code +=
`\n${local}.__hmrId = "${id}"` +
`\n__VUE_HMR_RUNTIME__.createRecord("${id}", ${local})`
callbackCode += `\n__VUE_HMR_RUNTIME__.reload("${id}", __${exported})`
}
code += `\nimport.meta.hot.accept(({${hotComponents
.map((c) => `${c.exported}: __${c.exported}`)
.join(',')}}) => {${callbackCode}\n})`
result.code = code
}
if (ssr) {
const normalizedId = normalizePath(path.relative(root, id))
let ssrInjectCode =
`\nimport { ssrRegisterHelper } from "${ssrRegisterHelperId}"` +
`\nconst __moduleId = ${JSON.stringify(normalizedId)}`
for (const { local } of hotComponents) {
ssrInjectCode += `\nssrRegisterHelper(${local}, __moduleId)`
}
result.code += ssrInjectCode
}
}
return {
code: result.code,
map: result.map
}
}
}
}
}
/**
* @param {import('@babel/core').types.VariableDeclaration} node
* @param {string} source
*/
function parseComponentDecls(node, source) {
const names = []
for (const decl of node.declarations) {
if (decl.id.type === 'Identifier' && isDefineComponentCall(decl.init)) {
names.push({
name: decl.id.name
})
}
}
return names
}
/**
* @param {import('@babel/core').types.Node} node
*/
function isDefineComponentCall(node) {
return (
node &&
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'defineComponent'
)
}
module.exports = vueJsxPlugin
vueJsxPlugin.default = vueJsxPlugin
{
"name": "@vitejs/plugin-vue-jsx",
"version": "1.2.0",
"license": "MIT",
"author": "Evan You",
"files": [
"index.js",
"index.d.ts"
],
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . --lerna-package plugin-vue-jsx",
"release": "node ../../scripts/release.js --skipBuild"
},
"engines": {
"node": ">=12.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vitejs/vite.git",
"directory": "packages/plugin-vue-jsx"
},
"bugs": {
"url": "https://github.com/vitejs/vite/issues"
},
"homepage": "https://github.com/vitejs/vite/tree/main/packages/plugin-vue-jsx#readme",
"dependencies": {
"@babel/core": "^7.15.5",
"@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/plugin-transform-typescript": "^7.15.4",
"@rollup/pluginutils": "^4.1.1",
"@vue/babel-plugin-jsx": "^1.0.7",
"hash-sum": "^2.0.0"
}
}
......@@ -30,6 +30,7 @@
"@rollup/pluginutils": "^4.1.1",
"@vitejs/plugin-legacy": "^1.6.3",
"@vitejs/plugin-vue": "^1.10.1",
"@vitejs/plugin-vue-jsx": "^1.3.0",
"@vue/compiler-core": "3.2.23",
"@vue/compiler-dom": "3.2.23",
"@vue/compiler-sfc": "3.2.23",
......
......@@ -38,25 +38,20 @@ export function uniPrePlugin(options: UniPluginFilterOptions): Plugin {
debugPreJsTry(id)
}
const hasEndif = isPre && code.includes('#endif')
if (isHtml && hasEndif) {
if (!hasEndif) {
return
}
if (isHtml) {
code = preHtml(code)
debugPreHtml(id)
}
if (isJs && hasEndif) {
if (isJs) {
code = preJs(code)
debugPreJs(id)
}
// https://github.com/vitejs/vite/blob/bc35fe994d48b2bd7076474f4a1a7b8ae5e8f401/packages/vite/src/node/server/sourcemap.ts#L15
// 读取sourcemap时,需要移除?mpType=page等参数,否则读取不到提示文件不存在
const map = this.getCombinedSourcemap()
if (map) {
map.sources = map.sources.map(
(source) => parseVueRequest(source).filename
)
}
return {
code,
map,
map: this.getCombinedSourcemap(),
}
},
}
......
import fs from 'fs'
import path from 'path'
import debug from 'debug'
import { Plugin } from 'vite'
import { unescape } from 'querystring'
import {
isInHBuilderX,
normalizePath,
parseVueRequest,
resolveBuiltIn,
} from '@dcloudio/uni-cli-shared'
import { resolveBuiltIn } from '@dcloudio/uni-cli-shared'
import { VitePluginUniResolvedOptions } from '../..'
......@@ -27,15 +20,6 @@ const BUILT_IN_MODULES = {
export type BuiltInModulesKey = keyof typeof BUILT_IN_MODULES
const FS_PREFIX = `/@fs/`
const VOLUME_RE = /^[A-Z]:/i
function fsPathFromId(id: string) {
const fsPath = normalizePath(id.slice(FS_PREFIX.length))
return fsPath.startsWith('/') || fsPath.match(VOLUME_RE)
? fsPath
: `/${fsPath}`
}
export function uniResolveIdPlugin(
options: VitePluginUniResolvedOptions
): Plugin {
......@@ -53,22 +37,6 @@ export function uniResolveIdPlugin(
path.join(id, BUILT_IN_MODULES[id as BuiltInModulesKey])
))
}
// fixed by vite 3.5.2 https://github.com/vitejs/vite/pull/4728
if (isInHBuilderX()) {
// 解决文件路径包含转义字符(空格)等
// /@fs/Applications/HBuilderX%20Alpha.app/Contents/HBuilderX/plugins/uniapp-cli-vite/node_modules/vite/dist/client/env.mjs
if (id.startsWith(FS_PREFIX) && id.includes('uniapp-cli-vite')) {
return fsPathFromId(unescape(id))
}
}
},
load(id) {
if (options.command === 'build') {
const { filename, query } = parseVueRequest(id)
if (query.mpType === 'page') {
return fs.readFileSync(filename, 'utf8')
}
}
},
}
}
......@@ -5,7 +5,8 @@ import type { Options as VueOptions } from '@vitejs/plugin-vue'
import type { Options as ViteLegacyOptions } from '@vitejs/plugin-legacy'
import type { VueJSXPluginOptions } from '@vue/babel-plugin-jsx'
import vuePlugin from '@vitejs/plugin-vue'
import type ViteLegacyPlugin from '@vitejs/plugin-legacy'
import vueJsxPlugin from '@vitejs/plugin-vue-jsx'
import legacyPlugin from '@vitejs/plugin-legacy'
import {
CopyOptions,
......@@ -55,11 +56,6 @@ export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
export { runDev, runBuild } from './cli/action'
let createViteLegacyPlugin: typeof ViteLegacyPlugin | undefined
try {
createViteLegacyPlugin = require('@vitejs/plugin-legacy')
} catch (e) {}
export default function uniPlugin(
rawOptions: VitePluginUniOptions = {}
): Plugin[] {
......@@ -80,9 +76,9 @@ export default function uniPlugin(
const plugins: Plugin[] = []
if (createViteLegacyPlugin && options.viteLegacyOptions) {
if (options.viteLegacyOptions) {
plugins.push(
...(createViteLegacyPlugin(
...(legacyPlugin(
initPluginViteLegacyOptions(options)
) as unknown as Plugin[])
)
......@@ -101,7 +97,7 @@ export default function uniPlugin(
if (options.vueJsxOptions) {
plugins.push(
require('../lib/plugin-vue-jsx/index')(
vueJsxPlugin(
initPluginVueJsxOptions(options, uniPluginOptions.compilerOptions)
)
)
......
......@@ -785,6 +785,7 @@ importers:
'@types/sass': ^1.16.0
'@vitejs/plugin-legacy': ^1.6.3
'@vitejs/plugin-vue': ^1.10.1
'@vitejs/plugin-vue-jsx': ^1.3.0
'@vue/babel-plugin-jsx': ^1.1.1
'@vue/compiler-core': 3.2.23
'@vue/compiler-dom': 3.2.23
......@@ -808,6 +809,7 @@ importers:
'@rollup/pluginutils': 4.1.1
'@vitejs/plugin-legacy': 1.6.3_vite@2.6.14
'@vitejs/plugin-vue': 1.10.1_vite@2.6.14
'@vitejs/plugin-vue-jsx': 1.3.0
'@vue/compiler-core': 3.2.23
'@vue/compiler-dom': 3.2.23
'@vue/compiler-sfc': 3.2.23
......@@ -1377,7 +1379,6 @@ packages:
dependencies:
'@babel/core': 7.16.0
'@babel/helper-plugin-utils': 7.14.5
dev: true
/@babel/plugin-syntax-logical-assignment-operators/7.10.4_@babel+core@7.16.0:
resolution: {integrity: sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==}
......@@ -2930,7 +2931,6 @@ packages:
hash-sum: 2.0.0
transitivePeerDependencies:
- supports-color
dev: true
/@vitejs/plugin-vue/1.10.1_vite@2.6.14:
resolution: {integrity: sha512-oL76QETMSpVE9jIScirGB2bYJEVU/+r+g+K7oG+sXPs9TZljqveoVRsmLyXlMZTjpQkLL8gz527cW80NMGVKJg==}
......@@ -2942,7 +2942,6 @@ packages:
/@vue/babel-helper-vue-transform-on/1.0.2:
resolution: {integrity: sha512-hz4R8tS5jMn8lDq6iD+yWL6XNB699pGIVLk7WSJnn1dbpjaazsjZQkieJoRX6gW5zpYSCFqQ7jUquPNY65tQYA==}
dev: true
/@vue/babel-plugin-jsx/1.1.1_@babel+core@7.16.0:
resolution: {integrity: sha512-j2uVfZjnB5+zkcbc/zsOc0fSNGCMMjaEXP52wdwdIfn0qjFfEYpYZBFKFg+HHnQeJCVrjOeO0YxgaL7DMrym9w==}
......@@ -2959,7 +2958,6 @@ packages:
transitivePeerDependencies:
- '@babel/core'
- supports-color
dev: true
/@vue/compiler-core/3.2.23:
resolution: {integrity: sha512-4ZhiI/orx+7EJ1B+0zjgvXMV2uRN+XBfG06UN2sJfND9rH5gtEQT3QmO4erum1o6Irl7y754W8/KSaDJh4EUQg==}
......@@ -3748,7 +3746,6 @@ packages:
/camelcase/6.2.1:
resolution: {integrity: sha512-tVI4q5jjFV5CavAU8DXfza/TJcZutVKo/5Foskmsqcm0MsL91moHvwiGNnqaa2o6PF/7yT5ikDRcVcl8Rj6LCA==}
engines: {node: '>=10'}
dev: true
/caniuse-lite/1.0.30001282:
resolution: {integrity: sha512-YhF/hG6nqBEllymSIjLtR2iWDDnChvhnVJqp+vloyt2tEHFG1yBR+ac2B/rOw0qOK0m0lEXU2dv4E/sMk5P9Kg==}
......@@ -5304,7 +5301,6 @@ packages:
/html-tags/3.1.0:
resolution: {integrity: sha512-1qYz89hW3lFDEazhjW0yVAV87lw8lVkrJocr72XmBkMKsoSVJCQx3W8BXsC7hO2qAt8BoVjYjtAcZ9perqGnNg==}
engines: {node: '>=8'}
dev: true
/http-errors/1.7.2:
resolution: {integrity: sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==}
......@@ -8087,7 +8083,6 @@ packages:
/svg-tags/1.0.0:
resolution: {integrity: sha1-WPcc7jvVGbWdSyqEO2x95krAR2Q=}
dev: true
/symbol-tree/3.2.4:
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册