vite+ts项目知识点笔记(上)

简介: fs-extra是fs的一个扩展,提供了非常多的便利API,并且继承了fs所有方法和为fs方法添加了promise的支持。

1.依赖项



fs-extra


fs-extra是fs的一个扩展,提供了非常多的便利API,并且继承了fs所有方法和为fs方法添加了promise的支持。

npm install fs-extra -S


vite-plugin-compression


vite-plugin-compress的增强版,压缩用的。

npm i vite-plugin-compression


vite-plugin-html


一个为index.html提供minify和基于EJS模板功能的Vite插件。

npm i vite-plugin-html -D


vite-plugin-imagemin


用于图片压缩。

npm i vite-plugin-imagemin


vite-plugin-mock


vite 的数据模拟插件,是基于 vite.js 开发的。 并同时支持本地环境和生产环境。 Connect 服务中间件在本地使用,mockjs 在生产环境中使用。

npm i vite-plugin-mock -D


vite-plugin-pwa

PWA一些技术集成。

`npm i vite-plugin-pwa`


vite-plugin-style-import


按需加载组件样式.

npm i vite-plugin-theme


vite-plugin-theme


可以选任意主题色切换的,并且不需要实时编译的后台服务.

npm i vite-plugin-svg-icons -D


vite-plugin-svg-icons


用于生成svg精灵图。 特征 预加载项目运行时会生成所有图标,并且只需要操作一次dom。 高性能的内置缓存,只有在修改文件后才会重新生成。

npm i vite-plugin-svg-icons -D


rollup-plugin-visualizer

可视化并分析构建包,查看哪些模块占用空间大小,以此来优化构建包的大小。

npm i rollup-plugin-visualizer


2.参数类



导出类定义

export const primaryColor = '#0960bd';
export const darkMode = 'light';
//使用
export function getThemeColors(color?: string) {
  const tc = color || primaryColor;
  const lightColors = generateAntColors(tc);
  const primary = lightColors[5];
  const modeColors = generateAntColors(primary, 'dark');
  return [...lightColors, ...modeColors];
}


不定参数

type Fn = (...arg: any) => any;
export interface GenerateColorsParams {
  mixLighten: Fn;
  mixDarken: Fn;
  tinycolor: any;
  color?: string;
}
export function generateColors({
  color = primaryColor,
  mixLighten,
  mixDarken,
  tinycolor,
}: GenerateColorsParams) {}


3.Model类定义基础


Model

export interface BasicPageParams {
  page: number;
  pageSize: number;
}
export interface BasicFetchResult<T extends any> {
  items: T[];
  total: number;
}

Attachment

// 引入基础包
import { BasicPageParams, BasicFetchResult } from '/@/api/model/baseModel';
// 定义查询参数
export type AttachmentVO = BasicPageParams & {
  keyword?: string;
  startDate?: string;
  endDate?: string;
};
// 定义路由对象
export interface Attachment {
  id: string;
  storageId: string;
  attachmentGroupId: string;
  name: string;
  size: string;
  url: string;
  fileName: string;
  thumbUrl: string;
  type: number;
  createTime: string;
}
// 根据字典对象生成响应模型
export type AttachmentDTO = BasicFetchResult<AttachmentVO>;
export interface ContextMenuProps {
  event?: MouseEvent;
  styles?: any;
  items: ContextMenuItem[];
  customEvent?: MouseEvent;
  axis?: Axis;
  width?: number;
  showIcon?: boolean;
}
export interface ItemContentProps {
  showIcon: boolean | undefined;
  item: ContextMenuItem;
  handler: Fn;
}
export interface DropMenu {
  onClick?: Fn;
  to?: string;
  icon?: string;
  event: string | number;
  text: string;
  disabled?: boolean;
  divider?: boolean;
}


4 Vue3.0知识点



process.cwd()

process.cwd()


5 其他



fs.readJSON


import fs from 'fs-extra';
const raw = await fs.readJSON(path.join(dir, 'collections.json'));

readJson() 方法读取一个 JSON 对象,然后将其解析为一个对象。


ensureDir()


ensureDir()函数确保目录用户正在请求的目录存在。如果目录结构不存在,该函数将自行创建结构。 mkdirs()和mkdirp()是该函数的其他名称,这意味着我们可以使用它们代替ensureDir(),一切都会按原样进行。

fs.ensureDir(dir,options,callback)
// OR
fs.mkdirs(dir,options,callback)
// OR
fs.mkdirp(dir,options,callback)
const { iconSet, output, useType } = answers;
const outputDir = path.resolve(process.cwd(), output);
fs.ensureDir(outputDir);


fs.writeFileSync同步写入内容



fs.writeFileSync()方法用于将数据同步写入文件。如果该文件已经存在,则替换该文件。 “ options”参数可用于修改方法的函数。

fs.writeFileSync( file, data, options )
await fs.writeFileSync(
    path.join(output, `icons.data.ts`),
    `export default ${isLocal ? JSON.stringify(icons) : JSON.stringify({ prefix, icons })}`);


6.代码片段



const collections = Object.entries(raw).map(([id, v]) => ({
    ...(v as any),
    id,
}));
const primaryColorObj: Record<string, string> = {};
return plugin as unknown as Plugin[];
import { MockMethod } from 'vite-plugin-mock';
export default [
  {
    url: '/basic-api/account/getAccountInfo',
    timeout: 1000,
    method: 'get',
    response: () => {
      return resultSuccess(userInfo);
    },
  }
] as MockMethod[];
const result = {
    list: [] as any[],
  };
const result: any[] = [];
const result = {
    list: [] as Recordable[],
};
const children: Recordable[] = [];
let menu: Object[];

import.meta.globEager

const modules = import.meta.globEager('./**/*.ts');

enum

enum Api {
  // The address does not exist
  Error = '/error',
}
const selectedKeys = ref<string[]>([]);
helpMessage: {
   type: [String, Array] as PropType<string | string[]>,
   default: '',
},
onClick: { type: Function as PropType<(...args) => any>, default: null },
export declare type ButtonProps = Partial<ExtractPropTypes<typeof buttonProps>>;
import { onClickOutside } from '@vueuse/core';
const wrap = ref<ElRef>(null);
import type { ButtonProps } from 'ant-design-vue/lib/button/buttonTypes';
import type { CSSProperties, VNodeChild, ComputedRef } from 'vue';
import type { ScrollContainerOptions } from '/@/components/Container/index';
export interface DrawerInstance {
  setDrawerProps: (props: Partial<DrawerProps> | boolean) => void;
  emitVisible?: (visible: boolean, uid: number) => void;
}
export interface ReturnMethods extends DrawerInstance {
  openDrawer: <T = any>(visible?: boolean, data?: T, openOnSet?: boolean) => void;
  closeDrawer: () => void;
  getVisible?: ComputedRef<boolean>;
}
\
export type RegisterFn = (drawerInstance: DrawerInstance, uuid?: string) => void;
\
export interface ReturnInnerMethods extends DrawerInstance {
  closeDrawer: () => void;
  changeLoading: (loading: boolean) => void;
  changeOkLoading: (loading: boolean) => void;
  getVisible?: ComputedRef<boolean>;
}
\
export type UseDrawerReturnType = [RegisterFn, ReturnMethods];
\
export type UseDrawerInnerReturnType = [RegisterFn, ReturnInnerMethods];
\
export interface DrawerFooterProps {
  showOkBtn: boolean;
  showCancelBtn: boolean;
  /**
   * Text of the Cancel button
   * @default 'cancel'
   * @type string
   */
  cancelText: string;
  /**
   * Text of the OK button
   * @default 'OK'
   * @type string
   */
  okText: string;
\
  /**
   * Button type of the OK button
   * @default 'primary'
   * @type string
   */
  okType: 'primary' | 'danger' | 'dashed' | 'ghost' | 'default';
  /**
   * The ok button props, follow jsx rules
   * @type object
   */
  okButtonProps: { props: ButtonProps; on: {} };
\
  /**
   * The cancel button props, follow jsx rules
   * @type object
   */
  cancelButtonProps: { props: ButtonProps; on: {} };
  /**
   * Whether to apply loading visual effect for OK button or not
   * @default false
   * @type boolean
   */
  confirmLoading: boolean;
\
  showFooter: boolean;
  footerHeight: string | number;
}
export interface DrawerProps extends DrawerFooterProps {
  isDetail?: boolean;
  loading?: boolean;
  showDetailBack?: boolean;
  visible?: boolean;
  /**
   * Built-in ScrollContainer component configuration
   * @type ScrollContainerOptions
   */
  scrollOptions?: ScrollContainerOptions;
  closeFunc?: () => Promise<any>;
  triggerWindowResize?: boolean;
  /**
   * Whether a close (x) button is visible on top right of the Drawer dialog or not.
   * @default true
   * @type boolean
   */
  closable?: boolean;
\
  /**
   * Whether to unmount child components on closing drawer or not.
   * @default false
   * @type boolean
   */
  destroyOnClose?: boolean;
\
  /**
   * Return the mounted node for Drawer.
   * @default 'body'
   * @type any ( HTMLElement| () => HTMLElement | string)
   */
  getContainer?: () => HTMLElement | string;
\
  /**
   * Whether to show mask or not.
   * @default true
   * @type boolean
   */
  mask?: boolean;
\
  /**
   * Clicking on the mask (area outside the Drawer) to close the Drawer or not.
   * @default true
   * @type boolean
   */
  maskClosable?: boolean;
\
  /**
   * Style for Drawer's mask element.
   * @default {}
   * @type object
   */
  maskStyle?: CSSProperties;
\
  /**
   * The title for Drawer.
   * @type any (string | slot)
   */
  title?: VNodeChild | JSX.Element;
\
  /**
   * The class name of the container of the Drawer dialog.
   * @type string
   */
  wrapClassName?: string;
\
  /**
   * Style of wrapper element which **contains mask** compare to `drawerStyle`
   * @type object
   */
  wrapStyle?: CSSProperties;
\
  /**
   * Style of the popup layer element
   * @type object
   */
  drawerStyle?: CSSProperties;
\
  /**
   * Style of floating layer, typically used for adjusting its position.
   * @type object
   */
  bodyStyle?: CSSProperties;
  headerStyle?: CSSProperties;
\
  /**
   * Width of the Drawer dialog.
   * @default 256
   * @type string | number
   */
  width?: string | number;
\
  /**
   * placement is top or bottom, height of the Drawer dialog.
   * @type string | number
   */
  height?: string | number;
\
  /**
   * The z-index of the Drawer.
   * @default 1000
   * @type number
   */
  zIndex?: number;
\
  /**
   * The placement of the Drawer.
   * @default 'right'
   * @type string
   */
  placement?: 'top' | 'right' | 'bottom' | 'left';
  afterVisibleChange?: (visible?: boolean) => void;
  keyboard?: boolean;
  /**
   * Specify a callback that will be called when a user clicks mask, close button or Cancel button.
   */
  onClose?: (e?: Event) => void;
}
export interface DrawerActionType {
  scrollBottom: () => void;
  scrollTo: (to: number) => void;
  getScrollWrap: () => Element | null;
}
const props = {
    value: { type: [Object, String] as PropType<Record<string, any> | string> },
    mode: { type: String, default: MODE.JSON },
    readonly: { type: Boolean },
};
helpMessage: {
   type: [Array, String] as PropType<string[] | string>,
   default: '',
},
viewport: {
      type: (typeof window !== 'undefined' ? window.HTMLElement : Object) as PropType<HTMLElement>,
      default: () => null,
},
interface State {
    isInit: boolean;
    loading: boolean;
    intersectionObserverInstance: IntersectionObserver | null;
}
const state = reactive<State>({
    isInit: false,
    loading: false,
    intersectionObserverInstance: null,
});
const scrollbarRef = ref<Nullable<ScrollbarType>>(null);
export type ScrollActionType = RefType<{
  scrollBottom: () => void;
  getScrollWrap: () => Nullable<HTMLElement>;
  scrollTo: (top: number) => void;
}>;
import type { FunctionalComponent, CSSProperties } from 'vue';
const props = {
    width: { type: Number, default: 156 },
    customEvent: { type: Object as PropType<Event>, default: null },
    styles: { type: Object as PropType<CSSProperties> },
    showIcon: { type: Boolean, default: true },
    axis: {
      // The position of the right mouse button click
      type: Object as PropType<Axis>,
      default() {
        return { x: 0, y: 0 };
      },
    },
    items: {
      // The most important list, if not, will not be displayed
      type: Array as PropType<ContextMenuItem[]>,
      default() {
        return [];
      },
    },
  };
const wrapRef = ref<ElRef>(null);
function handleAction(item: ContextMenuItem, e: MouseEvent) {
        const { handler, disabled } = item;
        if (disabled) {
          return;
        }
        showRef.value = false;
        e?.stopPropagation();
        e?.preventDefault();
        handler?.();
}
const props = {
    value: { type: [Object, Number, String, Array] },
    count: { type: Number, default: 60 },
    beforeStartFunc: {
      type: Function as PropType<() => Promise<boolean>>,
      default: null,
    },
  };
const props = {
    value: { type: String },
    size: { type: String, validator: (v) => ['default', 'large', 'small'].includes(v) },
    count: { type: Number, default: 60 },
    sendCodeApi: {
      type: Function as PropType<() => Promise<boolean>>,
      default: null,
    },
  };
type apiFunParams = { file: Blob; name: string; filename: string };
const props = {
    circled: { type: Boolean, default: true },
    uploadApi: {
      type: Function as PropType<(params: apiFunParams) => Promise<any>>,
    },
};
const props = {
    src: { type: String, required: true },
    alt: { type: String },
    circled: { type: Boolean, default: false },
    realTimePreview: { type: Boolean, default: true },
    height: { type: [String, Number], default: '360px' },
    crossorigin: {
      type: String as PropType<'' | 'anonymous' | 'use-credentials' | undefined>,
      default: undefined,
    },
    imageStyle: { type: Object as PropType<CSSProperties>, default: () => ({}) },
    options: { type: Object as PropType<Options>, default: () => ({}) },
  };
const imgElRef = ref<ElRef<HTMLImageElement>>();
const cropper = ref<Nullable<Cropper>>();
const getImageStyle = computed((): CSSProperties => {
        return {
          height: props.height,
          maxWidth: '100%',
          ...props.imageStyle,
        };
});
const getWrapperStyle = computed((): CSSProperties => {
        return { height: `${props.height}`.replace(/px/, '') + 'px' };
 });
const props = {
    width: { type: [String, Number], default: '200px' },
    value: { type: String },
    showBtn: { type: Boolean, default: true },
    btnProps: { type: Object as PropType<ButtonProps> },
    btnText: { type: String, default: '' },
    uploadApi: { type: Function as PropType<({ file: Blob, name: string }) => Promise<void>> },
};
const getImageWrapperStyle = computed(
        (): CSSProperties => ({ width: unref(getWidth), height: unref(getWidth) })
);
const props = {
    useCollapse: { type: Boolean, default: true },
    title: { type: String, default: '' },
    size: {
      type: String,
      validator: (v) => ['small', 'default', 'middle', undefined].includes(v),
      default: 'small',
    },
    bordered: { type: Boolean, default: true },
    column: {
      type: [Number, Object] as PropType<number | Recordable>,
      default: () => {
        return { xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 };
      },
    },
    collapseOptions: {
      type: Object as PropType<CollapseContainerOptions>,
      default: null,
    },
    schema: {
      type: Array as PropType<DescItem[]>,
      default: () => [],
    },
    data: { type: Object },
  };
const instance = getCurrentInstance();
instance && emit('register', drawerInstance, instance.uid);
const dataTransferRef = reactive<any>({});
const visibleData = reactive<{ [key: number]: boolean }>({});
const loaded = ref<Nullable<boolean>>(false);
const uid = ref<string>('');
api: {
   type: Function as PropType<(arg?: Recordable) => Promise<OptionsItem[]>>,
   default: null,
},
export type EventType = Event & MouseEvent & TouchEvent;
type DocumentHandler = <T extends MouseEvent>(mouseup: T, mousedown: T) => void;
type FlushList = Map<
  HTMLElement,
  {
    documentHandler: DocumentHandler;
    bindingFn: (...args: unknown[]) => unknown;
  }
>;
const nodeList: FlushList = new Map();
let startClick: MouseEvent;
declare interface Fn<T = any, R = T> {
  (...arg: T[]): R;
}
declare interface PromiseFn<T = any, R = T> {
  (...arg: T[]): Promise<R>;
}
declare type RefType<T> = T | null;
declare type LabelValueOptions = {
  label: string;
  value: any;
  [key: string]: string | number | boolean;
}[];
declare type EmitType = (event: string, ...args: any[]) => void;
declare type TargetContext = '_self' | '_blank';
declare interface ComponentElRef<T extends HTMLElement = HTMLDivElement> {
  $el: T;
}
declare type ComponentRef<T extends HTMLElement = HTMLDivElement> = ComponentElRef<T> | null;
declare type ElRef<T extends HTMLElement = HTMLDivElement> = Nullable<T>;
import type { ComputedRef, Ref } from 'vue';
export type DynamicProps<T> = {
  [P in keyof T]: Ref<T[P]> | T[P] | ComputedRef<T[P]>;
};


7. 文件内容



buildConf.ts

/**
 * Generate additional configuration files when used for packaging. The file can be configured with some global variables, so that it can be changed directly externally without repackaging
 */
import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant';
import fs, { writeFileSync } from 'fs-extra';
import chalk from 'chalk';
import { getRootPath, getEnvConfig } from '../utils';
import { getConfigFileName } from '../getConfigFileName';
import pkg from '../../package.json';
function createConfig(
  {
    configName,
    config,
    configFileName = GLOB_CONFIG_FILE_NAME,
  }: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} }
) {
  try {
    const windowConf = `window.${configName}`;
    // Ensure that the variable will not be modified
    const configStr = `${windowConf}=${JSON.stringify(config)};
      Object.freeze(${windowConf});
      Object.defineProperty(window, "${configName}", {
        configurable: false,
        writable: false,
      });
    `.replace(/\s/g, '');
    fs.mkdirp(getRootPath(OUTPUT_DIR));
    writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr);
    console.log(chalk.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
    console.log(chalk.gray(OUTPUT_DIR + '/' + chalk.green(configFileName)) + '\n');
  } catch (error) {
    console.log(chalk.red('configuration file configuration file failed to package:\n' + error));
  }
}
export function runBuildConfig() {
  const config = getEnvConfig();
  const configFileName = getConfigFileName(config);
  createConfig({ config, configName: configFileName });
}

postBuild.ts

// #!/usr/bin/env node
import { runBuildConfig } from './buildConf';
import chalk from 'chalk';
import pkg from '../../package.json';
export const runBuild = async () => {
  try {
    const argvList = process.argv.splice(2);
    // Generate configuration file
    if (!argvList.includes('disabled-config')) {
      runBuildConfig();
    }
    console.log(`✨ ${chalk.cyan(`[${pkg.name}]`)}` + ' - build successfully!');
  } catch (error) {
    console.log(chalk.red('vite build error:\n' + error));
    process.exit(1);
  }
};
runBuild();
相关文章
|
JavaScript 前端开发 测试技术
[小笔记]TypeScript/JavaScript数组转置
[小笔记]TypeScript/JavaScript数组转置
355 0
|
JavaScript 前端开发 测试技术
[小笔记]TypeScript/JavaScript模拟Python中的Range函数
[小笔记]TypeScript/JavaScript模拟Python中的Range函数
458 0
|
JavaScript 前端开发
TypeScript极速入门笔记1
TypeScript极速入门笔记1
369 4
|
存储 JavaScript 前端开发
深入浅出TypeScript | 青训营笔记
深入浅出TypeScript | 青训营笔记
1005 0
|
JavaScript 前端开发 程序员
typescript入门笔记分享
typescript入门笔记分享
235 0
|
JavaScript Java
TypeScript入门笔记(三):函数
TypeScript入门笔记(三):函数
288 1
|
JavaScript
TypeScript入门笔记(二):数据类型
TypeScript入门笔记(二):数据类型
371 1
|
JavaScript 前端开发 Java
小笔记:如何使用代码注释:关于JavaScript与TypeScript 注释和文档的自动生成
小笔记:如何使用代码注释:关于JavaScript与TypeScript 注释和文档的自动生成
1375 0
|
JavaScript 前端开发 测试技术
[小笔记]TypeScript/JavaScript模拟Python中的zip(不使用map)
[小笔记]TypeScript/JavaScript模拟Python中的zip(不使用map)
317 0
|
存储 JavaScript 前端开发
TypeScript笔记(15)—— 深入理解TypeScript中的装饰器
TypeScript笔记(15)—— 深入理解TypeScript中的装饰器
375 0