从0到1系列---Vite-Vue3-TS-Electron-Prettier-Eslint基本环境配置

从0到1系列---Vite-Vue3-TS-Electron-Prettier-Eslint基本环境配置

前言

说明

目标

仅有的一点废话

正式开始

vscode 安装插件

Vite 创建项目&安装所有依赖

// 建立项目,依次输入项目名称、选择Vue和TypeScript
npm create vite@latest

// 非常重要:安装下面所有依赖,我把项目中用到的都列出来了,如果你不需要某个依赖,可以自行删除
cnpm i -D electron prettier nodemon eslint vite-plugin-eslint @babel/core @babel/eslint-parser @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-prettier eslint-config-prettier eslint-plugin-vue

配置 Prettier

// .prettierignore
node_modules
.vscode
.idea
dist
/public
.eslintrc.js

// .prettierrc
{
    "arrowParens": "always",
    "bracketSameLine": false,
    "bracketSpacing": false,
    "embeddedLanguageFormatting": "auto",
    "htmlWhitespaceSensitivity": "css",
    "insertPragma": false,
    "jsxSingleQuote": false,
    "printWidth": 80,
    "proseWrap": "preserve",
    "quoteProps": "as-needed",
    "requirePragma": false,
    "semi": false,
    "singleQuote": true,
    "tabWidth": 2,
    "trailingComma": "es5",
    "useTabs": false,
    "vueIndentScriptAndStyle": false
}

修改 vite.config.ts

import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite";
import eslintPlugin from "vite-plugin-eslint";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    eslintPlugin({
      include: ["src/**/*.ts", "src/**/*.vue", "src/*.ts", "src/*.vue"],
    }),
  ],
  resolve: {
    // 配置路径别名
    alias: {
      "@": "/src",
    },
  },
});

配置 Eslint

// .eslintignore
node_modules.vscode.idea;
dist / public.eslintrc.js;

// .eslintrc.cjs
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  parser: "vue-eslint-parser",
  extends: [
    "eslint:recommended",
    "plugin:vue/vue3-essential",
    "plugin:prettier/recommended",
    "plugin:@typescript-eslint/recommended",
  ],
  overrides: [],
  parserOptions: {
    ecmaVersion: "latest",
    parser: "@typescript-eslint/parser",
  },
  plugins: ["vue", "@typescript-eslint"],
  rules: {
    "@typescript-eslint/no-var-requires": "off", // 关闭ts中使用const导入模块的时候错误提示
  },
};

配置 electron

// package.json
"main": "main.ts",
"scripts": {
    "start": "nodemon --exec electron . --watch ./ --ext .js,.ts,.vue,.html,.css,.json"
  },
const path = require("node:path");
const { app, BrowserWindow } = require("electron");

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 定义预加载的js
      preload: path.join(__dirname, "./preload/index.ts"),
    },
  });

  win.loadURL("http://localhost:5173/");
}

app.whenReady().then(() => {
  createWindow();
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

运行测试

npm run dev // 启动vue.因为electron从localhost:5173读取页面,所以要先启动vue
npm start // 启动electron