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

refactor: load => plugin

上级 a2b13dd4
此差异已折叠。
......@@ -9234,7 +9234,7 @@ function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) {
], 8, ["data-page"]);
}
_sfc_main$2.render = _sfc_render$2;
var index_vue_vue_type_style_index_0_lang$1 = "\n.uni-async-error {\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n top: 0;\r\n bottom: 0;\r\n color: #999;\r\n padding: 100px 0;\r\n text-align: center;\n}\r\n";
var index_vue_vue_type_style_index_0_lang$1 = "\n.uni-async-error {\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n top: 0;\r\n bottom: 0;\r\n color: #999;\r\n padding: 100px 0;\r\n text-align: center;\n}\r\n";
const _sfc_main$1 = {
name: "AsyncError",
methods: {
......@@ -9250,7 +9250,7 @@ function _sfc_render$1(_ctx, _cache, $props, $setup, $data, $options) {
}, " \u8FDE\u63A5\u670D\u52A1\u5668\u8D85\u65F6\uFF0C\u70B9\u51FB\u5C4F\u5E55\u91CD\u8BD5 ");
}
_sfc_main$1.render = _sfc_render$1;
var index_vue_vue_type_style_index_0_lang = "\n.uni-async-loading {\n box-sizing: border-box;\r\n width: 100%;\r\n padding: 50px;\r\n text-align: center;\n}\n.uni-async-loading .uni-loading {\r\n width: 30px;\r\n height: 30px;\n}\r\n";
var index_vue_vue_type_style_index_0_lang = "\n.uni-async-loading {\r\n box-sizing: border-box;\r\n width: 100%;\r\n padding: 50px;\r\n text-align: center;\n}\n.uni-async-loading .uni-loading {\r\n width: 30px;\r\n height: 30px;\n}\r\n";
const _sfc_main = {
name: "AsyncLoading"
};
......
<template>
<div
class="uni-async-error"
@click="_onClick"
>
<div class="uni-async-error" @click="_onClick">
连接服务器超时,点击屏幕重试
</div>
</template>
<style>
.uni-async-error {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
color: #999;
padding: 100px 0;
text-align: center;
}
.uni-async-error {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
color: #999;
padding: 100px 0;
text-align: center;
}
</style>
<script>
export default {
name: 'AsyncError',
methods: {
_onClick () {
_onClick() {
// TODO 临时采用 reload
window.location.reload()
}
}
},
},
}
</script>
......@@ -4,20 +4,20 @@
</div>
</template>
<style>
.uni-async-loading {
box-sizing: border-box;
width: 100%;
padding: 50px;
text-align: center;
}
.uni-async-loading {
box-sizing: border-box;
width: 100%;
padding: 50px;
text-align: center;
}
.uni-async-loading .uni-loading {
width: 30px;
height: 30px;
}
.uni-async-loading .uni-loading {
width: 30px;
height: 30px;
}
</style>
<script>
export default {
name: 'AsyncLoading'
name: 'AsyncLoading',
}
</script>
</script>
......@@ -36,5 +36,8 @@
},
"devDependencies": {
"@types/sass": "^1.16.0"
},
"uni-app": {
"compilerVersion": "3.1.2"
}
}
......@@ -13,6 +13,8 @@ export function createConfig(
): Plugin['config'] {
return () => {
return {
root: options.root,
base: options.base,
define: createDefine(options),
resolve: createResolve(options),
optimizeDeps: createOptimizeDeps(options),
......
import path from 'path'
import slash from 'slash'
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '../..'
export function uniAppVuePlugin(options: VitePluginUniResolvedOptions): Plugin {
const appVuePath = slash(path.resolve(options.inputDir, 'App.vue'))
return {
name: 'vite:uni-app-vue',
transform(code, id) {
if (id === appVuePath) {
return {
code: `<template><VUniApp ref="app"/></template><style src="@dcloudio/uni-h5/style/base.css"/>${code}`,
map: this.getCombinedSourcemap(),
}
}
},
}
}
......@@ -7,6 +7,12 @@ import { uniJsonPlugin } from './json'
import { uniPreCssPlugin } from './preCss'
import { uniEasycomPlugin } from './easycom'
import { InjectOptions, uniInjectPlugin } from './inject'
import { uniAppVuePlugin } from './appVue'
import { uniMainJsPlugin } from './mainJs'
import { uniPagesJsonPlugin } from './pagesJson'
import { uniManifestJsonPlugin } from './manifestJson'
const debugPlugin = debug('uni:plugin')
export interface UniPluginFilterOptions extends VitePluginUniResolvedOptions {
......@@ -64,6 +70,11 @@ export function resolvePlugins(
0,
'pre'
)
addPlugin(plugins, uniAppVuePlugin(options), 1, 'pre')
addPlugin(plugins, uniMainJsPlugin(options), 1, 'pre')
addPlugin(plugins, uniPagesJsonPlugin(options), 1, 'pre')
addPlugin(plugins, uniManifestJsonPlugin(options), 1, 'pre')
addPlugin(
plugins,
uniPreCssPlugin(Object.assign(uniPreCssPluginOptions, options)),
......
......@@ -6,11 +6,16 @@ import { VitePluginUniResolvedOptions } from '../..'
export function uniJsonPlugin(options: VitePluginUniResolvedOptions): Plugin {
const pagesJsonPath = slash(path.resolve(options.inputDir, 'pages.json'))
const pagesJsonJsPath = pagesJsonPath + '.js'
const manifestJsonPath = slash(
path.resolve(options.inputDir, 'manifest.json')
)
return {
name: 'vite:uni-json',
transform(code, id) {
if (id.startsWith(pagesJsonPath) && !id.startsWith(pagesJsonJsPath)) {
if (
(id.startsWith(pagesJsonPath) || id.startsWith(manifestJsonPath)) &&
!id.endsWith('.json.js')
) {
code = JSON.stringify(parse(code))
}
return code
......
import path from 'path'
import slash from 'slash'
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '../..'
export function uniMainJsPlugin(options: VitePluginUniResolvedOptions): Plugin {
const mainPath = slash(path.resolve(options.inputDir, 'main'))
const mainJsPath = mainPath + '.js'
const mainTsPath = mainPath + '.ts'
const pagesJsonJsPath = slash(path.resolve(options.inputDir, 'pages.json.js'))
return {
name: 'vite:uni-main-js',
transform(code, id) {
if (id === mainJsPath || id === mainTsPath) {
return {
code: `import { plugin } from '@dcloudio/uni-h5';import '${pagesJsonJsPath}';function createApp(rootComponent,rootProps){rootComponent && (rootComponent.mpType = 'app');return createVueApp(rootComponent, rootProps).use(plugin)};${code.replace(
'createApp',
'createVueApp'
)}`,
map: this.getCombinedSourcemap(),
}
}
},
}
}
import fs from 'fs'
import path from 'path'
import { parse } from 'jsonc-parser'
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '../..'
import slash from 'slash'
const MANIFEST_JSON_JS = 'manifest.json.js'
const defaultRouter = {
mode: 'hash',
base: '/',
}
const defaultAsync = {
loading: 'AsyncLoading',
error: 'AsyncError',
delay: 200,
timeout: 60000,
suspensible: true,
}
const defaultNetworkTimeout = {
request: 60000,
connectSocket: 60000,
uploadFile: 60000,
downloadFile: 60000,
}
const defaultQQMapKey = 'XVXBZ-NDMC4-JOGUS-XGIEE-QVHDZ-AMFV2'
export function uniManifestJsonPlugin(
options: VitePluginUniResolvedOptions
): Plugin {
const manifestJsonPath = slash(path.join(options.inputDir, 'manifest.json'))
return {
name: 'vite:uni-manifest-json',
resolveId(id) {
if (id.endsWith(MANIFEST_JSON_JS)) {
return manifestJsonPath + '.js'
}
},
transform(code, id) {
if (id.endsWith(MANIFEST_JSON_JS)) {
const manifest = JSON.parse(code)
const { debug, h5 } = manifest
const appid = (manifest.appid || '').replace('__UNI__', '')
const router = { ...defaultRouter, ...((h5 && h5.router) || {}) }
const async = { ...defaultAsync, ...((h5 && h5.async) || {}) }
const networkTimeout = {
...defaultNetworkTimeout,
...(manifest.networkTimeout || {}),
}
const sdkConfigs = (h5 && h5.sdkConfigs) || {}
const qqMapKey =
(sdkConfigs.maps &&
sdkConfigs.maps.qqmap &&
sdkConfigs.maps.qqmap.key) ||
defaultQQMapKey
const flexDirection =
(manifest['app-plus'] &&
manifest['app-plus'].nvue &&
manifest['app-plus'].nvue['flex-direction']) ||
'column'
return {
code: `export const appid = '${appid || ''}'
export const debug = ${!!debug}
export const nvue = ${JSON.stringify({
'flex-direction': flexDirection,
})}
export const networkTimeout = ${JSON.stringify(networkTimeout)}
// h5
export const router = ${JSON.stringify(router)}
export const async = ${JSON.stringify(async)}
export const qqMapKey = '${qqMapKey}'
export const sdkConfigs = ${JSON.stringify(sdkConfigs)}
`,
map: { mappings: '' },
}
}
},
load(id) {
if (id.endsWith(MANIFEST_JSON_JS)) {
return JSON.stringify(parse(fs.readFileSync(manifestJsonPath, 'utf8')))
}
},
}
}
import fs from 'fs'
import path from 'path'
import slash from 'slash'
import { parse } from 'jsonc-parser'
import { Plugin } from 'vite'
import { camelize, capitalize } from '@vue/shared'
import { VitePluginUniResolvedOptions } from '..'
import { VitePluginUniResolvedOptions } from '../..'
const { parseJson } = require('@dcloudio/uni-cli-shared')
const pkg = require('@dcloudio/vite-plugin-uni/package.json')
export const pages = {
test(id: string, _inputDir: string) {
return id.endsWith('pages.json.js')
},
load(filename: string, options: VitePluginUniResolvedOptions) {
return (
(options.devServer ? registerGlobalCode : '') +
parsePagesJson(
fs.readFileSync(filename.substr(0, filename.length - 3), 'utf-8')
)
)
},
const PAGES_JSON_JS = 'pages.json.js'
export function uniPagesJsonPlugin(
options: VitePluginUniResolvedOptions
): Plugin {
const pagesJsonPath = slash(path.join(options.inputDir, 'pages.json'))
return {
name: 'vite:uni-pages-json',
resolveId(id) {
if (id.endsWith(PAGES_JSON_JS)) {
return pagesJsonPath + '.js'
}
},
transform(code, id) {
if (id.endsWith(PAGES_JSON_JS)) {
return {
code:
(options.devServer ? registerGlobalCode : '') +
parsePagesJson(code, options),
map: { mappings: '' },
}
}
},
load(id) {
if (id.endsWith(PAGES_JSON_JS)) {
return JSON.stringify(parse(fs.readFileSync(pagesJsonPath, 'utf8')))
}
},
}
}
interface PageOptions {
......@@ -46,17 +65,24 @@ interface PageRouteOptions {
}
}
function parsePagesJson(jsonStr: string) {
function parsePagesJson(
jsonStr: string,
options: VitePluginUniResolvedOptions
) {
const pagesJson = formatPagesJson(jsonStr)
const definePagesCode = generatePagesDefineCode(pagesJson)
const uniRoutesCode = generateRoutes(pagesJson).join(',')
const uniConfigCode = generateConfig(pagesJson)
const uniRoutesCode = generateRoutes(pagesJson)
const uniConfigCode = generateConfig(pagesJson, options)
const manifestJsonPath = slash(
path.resolve(options.inputDir, 'manifest.json.js')
)
return `
import { defineAsyncComponent, resolveComponent, createVNode, withCtx, openBlock, createBlock } from 'vue'
import { PageComponent } from '@dcloudio/uni-h5'
import { PageComponent, AsyncLoadingComponent, AsyncErrorComponent } from '@dcloudio/uni-h5'
import { appid, debug, networkTimeout, router, async, sdkConfigs, qqMapKey, nvue } from '${manifestJsonPath}'
${uniConfigCode}
${definePagesCode}
window.__uniConfig=${uniConfigCode}
window.__uniRoutes=[${uniRoutesCode}]
${uniRoutesCode}
`
}
......@@ -148,7 +174,14 @@ function formatPageIdentifier(path: string) {
function generatePageDefineCode(pageOptions: PageOptions) {
return `const ${formatPageIdentifier(
pageOptions.path
)} = defineAsyncComponent(() => import('./${pageOptions.path}.vue'))`
)} = defineAsyncComponent({
loader: () => import('./${pageOptions.path}.vue'),
loadingComponent: AsyncLoadingComponent,
errorComponent: AsyncErrorComponent,
delay: async.delay,
timeout: async.timeout,
suspensible: async.suspensible
})`
}
function generatePagesDefineCode(pagesJson: Record<string, any>) {
......@@ -210,16 +243,35 @@ function generatePagesRoute(pagesRouteOptions: PageRouteOptions[]) {
}
function generateRoutes(pagesJson: Record<string, any>) {
return [
return `window.__uniRoutes=[${[
`{ path: '/${pagesJson.pages[0].path}', redirect: '/' }`,
...generatePagesRoute(formatPagesRoute(pagesJson)),
]
].join(',')}]`
}
function generateConfig(pagesJson: Record<string, any>) {
function generateConfig(
pagesJson: Record<string, any>,
options: VitePluginUniResolvedOptions
) {
delete pagesJson.pages
delete pagesJson.subPackages
delete pagesJson.subpackages
pagesJson.router = {} // TODO
return JSON.stringify(pagesJson)
pagesJson.compilerVersion = pkg['uni-app'].compilerVersion
return (
(options.devServer
? ''
: `window['____'+appid+'____']=true
delete window['____'+appid+'____']
`) +
`window.__uniConfig=Object.assign(${JSON.stringify(pagesJson)},{
async,
debug,
networkTimeout,
sdkConfigs,
qqMapKey,
nvue,
router
})
`
)
}
import fs from 'fs'
import path from 'path'
import { parse } from 'jsonc-parser'
import { Plugin, ViteDevServer } from 'vite'
import { initEnv } from './env'
import { createLoad } from './load'
import { createConfig } from './config'
import { createResolveId } from './resolveId'
import { createConfigResolved } from './configResolved'
......@@ -16,6 +17,7 @@ export interface VitePluginUniOptions {
}
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
root: string
base: string
inputDir: string
assetsDir: string
devServer?: ViteDevServer
......@@ -23,14 +25,23 @@ export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
export * from './vue'
function resolveBase(inputDir: string) {
const manifest = parse(
fs.readFileSync(path.join(inputDir, 'manifest.json'), 'utf8')
)
return (manifest.h5 && manifest.h5.router && manifest.h5.router.base) || '/'
}
export default function uniPlugin(
rawOptions: VitePluginUniOptions = {}
): Plugin {
const inputDir = rawOptions.inputDir || path.resolve(process.cwd(), 'src')
const options: VitePluginUniResolvedOptions = {
...rawOptions,
root: process.cwd(),
base: resolveBase(inputDir),
assetsDir: 'assets',
inputDir: rawOptions.inputDir || path.resolve(process.cwd(), 'src'),
inputDir,
}
initEnv(options)
return {
......@@ -39,6 +50,5 @@ export default function uniPlugin(
configResolved: createConfigResolved(options),
configureServer: createConfigureServer(options),
resolveId: createResolveId(options),
load: createLoad(options),
}
}
import fs from 'fs'
import path from 'path'
import slash from 'slash'
import { VitePluginUniResolvedOptions } from '..'
let appVuePath: string
export const app = {
test(id: string, inputDir: string) {
if (!appVuePath) {
appVuePath = slash(path.resolve(inputDir, 'App.vue'))
}
return id === appVuePath
},
load(filename: string, _options: VitePluginUniResolvedOptions) {
return `<template><VUniApp ref="app"/></template><style src="@dcloudio/uni-h5/style/base.css"/>${fs
.readFileSync(filename, 'utf-8')
.toString()}`
},
}
import debug from 'debug'
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '..'
import { app } from './app'
import { main } from './main'
import { pages } from './pages'
const debugLoad = debug('uni:load')
const loads = [app, main, pages]
export function createLoad(
options: VitePluginUniResolvedOptions
): Plugin['load'] {
return (id) => {
const item = loads.find((item) => item.test(id, options.inputDir))
if (item) {
debugLoad(id)
return item.load(id, options)
}
}
}
import fs from 'fs'
import path from 'path'
import slash from 'slash'
import { VitePluginUniResolvedOptions } from '..'
let mainJsPath: string
let mainTsPath: string
let pagesJsPath: string
export const main = {
test(id: string, inputDir: string) {
if (!mainJsPath) {
const mainPath = slash(path.resolve(inputDir, 'main'))
mainJsPath = mainPath + '.js'
mainTsPath = mainPath + '.ts'
}
return id === mainJsPath || id === mainTsPath
},
load(filename: string, options: VitePluginUniResolvedOptions) {
if (!pagesJsPath) {
pagesJsPath = slash(path.resolve(options.inputDir, 'pages.json.js'))
}
return `import { plugin } from '@dcloudio/uni-h5';import '${pagesJsPath}';function createApp(rootComponent,rootProps){rootComponent && (rootComponent.mpType = 'app');return createVueApp(rootComponent, rootProps).use(plugin)};${fs
.readFileSync(filename, 'utf-8')
.toString()
.replace('createApp', 'createVueApp')}`
},
}
import path from 'path'
import debug from 'debug'
import { Plugin } from 'vite'
import { VitePluginUniResolvedOptions } from '.'
......@@ -7,26 +6,13 @@ const debugResolve = debug('uni:resolve')
const VUES = ['vue', 'vue.js', './vue.js', 'dist/vue.runtime.esm-bundler.js']
let pagesJsonJsPath: string
export function createResolveId(
options: VitePluginUniResolvedOptions
): Plugin['resolveId'] {
return function (id) {
if (id.endsWith('pages.json.js')) {
if (!pagesJsonJsPath) {
pagesJsonJsPath = path.resolve(options.inputDir, 'pages.json.js')
}
debugResolve(id)
return pagesJsonJsPath
}
if (VUES.includes(id)) {
debugResolve(id)
return '@dcloudio/uni-h5-vue'
}
// if (id.startsWith('@/')) {
// debugResolve(id)
// return path.join(options.inputDir, id.replace('@/', ''))
// }
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册