WangShuXian6 / blog

FE-BLOG
https://wangshuxian6.github.io/blog/
MIT License
45 stars 10 forks source link

Vite #127

Open WangShuXian6 opened 2 years ago

WangShuXian6 commented 2 years ago

Vite

https://cn.vitejs.dev/ 前端开发与构建工具

WangShuXian6 commented 2 years ago

初始化 Vite 项目

直接创建

使用 NPM:

$ npm init vite@latest

使用 Yarn:

$ yarn create vite

使用 PNPM:

$ pnpm create vite

指定项目名称和模板

https://github.com/vitejs/vite/tree/main/packages/create-vite

# npm 6.x
npm init vite@latest my-vue-app --template vue

# npm 7+, 需要额外的双横线:
npm init vite@latest my-vue-app -- --template vue

# yarn
yarn create vite my-vue-app --template vue

# pnpm
pnpm create vite my-vue-app -- --template vue

模版列表

vanilla,vanilla-ts,vue,vue-ts,react,react-ts,preact,preact-ts,lit,lit-ts,svelte,svelte-ts

WangShuXian6 commented 2 years ago

vite issues

vite 支持optional Chaining(可选链判断运算符 ?.)和 nullishCoalescingOperator (空值合并运算符 ??)

安装依赖


yarn add @babel/plugin-proposal-optional-chaining --dev

yarn add @babel/plugin-proposal-nullish-coalescing-operator -dev


>`vite.config.ts` 添加配置
```ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import checker from "vite-plugin-checker";
import vitePluginImp from "vite-plugin-imp";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  return {
    plugins: [
      react({
        babel: {
          plugins: [
            "@babel/plugin-proposal-optional-chaining",
            "@babel/plugin-proposal-nullish-coalescing-operator",
          ],
        },
      }),
    ],
  };
});

vue 请使用 @vitejs/plugin-vue [未测试]

WangShuXian6 commented 1 month ago

Vite 中使用 Jquery

方式

安装

npm i jquery -S
npm i @rollup/plugin-inject @types/jquery -D

配置 vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import { resolve } from "path";
import inject from "@rollup/plugin-inject";

function pathResolve(dir: string) {
  return resolve(__dirname, ".", dir);
}
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    inject({
      // => that should be first under plugins array
      $: "jquery",
      jQuery: "jquery",
    }),
  ],
  resolve: {
    alias: [
      {
        find: /^~/,
        replacement: pathResolve("node_modules") + "/",
      },
      {
        find: /@\//,
        replacement: pathResolve("src") + "/",
      },
    ],
  },
  define: {
    //"window.jQuery": "jquery",
    //"window.$": "jquery",
  },
});

类型 src\vite-env.d.ts

/// <reference types="vite/client" />

import 'jquery';

declare global {
  interface Window {
    $: typeof $;
    test_jquery: () => void;
  }
}

使用Jquery

index.html


<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root">
</div>
<div id="test-jquery"></div>

<script type="module" src="/src/main.tsx"></script>


>`src\App.tsx`
```tsx
import { useEffect, useRef } from "react";
import "./App.css";
import $ from "jquery";

function App() {
  const appRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    window.$ = $;

    window.test_jquery = function () {
      $("#test-jquery").html("jQuery works!");
    };

    window.test_jquery();

    if (!appRef.current) return;
    $(appRef.current).html("jQuery works! ref");
  }, []);
  return (
    <>
      <div className="app-wrapper" ref={appRef}></div>
    </>
  );
}

export default App;

图片

WangShuXian6 commented 3 weeks ago

Vite 导入 xml 文件 ,Vite xml plugin

xml 插件

import fs from 'fs';
import path from 'path';

/**
 * Vite 插件:导入 XML 文件为字符串
 */
export default function xmlPlugin() {
  return {
    name: 'xml-plugin', // 插件名称
    transform(code: any, id: string) {
      if (id.endsWith('.xml')) {
        const xmlContent = fs.readFileSync(path.resolve(__dirname, id), 'utf-8');
        return `export default ${JSON.stringify(xmlContent)}`;
      }
    }
  }
}

使用插件

``

import { defineConfig } from 'vite'
...
import XMLLoader from './xml' 

...
export default defineConfig({
  plugins: [
    ...
    XMLLoader(),
  ],
  assetsInclude: ['**/*.xml'],
})

定义xml文件类型

src\vite-env.d.ts 增加

  declare module '*.xml' {
    const content: string;
    export default content;
  }

导入xml文件

导入后为xml原始字符串,不做转换

import templateXml from './template1.xml'
WangShuXian6 commented 2 days ago

编译

忽略lint校验


  "scripts": {
    "build": "tsc --noEmit && vite build",
  }