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

wip(mp): easycom

上级 76e85b8b
export { default as chokidar } from 'chokidar'
......@@ -17,4 +17,5 @@ export * from './filter'
export * from './esbuild'
export { M } from './messages'
export * from './exports'
export { checkUpdate } from './checkUpdate'
import {
getRouterOptions,
parseManifestJsonOnce,
} from '@dcloudio/uni-cli-shared'
import { Plugin } from 'vite'
import { uniTimestampMiddleware } from './middlewares/timestamp'
import { initSSR } from './ssr'
import { initStatic } from './static'
export function createConfigureServer(): Plugin['configureServer'] {
return function (server) {
initSSR(server)
const routerOptions = getRouterOptions(
parseManifestJsonOnce(process.env.UNI_INPUT_DIR)
)
if (routerOptions.mode === 'history') {
server.middlewares.use(uniTimestampMiddleware(server))
}
return () => {
initStatic(server)
}
}
}
......@@ -69,11 +69,11 @@ interface UniStaticMiddlewareOptions {
resolve: (pathname: string) => string | void
}
type NextHandler = () => void | Promise<void>
export type NextHandler = () => void | Promise<void>
export function uniStaticMiddleware(opts: UniStaticMiddlewareOptions) {
const isEtag = !!opts.etag
return function (
return function staticMiddleware(
req: IncomingMessage,
res: ServerResponse,
next: NextHandler
......
import { parse as parseUrl } from 'url'
import { IncomingMessage, ServerResponse } from 'http'
import { ViteDevServer } from 'vite'
import { NextHandler } from './static'
import path from 'path'
import { EXTNAME_VUE_RE } from '@dcloudio/uni-cli-shared'
export function uniTimestampMiddleware(server: ViteDevServer) {
return async function timestampMiddleware(
req: IncomingMessage,
_: ServerResponse,
next: NextHandler
) {
// 当页面被作为组件引用时,会导致history刷新该页面直接显示js代码,因为该页面已被缓存为了module,
// https://github.com/vitejs/vite/blob/702d50315535c189151c67d33e4a22124f926bed/packages/vite/src/node/server/transformRequest.ts#L52
// /pages/tabBar/API/API
let { url } = req
if (url) {
const base = server.config.base
const parsed = parseUrl(url)
let newUrl = url
if ((parsed.pathname || '/').startsWith(base)) {
newUrl = newUrl.replace(base, '/')
}
if (
!path.extname(newUrl) &&
!newUrl.endsWith('/') &&
!newUrl.includes('?')
) {
const module = await server.moduleGraph.getModuleByUrl(newUrl)
if (module && module.file && EXTNAME_VUE_RE.test(module.file)) {
// /pages/tabBar/API/API => /pages/tabBar/API/API?__t__=time
req.url = url + '?__t__=' + Date.now()
}
}
}
next()
}
}
import { ViteDevServer } from 'vite'
export const external = [
'@dcloudio/uni-app',
'@dcloudio/uni-cloud',
'@dcloudio/uni-h5',
'@dcloudio/uni-h5-vue',
'@dcloudio/uni-i18n',
'@dcloudio/uni-shared',
'@dcloudio/uni-stat',
'@vue/shared',
'vue',
'vue-i18n',
'vue-router',
'vuex',
]
export function initSSR(server: ViteDevServer) {
const { ssrLoadModule } = server
let added = false
server.ssrLoadModule = (url) => {
const res = ssrLoadModule(url)
if (!added) {
// HBuilderX项目,根目录可能没有package.json,导致 ssrExternals 不生效
added = true
if ((server as any)._ssrExternals) {
const { _ssrExternals } = server as unknown as {
_ssrExternals: string[]
}
external.forEach((module) => {
if (!_ssrExternals.includes(module)) {
_ssrExternals.push(module)
}
})
}
}
return res
}
}
......@@ -2,13 +2,14 @@ import fs from 'fs'
import path from 'path'
import debug from 'debug'
import { ViteDevServer } from 'vite'
import { isImportRequest } from '@dcloudio/uni-cli-shared'
import { VitePluginUniResolvedOptions } from '..'
import { createFilter } from '@rollup/pluginutils'
import {
isImportRequest,
normalizePath,
PUBLIC_DIR,
} from '@dcloudio/uni-cli-shared'
import { uniStaticMiddleware } from './middlewares/static'
import { createPublicFileFilter } from '../utils'
const debugStatic = debug('vite:uni:static')
/**
......@@ -16,10 +17,7 @@ const debugStatic = debug('vite:uni:static')
* @param server
* @param param
*/
export const serveStatic = (
server: ViteDevServer,
{ inputDir }: VitePluginUniResolvedOptions
) => {
export const initStatic = (server: ViteDevServer) => {
const filter = createPublicFileFilter()
const serve = uniStaticMiddleware({
etag: true,
......@@ -27,7 +25,7 @@ export const serveStatic = (
if (!filter(pathname)) {
return
}
const filename = path.join(inputDir, pathname)
const filename = path.join(process.env.UNI_INPUT_DIR, pathname)
if (fs.existsSync(filename)) {
debugStatic(filename, 'success')
return filename
......@@ -44,3 +42,11 @@ export const serveStatic = (
return serve(req, res, next)
})
}
export function createPublicFileFilter(base: string = '/') {
const publicDir = normalizePath(path.join(base, PUBLIC_DIR + '/**/*'))
const uniModulesDir = normalizePath(
path.join(base, 'uni_modules/*/' + PUBLIC_DIR + '/**/*')
)
return createFilter([publicDir, uniModulesDir])
}
import fs from 'fs'
import path from 'path'
import { parse as parseUrl } from 'url'
import { isH5CustomElement, isH5NativeTag } from '@dcloudio/uni-shared'
import {
isInHBuilderX,
resolveMainPathOnce,
UniVitePlugin,
getRouterOptions,
parseManifestJsonOnce,
EXTNAME_VUE_RE,
} from '@dcloudio/uni-cli-shared'
import { createHandleHotUpdate } from './handleHotUpdate'
import { createTransformIndexHtml } from './transformIndexHtml'
import { createDefine } from '../utils/features'
import { isSsr } from '../utils'
import { ViteDevServer } from 'vite'
import { esbuildPrePlugin } from './esbuild/esbuildPrePlugin'
import { isH5CustomElement, isH5NativeTag } from '@dcloudio/uni-shared'
const external = [
'@dcloudio/uni-app',
'@dcloudio/uni-cloud',
'@dcloudio/uni-h5',
'@dcloudio/uni-h5-vue',
'@dcloudio/uni-i18n',
'@dcloudio/uni-shared',
'@dcloudio/uni-stat',
'@vue/shared',
'vue',
'vue-i18n',
'vue-router',
'vuex',
]
import { external } from './configureServer/ssr'
import { createConfigureServer } from './configureServer'
export const UniH5Plugin: UniVitePlugin = {
name: 'vite:uni-h5',
......@@ -85,59 +67,7 @@ export const UniH5Plugin: UniVitePlugin = {
// TODO 禁止 optimizeDeps
;(config as any).cacheDir = ''
},
configureServer(server: ViteDevServer) {
const { ssrLoadModule } = server
let added = false
server.ssrLoadModule = (url) => {
const res = ssrLoadModule(url)
if (!added) {
// HBuilderX项目,根目录可能没有package.json,导致 ssrExternals 不生效
added = true
if ((server as any)._ssrExternals) {
const { _ssrExternals } = server as unknown as {
_ssrExternals: string[]
}
external.forEach((module) => {
if (!_ssrExternals.includes(module)) {
_ssrExternals.push(module)
}
})
}
}
return res
}
const routerOptions = getRouterOptions(
parseManifestJsonOnce(process.env.UNI_INPUT_DIR)
)
if (routerOptions.mode === 'history') {
server.middlewares.use(async (req, res, next) => {
// 当页面被作为组件引用时,会导致history刷新该页面直接显示js代码,因为该页面已被缓存为了module,
// https://github.com/vitejs/vite/blob/702d50315535c189151c67d33e4a22124f926bed/packages/vite/src/node/server/transformRequest.ts#L52
// /pages/tabBar/API/API
let { url } = req
if (url) {
const base = server.config.base
const parsed = parseUrl(url)
let newUrl = url
if ((parsed.pathname || '/').startsWith(base)) {
newUrl = newUrl.replace(base, '/')
}
if (
!path.extname(newUrl) &&
!newUrl.endsWith('/') &&
!newUrl.includes('?')
) {
const module = await server.moduleGraph.getModuleByUrl(newUrl)
if (module && module.file && EXTNAME_VUE_RE.test(module.file)) {
// /pages/tabBar/API/API => /pages/tabBar/API/API?__t__=time
req.url = url + '?__t__=' + Date.now()
}
}
}
next()
})
}
},
configureServer: createConfigureServer(),
handleHotUpdate: createHandleHotUpdate(),
transformIndexHtml: createTransformIndexHtml(),
}
import { extend, isSymbol, isObject, toRawType, def, hasChanged, isArray, isFunction, NOOP, remove, toHandlerKey, camelize, capitalize, isString, normalizeClass, normalizeStyle, isOn, isPromise, EMPTY_OBJ, isSet, isMap, isPlainObject, toTypeString, invokeArrayFns, hasOwn, NO, isIntegerKey, toNumber, hyphenate, isReservedProp, EMPTY_ARR, makeMap, stringifyStyle as stringifyStyle$1 } from '@vue/shared';
export { camelize as c, camelize, extend as e, hyphenate as h, normalizeClass as n, normalizeClass, normalizeProps, normalizeStyle, toDisplayString as t, toDisplayString, toHandlerKey } from '@vue/shared';
import { extend, isSymbol, isObject, toRawType, def, hasChanged, isArray, isFunction, NOOP, remove, toHandlerKey, camelize, capitalize, isString, normalizeClass, normalizeStyle, isOn, isPromise, EMPTY_OBJ, isSet, isMap, isPlainObject, toTypeString, invokeArrayFns, hasOwn, NO, isIntegerKey, toNumber, hyphenate, isReservedProp, EMPTY_ARR, makeMap, stringifyStyle as stringifyStyle$1, toDisplayString } from '@vue/shared';
export { camelize, normalizeClass, normalizeProps, normalizeStyle, toDisplayString, toHandlerKey } from '@vue/shared';
import { isRootHook, ON_ERROR, UniLifecycleHooks } from '@dcloudio/uni-shared';
function warn(msg, ...args) {
......@@ -4290,6 +4290,9 @@ const version = "3.2.20";
*/
const resolveFilter = null;
function unwrapper(target) {
return toRaw(unref(target));
}
// import deepCopy from './deepCopy'
/**
* https://raw.githubusercontent.com/Tencent/westore/master/packages/westore/utils/diff.js
......@@ -4304,7 +4307,7 @@ function diff(current, pre) {
return result;
}
function syncKeys(current, pre) {
current = unref(current);
current = unwrapper(current);
if (current === pre)
return;
const rootCurrentType = toTypeString(current);
......@@ -4329,7 +4332,7 @@ function syncKeys(current, pre) {
}
}
function _diff(current, pre, path, result) {
current = unref(current);
current = unwrapper(current);
if (current === pre)
return;
const rootCurrentType = toTypeString(current);
......@@ -4341,7 +4344,7 @@ function _diff(current, pre, path, result) {
}
else {
for (let key in current) {
const currentValue = unref(current[key]);
const currentValue = unwrapper(current[key]);
const preValue = pre[key];
const currentType = toTypeString(currentValue);
const preType = toTypeString(preValue);
......@@ -4483,10 +4486,10 @@ function patch(instance, data, oldData) {
if (!data) {
return;
}
// 序列化
pauseTracking();
data = JSON.parse(JSON.stringify(data));
resetTracking();
// 通常不用序列化,但是好像部分边界情况需要,目前还未排查到
// pauseTracking()
// data = JSON.parse(JSON.stringify(data))
// resetTracking()
const ctx = instance.ctx;
const mpType = ctx.mpType;
if (mpType === 'page' || mpType === 'component') {
......@@ -4495,7 +4498,9 @@ function patch(instance, data, oldData) {
const mpInstance = ctx.$scope;
const keys = Object.keys(data);
// data.__webviewId__ = mpInstance.data.__webviewId__
pauseTracking();
const diffData = diff(data, oldData || getMPInstanceData(mpInstance, keys));
resetTracking();
if (Object.keys(diffData).length) {
console.log('[' +
+new Date() +
......@@ -4891,46 +4896,6 @@ var plugin = {
},
};
/**
* Actual implementation
*/
function vFor(source, renderItem) {
let ret;
if (isArray(source) || isString(source)) {
ret = new Array(source.length);
for (let i = 0, l = source.length; i < l; i++) {
ret[i] = renderItem(source[i], i, i);
}
}
else if (typeof source === 'number') {
if ((process.env.NODE_ENV !== 'production') && !Number.isInteger(source)) {
warn$1(`The v-for range expect an integer value but got ${source}.`);
return [];
}
ret = new Array(source);
for (let i = 0; i < source; i++) {
ret[i] = renderItem(i + 1, i, i);
}
}
else if (isObject(source)) {
if (source[Symbol.iterator]) {
ret = Array.from(source, (item, i) => renderItem(item, i, i));
}
else {
const keys = Object.keys(source);
ret = new Array(keys.length);
for (let i = 0, l = keys.length; i < l; i++) {
const key = keys[i];
ret[i] = renderItem(source[key], key, i);
}
}
}
else {
ret = [];
}
return ret;
}
function vOn(value) {
const instance = getCurrentInstance();
const name = 'e' + instance.$ei++;
......@@ -5000,6 +4965,46 @@ function patchStopImmediatePropagation(e, value) {
}
}
/**
* Actual implementation
*/
function vFor(source, renderItem) {
let ret;
if (isArray(source) || isString(source)) {
ret = new Array(source.length);
for (let i = 0, l = source.length; i < l; i++) {
ret[i] = renderItem(source[i], i, i);
}
}
else if (typeof source === 'number') {
if ((process.env.NODE_ENV !== 'production') && !Number.isInteger(source)) {
warn$1(`The v-for range expect an integer value but got ${source}.`);
return [];
}
ret = new Array(source);
for (let i = 0; i < source; i++) {
ret[i] = renderItem(i + 1, i, i);
}
}
else if (isObject(source)) {
if (source[Symbol.iterator]) {
ret = Array.from(source, (item, i) => renderItem(item, i, i));
}
else {
const keys = Object.keys(source);
ret = new Array(keys.length);
for (let i = 0, l = keys.length; i < l; i++) {
const key = keys[i];
ret[i] = renderItem(source[key], key, i);
}
}
}
else {
ret = [];
}
return ret;
}
function renderSlot(name, props = {}) {
const instance = getCurrentInstance();
const vueIds = instance.attrs.vI;
......@@ -5069,10 +5074,21 @@ function setupDevtoolsPlugin() {
// noop
}
const o = (value) => vOn(value);
const f = (source, renderItem) => vFor(source, renderItem);
const r = (name, props) => renderSlot(name, props);
const w = (fn, options) => withScopedSlot(fn, options);
const s = (value) => stringifyStyle(value);
const c = (str) => camelize(str);
const e = (target, ...sources) => extend(target, ...sources);
const h = (str) => hyphenate(str);
const n = (value) => normalizeClass(value);
const t = (val) => toDisplayString(val);
function createApp(rootComponent, rootProps = null) {
rootComponent && (rootComponent.mpType = 'app');
return createVueApp(rootComponent, rootProps).use(plugin);
}
const createSSRApp = createApp;
export { EffectScope, ReactiveEffect, callWithAsyncErrorHandling, callWithErrorHandling, computed, createApp, createSSRApp, createVNode$1 as createVNode, createVueApp, customRef, defineComponent, defineEmits, defineExpose, defineProps, effect, effectScope, vFor as f, getCurrentInstance, getCurrentScope, inject, injectHook, isInSSRComponentSetup, isProxy, isReactive, isReadonly, isRef, logError, markRaw, mergeDefaults, mergeProps, nextTick, vOn as o, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onUnmounted, onUpdated, patch, provide, proxyRefs, queuePostFlushCb, renderSlot as r, reactive, readonly, ref, resolveComponent, resolveDirective, resolveFilter, stringifyStyle as s, setupDevtoolsPlugin, shallowReactive, shallowReadonly, shallowRef, stop, toHandlers, toRaw, toRef, toRefs, triggerRef, unref, useAttrs, useSSRContext, useSlots, version, withScopedSlot as w, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withModifiers, withScopeId };
export { EffectScope, ReactiveEffect, c, callWithAsyncErrorHandling, callWithErrorHandling, computed, createApp, createSSRApp, createVNode$1 as createVNode, createVueApp, customRef, defineComponent, defineEmits, defineExpose, defineProps, e, effect, effectScope, f, getCurrentInstance, getCurrentScope, h, inject, injectHook, isInSSRComponentSetup, isProxy, isReactive, isReadonly, isRef, logError, markRaw, mergeDefaults, mergeProps, n, nextTick, o, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onUnmounted, onUpdated, patch, provide, proxyRefs, queuePostFlushCb, r, reactive, readonly, ref, resolveComponent, resolveDirective, resolveFilter, s, setupDevtoolsPlugin, shallowReactive, shallowReadonly, shallowRef, stop, t, toHandlers, toRaw, toRef, toRefs, triggerRef, unref, useAttrs, useSSRContext, useSlots, version, w, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withModifiers, withScopeId };
......@@ -4290,6 +4290,9 @@ const version = "3.2.20";
*/
const resolveFilter = null;
function unwrapper(target) {
return toRaw(unref(target));
}
// import deepCopy from './deepCopy'
/**
* https://raw.githubusercontent.com/Tencent/westore/master/packages/westore/utils/diff.js
......@@ -4304,7 +4307,7 @@ function diff(current, pre) {
return result;
}
function syncKeys(current, pre) {
current = unref(current);
current = unwrapper(current);
if (current === pre)
return;
const rootCurrentType = toTypeString(current);
......@@ -4329,7 +4332,7 @@ function syncKeys(current, pre) {
}
}
function _diff(current, pre, path, result) {
current = unref(current);
current = unwrapper(current);
if (current === pre)
return;
const rootCurrentType = toTypeString(current);
......@@ -4341,7 +4344,7 @@ function _diff(current, pre, path, result) {
}
else {
for (let key in current) {
const currentValue = unref(current[key]);
const currentValue = unwrapper(current[key]);
const preValue = pre[key];
const currentType = toTypeString(currentValue);
const preType = toTypeString(preValue);
......@@ -4483,10 +4486,10 @@ function patch(instance, data, oldData) {
if (!data) {
return;
}
// 序列化
pauseTracking();
data = JSON.parse(JSON.stringify(data));
resetTracking();
// 通常不用序列化,但是好像部分边界情况需要,目前还未排查到
// pauseTracking()
// data = JSON.parse(JSON.stringify(data))
// resetTracking()
const ctx = instance.ctx;
const mpType = ctx.mpType;
if (mpType === 'page' || mpType === 'component') {
......@@ -4495,7 +4498,9 @@ function patch(instance, data, oldData) {
const mpInstance = ctx.$scope;
const keys = Object.keys(data);
// data.__webviewId__ = mpInstance.data.__webviewId__
pauseTracking();
const diffData = diff(data, oldData || getMPInstanceData(mpInstance, keys));
resetTracking();
if (Object.keys(diffData).length) {
console.log('[' +
+new Date() +
......
export { vFor } from './vFor'
export { vOn } from './vOn'
export { renderSlot } from './renderSlot'
export { withScopedSlot } from './withScopedSlot'
export { stringifyStyle } from './style'
import {
camelize,
extend,
hyphenate,
normalizeClass,
toDisplayString,
} from '@vue/shared'
import { vOn } from './vOn'
import { vFor, VForItem } from './vFor'
import { renderSlot } from './renderSlot'
import { withScopedSlot } from './withScopedSlot'
import { stringifyStyle } from './style'
export { setupDevtoolsPlugin } from './devtools'
export const o: typeof vOn = (value) => vOn(value)
export const f: typeof vFor = (
source: any,
renderItem: (...args: any[]) => VForItem
) => vFor(source, renderItem)
export const r: typeof renderSlot = (name, props) => renderSlot(name, props)
export const w: typeof withScopedSlot = (fn, options) =>
withScopedSlot(fn, options)
export const s: typeof stringifyStyle = (value) => stringifyStyle(value)
export const c: typeof camelize = (str) => camelize(str)
export const e: typeof extend = (target: object, ...sources: any[]) =>
extend(target, ...sources)
export const h: typeof hyphenate = (str) => hyphenate(str)
export const n: typeof normalizeClass = (value) => normalizeClass(value)
export const t: typeof toDisplayString = (val) => toDisplayString(val)
import { isArray, isObject, isString } from '@vue/shared'
import { warn } from 'vue'
type VForItem = Record<string, unknown>
export type VForItem = Record<string, unknown>
/**
* v-for string
......
......@@ -6,20 +6,6 @@ export function createApp(rootComponent: unknown, rootProps = null) {
return createVueApp(rootComponent, rootProps).use(plugin)
}
export const createSSRApp = createApp
export {
vOn as o,
vFor as f,
renderSlot as r,
withScopedSlot as w,
stringifyStyle as s,
setupDevtoolsPlugin,
} from './helpers'
export {
camelize as c,
extend as e,
hyphenate as h,
normalizeClass as n,
toDisplayString as t,
} from '@vue/shared'
export * from './helpers'
// @ts-ignore
export * from 'vue'
......@@ -6,15 +6,20 @@ import { CliOptions } from '.'
import { build, buildSSR } from './build'
import { createServer, createSSRServer } from './server'
import { initEnv } from './utils'
import { initEasycom } from '../utils/easycom'
export async function runDev(options: CliOptions & ServerOptions) {
extend(options, { watch: true, minify: false })
initEnv('dev', options)
try {
if (options.platform === 'h5') {
await (options.ssr ? createSSRServer(options) : createServer(options))
const server = await (options.ssr
? createSSRServer(options)
: createServer(options))
initEasycom(server.watcher)
} else {
const watcher = (await build(options)) as RollupWatcher
initEasycom()
let isFirstStart = true
let isFirstEnd = true
watcher.on('event', (event) => {
......
......@@ -5,6 +5,7 @@ import {
createLogger,
createServer as createViteServer,
ServerOptions,
ViteDevServer,
} from 'vite'
import express from 'express'
import { printHttpServerUrls } from 'vite'
......@@ -34,9 +35,12 @@ export async function createServer(options: CliOptions & ServerOptions) {
)
server.printUrls()
return server
}
export async function createSSRServer(options: CliOptions & ServerOptions) {
export async function createSSRServer(
options: CliOptions & ServerOptions
): Promise<ViteDevServer> {
const app = express()
/**
* @type {import('vite').ViteDevServer}
......@@ -112,7 +116,7 @@ export async function createSSRServer(options: CliOptions & ServerOptions) {
return new Promise((resolve, reject) => {
const onSuccess = () => {
printHttpServerUrls(server, vite.config)
resolve(server)
resolve(vite)
}
const onError = (e: Error & { code?: string }) => {
if (e.code === 'EADDRINUSE') {
......
......@@ -55,6 +55,9 @@ export function initEnv(type: 'dev' | 'build', options: CliOptions) {
? path.resolve(process.env.UNI_HBUILDERX_PLUGINS!, 'uniapp-cli-vite')
: process.cwd()
if (options.platform === 'app-plus') {
options.platform = 'app'
}
process.env.UNI_PLATFORM = options.platform as UniApp.PLATFORM
process.env.VITE_ROOT_DIR = process.env.UNI_INPUT_DIR || process.cwd()
......
......@@ -6,7 +6,7 @@ import { VitePluginUniResolvedOptions } from '..'
export function createBuild(
options: VitePluginUniResolvedOptions
): UserConfig['build'] {
initEasycomsOnce(options.inputDir, options.platform)
const {} = initEasycomsOnce(options.inputDir, options.platform)
return {
chunkSizeWarningLimit: 100000000,
rollupOptions: {
......
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '..'
import { serveEasycom } from './easycom'
import { serveStatic } from './static'
export function createConfigureServer(
options: VitePluginUniResolvedOptions
): Plugin['configureServer'] {
return function (server) {
options.devServer = server
serveEasycom(server, options)
return () => {
serveStatic(server, options)
}
}
}
......@@ -14,7 +14,6 @@ import {
import { createConfig } from './config'
import { createConfigResolved } from './configResolved'
import { createConfigureServer } from './configureServer'
import { uniCopyPlugin } from './plugins/copy'
import { initExtraPlugins, initPluginUniOptions } from './utils'
import {
......@@ -109,7 +108,6 @@ export default function uniPlugin(
config: createConfig(options, uniPlugins),
// resolveId: createResolveId(options),
configResolved: createConfigResolved(options),
configureServer: createConfigureServer(options),
})
plugins.push(...uniPlugins)
......
import debug from 'debug'
import { ViteDevServer } from 'vite'
import type { FSWatcher } from 'chokidar'
import { debounce } from '@dcloudio/uni-shared'
import { initEasycomsOnce } from '@dcloudio/uni-cli-shared'
import { VitePluginUniResolvedOptions } from '..'
import { chokidar, initEasycomsOnce } from '@dcloudio/uni-cli-shared'
const debugEasycom = debug('vite:uni:easycom')
export const serveEasycom = (
server: ViteDevServer,
options: VitePluginUniResolvedOptions
) => {
const { filter, refresh } = initEasycomsOnce(
options.inputDir,
options.platform
export const initEasycom = (watcher?: FSWatcher) => {
const { filter, refresh, options } = initEasycomsOnce(
process.env.UNI_INPUT_DIR,
process.env.UNI_PLATFORM
)
if (!watcher) {
// build 模式,手动初始化 watcher
debugEasycom('initWatch', options.dirs!)
watcher = chokidar.watch(options.dirs!, {
ignored: ['**/node_modules/**', '**/.git/**'],
ignoreInitial: true,
ignorePermissionErrors: true,
disableGlobbing: true,
})
}
const refreshEasycom = debounce(refresh, 100)
server.watcher.on('all', (eventName, path) => {
watcher.on('all', (eventName, path) => {
if (!['add', 'unlink'].includes(eventName)) {
return
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册