当前位置: 首页 > news >正文

怎么用cms做网站斗牛网站开发

怎么用cms做网站,斗牛网站开发,做app网站的软件有哪些内容吗,免费做网站空间[Vite]vite-plugin-react和vite-plugin-react-swc插件原理了解 共同的作用 JSX 支持#xff1a;插件为 React 应用程序中的 JSX 语法提供支持#xff0c;确保它可以被正确地转换为 JavaScript。Fast Refresh#xff1a;提供热更新功能#xff0c;当应用程序在开发服务器上…[Vite]vite-plugin-react和vite-plugin-react-swc插件原理了解 共同的作用 JSX 支持插件为 React 应用程序中的 JSX 语法提供支持确保它可以被正确地转换为 JavaScript。Fast Refresh提供热更新功能当应用程序在开发服务器上运行时可以快速地看到更改的效果而不需要手动刷新页面。装饰器支持如果项目中使用了 TypeScript 装饰器插件会正确处理它们。Source Maps生成源代码映射以便于在浏览器中调试源代码。Virtual DOM 的导入确保 React 和 ReactDOM 的虚拟 DOM 导入被正确处理。开发模式与生产模式的区分在开发模式下插件会提供更多的辅助功能如 React 快速刷新而在生产模式下它会专注于代码的最小化和优化。ESLint 集成可选地集成 ESLint以在开发过程中提供代码质量和一致性的检查。配置 Rollup在构建过程中插件可能会配置 Rollup 以适应 React 应用程序的特定需求。兼容性确保 React 应用程序可以在目标浏览器中运行即使这些浏览器不支持最新的 JavaScript 特性。自定义配置允许用户通过 Vite 配置文件传递自定义选项给插件例如指定 JSX 工厂函数或模式等。 vite-plugin-react 源码地址 https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/src/index.ts 逻辑解读 类型导入代码开始部分导入了 TypeScript 类型用于确保插件的类型正确性。依赖懒加载loadBabel 函数用于按需加载 Babel因为 Babel 只在开发模式下或当特定的插件被使用时才需要。配置选项Options 接口定义了插件的配置选项允许用户自定义包括 include、exclude、jsxImportSource、jsxRuntime 等。插件数组导出viteReact 函数返回一个插件数组这些插件在 Vite 构建过程中执行不同的任务。创建 Babel 插件配置viteBabel 插件对象配置了如何使用 Babel 来转换 React 代码包括 JSX 支持和快速刷新。React 快速刷新viteReactRefresh 插件对象处理与 React 快速刷新相关的逻辑包括在 index.html 中注入必要的脚本。构建配置在 config 函数中插件可以修改 Vite 配置例如设置 esbuild 选项或 optimizeDeps。配置解析configResolved 函数在 Vite 配置解析完成后调用用于确定是否处于生产模式、项目根路径等。转换函数transform 函数是 Vite 插件中的核心用于实际的代码转换工作。它使用 Babel 来转换 JSX 语法并在开发模式下添加 React 快速刷新的包装器。快速刷新逻辑根据配置和代码内容插件决定是否需要对代码进行快速刷新包装。Babel 插件加载loadPlugin 函数用于加载 Babel 插件确保插件的异步加载。Babel 选项创建createBabelOptions 函数用于创建 Babel 的选项对象它可以从用户配置或默认值中初始化。编译器检测hasCompiler 和 hasCompilerWithDefaultRuntime 函数用于检测 Babel 插件列表中是否包含特定的编译器插件。构建时警告处理silenceUseClientWarning 函数用于抑制 Rollup 的某些警告。静态资源服务resolveId 和 load 函数用于处理静态资源的请求例如 React 快速刷新运行时脚本。转换 HTMLtransformIndexHtml 函数用于修改 index.html注入快速刷新的脚本。插件 APIViteReactPluginApi 类型定义了插件可以提供的 API允许其他插件通过 reactBabel 钩子来修改 Babel 配置。默认导出最后viteReact 函数作为默认导出使其可以在 Vite 配置中使用。 总结来说vitejs/plugin-react 插件的主要功能是为 React 应用程序提供 Vite 构建和开发服务器的集成支持。它包括 JSX 语法的转换、React 组件的快速刷新热更新、以及对 React 运行时的配置。通过插件的配置选项用户可以根据项目需求定制化插件的行为。 // eslint-disable-next-line import/no-duplicates import type * as babelCore from babel/core // eslint-disable-next-line import/no-duplicates import type { ParserOptions, TransformOptions } from babel/core import { createFilter } from vite import type {BuildOptions,Plugin,PluginOption,ResolvedConfig,UserConfig, } from vite import {addClassComponentRefreshWrapper,addRefreshWrapper,preambleCode,runtimeCode,runtimePublicPath, } from ./fast-refresh// lazy load babel since its not used during build if plugins are not used let babel: typeof babelCore | undefined async function loadBabel() {if (!babel) {babel await import(babel/core)}return babel }export interface Options {include?: string | RegExp | Arraystring | RegExpexclude?: string | RegExp | Arraystring | RegExp/*** Control where the JSX factory is imported from.* https://esbuild.github.io/api/#jsx-import-source* default react*/jsxImportSource?: string/*** Note: Skipping React import with classic runtime is not supported from v4* default automatic*/jsxRuntime?: classic | automatic/*** Babel configuration applied in both dev and prod.*/babel?:| BabelOptions| ((id: string, options: { ssr?: boolean }) BabelOptions) }export type BabelOptions OmitTransformOptions,| ast| filename| root| sourceFileName| sourceMaps| inputSourceMap /*** The object type used by the options passed to plugins with* an api.reactBabel method.*/ export interface ReactBabelOptions extends BabelOptions {plugins: ExtractBabelOptions[plugins], any[]presets: ExtractBabelOptions[presets], any[]overrides: ExtractBabelOptions[overrides], any[]parserOpts: ParserOptions {plugins: ExtractParserOptions[plugins], any[]} }type ReactBabelHook (babelConfig: ReactBabelOptions,context: ReactBabelHookContext,config: ResolvedConfig, ) voidtype ReactBabelHookContext { ssr: boolean; id: string }export type ViteReactPluginApi {/*** Manipulate the Babel options of vitejs/plugin-react*/reactBabel?: ReactBabelHook }const reactCompRE /extends\s(?:React\.)?(?:Pure)?Component/ const refreshContentRE /\$Refresh(?:Reg|Sig)\$\(/ const defaultIncludeRE /\.[tj]sx?$/ const tsRE /\.tsx?$/export default function viteReact(opts: Options {}): PluginOption[] {// Provide default values for Rollup compat.let devBase /const filter createFilter(opts.include ?? defaultIncludeRE, opts.exclude)const jsxImportSource opts.jsxImportSource ?? reactconst jsxImportRuntime ${jsxImportSource}/jsx-runtimeconst jsxImportDevRuntime ${jsxImportSource}/jsx-dev-runtimelet isProduction truelet projectRoot process.cwd()let skipFastRefresh falselet runPluginOverrides:| ((options: ReactBabelOptions, context: ReactBabelHookContext) void)| undefinedlet staticBabelOptions: ReactBabelOptions | undefined// Support patterns like:// - import * as React from react;// - import React from react;// - import React, {useEffect} from react;const importReactRE /\bimport\s(?:\*\sas\s)?React\b/const viteBabel: Plugin {name: vite:react-babel,enforce: pre,config() {if (opts.jsxRuntime classic) {return {esbuild: {jsx: transform,},}} else {return {esbuild: {jsx: automatic,jsxImportSource: opts.jsxImportSource,},optimizeDeps: { esbuildOptions: { jsx: automatic } },}}},configResolved(config) {devBase config.baseprojectRoot config.rootisProduction config.isProductionskipFastRefresh isProduction ||config.command build ||config.server.hmr falseif (jsxPure in opts) {config.logger.warnOnce([vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly.,)}const hooks: ReactBabelHook[] config.plugins.map((plugin) plugin.api?.reactBabel).filter(defined)if (hooks.length 0) {runPluginOverrides (babelOptions, context) {hooks.forEach((hook) hook(babelOptions, context, config))}} else if (typeof opts.babel ! function) {// Because hooks and the callback option can mutate the Babel options// we only create static option in this case and re-create them// each time otherwisestaticBabelOptions createBabelOptions(opts.babel)}},async transform(code, id, options) {if (id.includes(/node_modules/)) returnconst [filepath] id.split(?)if (!filter(filepath)) returnconst ssr options?.ssr trueconst babelOptions (() {if (staticBabelOptions) return staticBabelOptionsconst newBabelOptions createBabelOptions(typeof opts.babel function? opts.babel(id, { ssr }): opts.babel,)runPluginOverrides?.(newBabelOptions, { id, ssr })return newBabelOptions})()const plugins [...babelOptions.plugins]const isJSX filepath.endsWith(x)const useFastRefresh !skipFastRefresh !ssr (isJSX ||(opts.jsxRuntime classic? importReactRE.test(code): code.includes(jsxImportDevRuntime) ||code.includes(jsxImportRuntime)))if (useFastRefresh) {plugins.push([await loadPlugin(react-refresh/babel),{ skipEnvCheck: true },])}if (opts.jsxRuntime classic isJSX) {if (!isProduction) {// These development plugins are only needed for the classic runtime.plugins.push(await loadPlugin(babel/plugin-transform-react-jsx-self),await loadPlugin(babel/plugin-transform-react-jsx-source),)}}// Avoid parsing if no special transformation is neededif (!plugins.length !babelOptions.presets.length !babelOptions.configFile !babelOptions.babelrc) {return}const parserPlugins [...babelOptions.parserOpts.plugins]if (!filepath.endsWith(.ts)) {parserPlugins.push(jsx)}if (tsRE.test(filepath)) {parserPlugins.push(typescript)}const babel await loadBabel()const result await babel.transformAsync(code, {...babelOptions,root: projectRoot,filename: id,sourceFileName: filepath,// Required for esbuild.jsxDev to provide correct line numbers// This crates issues the react compiler because the re-order is too important// People should use babel/plugin-transform-react-jsx-development to get back good line numbersretainLines: hasCompiler(plugins)? false: !isProduction isJSX opts.jsxRuntime ! classic,parserOpts: {...babelOptions.parserOpts,sourceType: module,allowAwaitOutsideFunction: true,plugins: parserPlugins,},generatorOpts: {...babelOptions.generatorOpts,decoratorsBeforeExport: true,},plugins,sourceMaps: true,})if (result) {let code result.code!if (useFastRefresh) {if (refreshContentRE.test(code)) {code addRefreshWrapper(code, id)} else if (reactCompRE.test(code)) {code addClassComponentRefreshWrapper(code, id)}}return { code, map: result.map }}},}// We cant add react-dom because the dependency is react-dom/client// for React 18 while its react-dom for React 17. Wed need to detect// what React version the user has installed.const dependencies [react, jsxImportDevRuntime, jsxImportRuntime]const staticBabelPlugins typeof opts.babel object ? opts.babel?.plugins ?? [] : []if (hasCompilerWithDefaultRuntime(staticBabelPlugins)) {dependencies.push(react/compiler-runtime)}const viteReactRefresh: Plugin {name: vite:react-refresh,enforce: pre,config: (userConfig) ({build: silenceUseClientWarning(userConfig),optimizeDeps: {include: dependencies,},resolve: {dedupe: [react, react-dom],},}),resolveId(id) {if (id runtimePublicPath) {return id}},load(id) {if (id runtimePublicPath) {return runtimeCode}},transformIndexHtml() {if (!skipFastRefresh)return [{tag: script,attrs: { type: module },children: preambleCode.replace(__BASE__, devBase),},]},}return [viteBabel, viteReactRefresh] }viteReact.preambleCode preambleCodeconst silenceUseClientWarning (userConfig: UserConfig): BuildOptions ({rollupOptions: {onwarn(warning, defaultHandler) {if (warning.code MODULE_LEVEL_DIRECTIVE warning.message.includes(use client)) {return}if (userConfig.build?.rollupOptions?.onwarn) {userConfig.build.rollupOptions.onwarn(warning, defaultHandler)} else {defaultHandler(warning)}},}, })const loadedPlugin new Mapstring, any() function loadPlugin(path: string): any {const cached loadedPlugin.get(path)if (cached) return cachedconst promise import(path).then((module) {const value module.default || moduleloadedPlugin.set(path, value)return value})loadedPlugin.set(path, promise)return promise }function createBabelOptions(rawOptions?: BabelOptions) {const babelOptions {babelrc: false,configFile: false,...rawOptions,} as ReactBabelOptionsbabelOptions.plugins || []babelOptions.presets || []babelOptions.overrides || []babelOptions.parserOpts || {} as anybabelOptions.parserOpts.plugins || []return babelOptions }function definedT(value: T | undefined): value is T {return value ! undefined }function hasCompiler(plugins: ReactBabelOptions[plugins]) {return plugins.some((p) p babel-plugin-react-compiler ||(Array.isArray(p) p[0] babel-plugin-react-compiler),) }// https://gist.github.com/poteto/37c076bf112a07ba39d0e5f0645fec43 function hasCompilerWithDefaultRuntime(plugins: ReactBabelOptions[plugins]) {return plugins.some((p) p babel-plugin-react-compiler ||(Array.isArray(p) p[0] babel-plugin-react-compiler p[1]?.runtimeModule undefined),) }vite-plugin-react-swc 官方地址vite-plugin-react-swc 核心它使用SWC来替代Babel进行打包速度快了很多。 源码地址 https://github.com/vitejs/vite-plugin-react-swc/blob/main/src/index.ts 逻辑解读 导入依赖代码开始部分导入了 Node.js 的内置模块和第三方库如 fs、path、url 等以及 swc/core 和 Vite 的类型定义。定义插件选项Options 类型定义了插件的配置选项包括 jsxImportSource、tsDecorators、plugins、devTarget 和 parserConfig。react 函数这是一个工厂函数用于创建 Vite 插件数组。它接受用户配置并返回配置好的插件对象。处理 HMR代码检查了服务器是否启用了热模块替换HMR如果没有启用则设置 hmrDisabled 标志。创建插件对象 对象 vite:react-swc:resolve-runtime 用于解析 React 刷新运行时的路径并提供相应的代码。对象 vite:react-swc 包含了多个属性和方法用于处理开发服务器上的特定行为如 config、configResolved、transformIndexHtml 和 transform。 React 快速刷新在 transform 方法中插件会检查代码是否包含 React 组件或刷新相关的代码。如果是它将修改代码以支持 React 快速刷新。Source Map 处理对于支持快速刷新的代码插件会修改 Source Map以确保源代码映射正确。构建时的配置当插件应用于构建时它会配置 SWC 以使用特定的目标和插件选项进行代码转换。transformWithOptions 函数这是一个异步函数用于执行实际的代码转换。它接受文件 ID、代码、目标、选项和 React 配置然后调用 SWC 的 transform 方法。silenceUseClientWarning 函数这个函数用于抑制 Rollup 的警告特别是与 use client 相关的警告。导出默认最后react 函数作为默认导出使其可以在 Vite 配置中使用。 import { readFileSync } from fs; import { dirname, join } from path; import { fileURLToPath } from url; import { SourceMapPayload } from module; import {Output,ParserConfig,ReactConfig,JscTarget,transform, } from swc/core; import { PluginOption, UserConfig, BuildOptions } from vite; import { createRequire } from module;const runtimePublicPath /react-refresh;const preambleCode import { injectIntoGlobalHook } from __PATH__; injectIntoGlobalHook(window); window.$RefreshReg$ () {}; window.$RefreshSig$ () (type) type;;const _dirname typeof __dirname ! undefined? __dirname: dirname(fileURLToPath(import.meta.url)); const resolve createRequire(typeof __filename ! undefined ? __filename : import.meta.url, ).resolve; const reactCompRE /extends\s(?:React\.)?(?:Pure)?Component/; const refreshContentRE /\$Refresh(?:Reg|Sig)\$\(/;type Options {/*** Control where the JSX factory is imported from.* default react*/jsxImportSource?: string;/*** Enable TypeScript decorators. Requires experimentalDecorators in tsconfig.* default false*/tsDecorators?: boolean;/*** Use SWC plugins. Enable SWC at build time.* default undefined*/plugins?: [string, Recordstring, any][];/*** Set the target for SWC in dev. This can avoid to down-transpile private class method for example.* For production target, see https://vitejs.dev/config/build-options.html#build-target* default es2020*/devTarget?: JscTarget;/*** Override the default include list (.ts, .tsx, .mts, .jsx, .mdx).* This requires to redefine the config for any file you want to be included.* If you want to trigger fast refresh on compiled JS, use jsx: true.* Exclusion of node_modules should be handled by the function if needed.*/parserConfig?: (id: string) ParserConfig | undefined; };const isWebContainer globalThis.process?.versions?.webcontainer;const react (_options?: Options): PluginOption[] {let hmrDisabled false;const options {jsxImportSource: _options?.jsxImportSource ?? react,tsDecorators: _options?.tsDecorators,plugins: _options?.plugins? _options?.plugins.map((el): typeof el [resolve(el[0]), el[1]]): undefined,devTarget: _options?.devTarget ?? es2020,parserConfig: _options?.parserConfig,};return [{name: vite:react-swc:resolve-runtime,apply: serve,enforce: pre, // Run before Vite default resolve to avoid syscallsresolveId: (id) (id runtimePublicPath ? id : undefined),load: (id) id runtimePublicPath? readFileSync(join(_dirname, refresh-runtime.js), utf-8): undefined,},{name: vite:react-swc,apply: serve,config: () ({esbuild: false,optimizeDeps: {include: [${options.jsxImportSource}/jsx-dev-runtime],esbuildOptions: { jsx: automatic },},}),configResolved(config) {if (config.server.hmr false) hmrDisabled true;const mdxIndex config.plugins.findIndex((p) p.name mdx-js/rollup,);if (mdxIndex ! -1 mdxIndex config.plugins.findIndex((p) p.name vite:react-swc)) {throw new Error([vite:react-swc] The MDX plugin should be placed before this plugin,);}if (isWebContainer) {config.logger.warn([vite:react-swc] SWC is currently not supported in WebContainers. You can use the default React plugin instead.,);}},transformIndexHtml: (_, config) [{tag: script,attrs: { type: module },children: preambleCode.replace(__PATH__,config.server!.config.base runtimePublicPath.slice(1),),},],async transform(code, _id, transformOptions) {const id _id.split(?)[0];const refresh !transformOptions?.ssr !hmrDisabled;const result await transformWithOptions(id,code,options.devTarget,options,{refresh,development: true,runtime: automatic,importSource: options.jsxImportSource,},);if (!result) return;if (!refresh) return result;const hasRefresh refreshContentRE.test(result.code);if (!hasRefresh !reactCompRE.test(result.code)) return result;const sourceMap: SourceMapPayload JSON.parse(result.map!);sourceMap.mappings ;; sourceMap.mappings;result.code import * as RefreshRuntime from ${runtimePublicPath};${result.code};if (hasRefresh) {sourceMap.mappings ;;;;;; sourceMap.mappings;result.code if (!window.$RefreshReg$) throw new Error(React refresh preamble was not loaded. Something is wrong.); const prevRefreshReg window.$RefreshReg$; const prevRefreshSig window.$RefreshSig$; window.$RefreshReg$ RefreshRuntime.getRefreshReg(${id}); window.$RefreshSig$ RefreshRuntime.createSignatureFunctionForTransform;${result.code}window.$RefreshReg$ prevRefreshReg; window.$RefreshSig$ prevRefreshSig; ;}result.code RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) {RefreshRuntime.registerExportsForReactRefresh(${id}, currentExports);import.meta.hot.accept((nextExports) {if (!nextExports) return;const invalidateMessage RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${id}, currentExports, nextExports);if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);}); }); ;return { code: result.code, map: sourceMap };},},options.plugins? {name: vite:react-swc,apply: build,enforce: pre, // Run before esbuildconfig: (userConfig) ({build: silenceUseClientWarning(userConfig),}),transform: (code, _id) transformWithOptions(_id.split(?)[0], code, esnext, options, {runtime: automatic,importSource: options.jsxImportSource,}),}: {name: vite:react-swc,apply: build,config: (userConfig) ({build: silenceUseClientWarning(userConfig),esbuild: {jsx: automatic,jsxImportSource: options.jsxImportSource,tsconfigRaw: {compilerOptions: { useDefineForClassFields: true },},},}),},]; };const transformWithOptions async (id: string,code: string,target: JscTarget,options: Options,reactConfig: ReactConfig, ) {const decorators options?.tsDecorators ?? false;const parser: ParserConfig | undefined options.parserConfig? options.parserConfig(id): id.endsWith(.tsx)? { syntax: typescript, tsx: true, decorators }: id.endsWith(.ts) || id.endsWith(.mts)? { syntax: typescript, tsx: false, decorators }: id.endsWith(.jsx)? { syntax: ecmascript, jsx: true }: id.endsWith(.mdx)? // JSX is required to trigger fast refresh transformations, even if MDX already transforms it{ syntax: ecmascript, jsx: true }: undefined;if (!parser) return;let result: Output;try {result await transform(code, {filename: id,swcrc: false,configFile: false,sourceMaps: true,jsc: {target,parser,experimental: { plugins: options.plugins },transform: {useDefineForClassFields: true,react: reactConfig,},},});} catch (e: any) {const message: string e.message;const fileStartIndex message.indexOf(╭─[);if (fileStartIndex ! -1) {const match message.slice(fileStartIndex).match(/:(\d):(\d)]/);if (match) {e.line match[1];e.column match[2];}}throw e;}return result; };const silenceUseClientWarning (userConfig: UserConfig): BuildOptions ({rollupOptions: {onwarn(warning, defaultHandler) {if (warning.code MODULE_LEVEL_DIRECTIVE warning.message.includes(use client)) {return;}if (userConfig.build?.rollupOptions?.onwarn) {userConfig.build.rollupOptions.onwarn(warning, defaultHandler);} else {defaultHandler(warning);}},}, });export default react;
http://www.hkea.cn/news/14285453/

相关文章:

  • 商城开发网站网站建设招聘要求
  • 湖南建设厅网站二建注销社交电商怎么入手
  • 互助平台网站建设怎么给客户谈做网站
  • 济宁网站开发招聘安徽合肥做网站的公司有哪些
  • 南阳网站建设报价怎么搭建一个视频网站
  • 怎么编辑自己的网站我想投资谁有项目
  • 网站设计总结与心得体会珠珠宝宝网网站站建建设设
  • 网站优化名词解释番禺网站建设公司
  • 甘肃县门户网站建设方案oa系统建设方案
  • 如何验证网站分析网站建设的体会
  • 《c程序设计》精品课程网站建设专业企专业企业网站设计
  • 保险网站建设的总体目标哪些官网用wordpress
  • 织梦建网站东莞市房管局官方网站
  • 贵州省建设厅的网站首页网页制作三剑客即
  • 那个做图网站叫什么Wordpress图床对接阿里云
  • 网站开发大概需要多少钱做虚拟网站要花多少钱
  • 做网站需要的语言网上投诉平台
  • 网站建设和网络推广外包网站怎么免费建站
  • 怎样提高网站的排名做网站要在vs安装什么
  • 怎么开个网站两学一做网站登录
  • 软件上传到那个网站做宣传网站建设带主机
  • 光电网站设计wordpress实现同步登录
  • 做淘宝客网站需要什么要求建站宝盒小程序
  • 网站运营方案怎么写?什么是销售型网站
  • 广州网站营销优化开发校园网站设计毕业设计
  • 网站被跳转怎么办公司网站购物平台建设
  • 搜阅网站建设国家建设免费论文网站
  • 网教网站源码建设银行网站怎么预约纪念币
  • 家居企业网站建设平台推广软件是什么工作
  • 企业网站建设前期准备08系统iis信息管理器怎么建设网站