前端工程化各种常用配置文件总结(vite.config.js)

747 阅读5分钟

vite.config.js

注释版本

import { defineConfig } from "vite";
import { resolve } from "path"; // node中用来合并路径模块
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue()], // 配置需要使用的插件列表
  base: "./", // 在生产中服务时的基本公共路径
  publicDir: "public", // 静态资源服务的文件夹, 默认"public"
  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"), // 这里是将src目录配置别名为 @ 方便在项目中导入src目录下的文件
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        charset: false, // 关闭编译时 字符编码 报错问题
        javascriptEnabled: true,
        additionalData: `@import "${path.resolve(
          __dirname,
          "src/assets/css/var.scss"
        )}";`,
      },
    },
  },
  json: {
    //是否支持从 .json 文件中进行按名导入
    namedExports: true,
    //若设置为 true 导入的json会被转为 export default JSON.parse("..") 会比转译成对象字面量性能更好
    stringify: false,
  },
  //继承自 esbuild 转换选项,最常见的用例是自定义 JSX
  esbuild: {
    jsxFactory: "h",
    jsxFragment: "Fragment",
    jsxInject: `import Vue from 'vue'`,
  },
  // 打包配置
  build: {
    target: "modules", // 设置最终构建的浏览器兼容目标。modules:支持原生 ES 模块的浏览器
    outDir: "dist", // 指定输出路径
    assetsDir: "assets", // 指定生成静态资源的存放路径
    assetsInlineLimit: "4096", // 小于此阈值的导入或引用资源将内联为base64编码,设置为0可禁用此项。默认4096(4kb)
    cssCodeSplit: true, // 启用/禁用CSS代码拆分,如果禁用,整个项目的所有CSS将被提取到一个CSS文件中,默认true
    sourcemap: false, // 构建后是否生成 source map 文件
    minify: "terser", // 混淆器,terser构建后文件体积更小
    write: true, // 设置为 false 来禁用将构建后的文件写入磁盘
    emptyOutDir: true, // 默认情况下,若 outDir 在 root 目录下,则 Vite 会在构建时清空该目录。
    brotliSize: true, // 启用/禁用 brotli 压缩大小报告
    chunkSizeWarningLimit: 500, // chunk 大小警告的限制
    terserOptions: {
      // 去除 console debugger
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
  },
  server: {
    // 本地运行配置,及反向代理配置
    host: "127.0.0.1", // 指定服务器主机名
    port: 5173, // 指定服务器端口
    open: "/publick/index.html", // 在服务器启动时自动在浏览器中打开应用程序 值为文本/布尔
    strictPort: false, // 设为 false 时,若端口已被占用则会尝试下一个可用端口,而不是直接退出
    https: false, // 是否开启 https
    cors: true, // 为开发服务器配置 CORS。默认启用并允许任何源
    header: {}, // 指定服务器响应的 header ,类型OutgoingHttpHeaders
    hmr: {}, // 禁用或配置 HMR 连接
    watch: {}, // 传递给 chokidar 的文件系统监视器选项
    middlewareMode: "ssr", // 中间件模式创建 Vite 服务器,'ssr' | 'html'
    base: "", // HTTP请求中预留此文件夹,用于代理 Vite 作为子文件夹时使用。
    fs: {
      strict: true, // 限制为工作区 root 路径以外的文件的访问
      allow: [
        // 限制哪些文件可以通过 /@fs/ 路径提供服务
        searchForWorkspaceRoot(process.cwd()), // 搜索工作区的根目录
        "/path/to/custom/allow", // 自定义规则
      ],
      deny: [".env", ".env.*", "*.{pem,crt}"], // 限制Vite开发服务器提供敏感文件的黑名单
    },
    origin: "http://127.0.0.1:8080", // 定义开发调试阶段生成资产的url
    proxy: {
      // 开启代理配置
      "/foo": "http://127.0.0.1:4567", // 字符串简写写法
      "/api": {
        // 选项写法
        target: "http://127.0.0.1:4567",
        changeOrigin: true,
        rewrite: (path) => {
          path = path.replace(/^\/api/, "");
          // 进行调试输出
          console.log('vite proxy url: ',path);
          return path;
        },
      },
      "^/*.*m3u8*": {
        // ^开头使用正则表达式
        target: "http://127.0.0.1:4567",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path,
      },
      "/api": {
        target: "http://jsonplaceholder.typicode.com",
        changeOrigin: true,
        configure: (proxy, options) => {
          // 配置 proxy 是 'http-proxy' 的实例
        },
      },
      "/socket.io": {
        // 配置 websockets or socket.io
        target: "ws://localhost:3000",
        ws: true,
      },
    },
  },
  preview: {
    // 预览服务器
    host: "localhost",
    port: "5173",
    strictPort: true, // 设为 true 时若端口已被占用则会直接退出,false尝试下一个可用端口
    https: "", // https.createServer()配置项
    open: "/docs/index.html", // 服务器启动时自动在浏览器中打开应用程序。
    cors: {}, // 配置 CORS
    proxy: {
      // 自定义代理规则
      "/foo": "http://localhost:4567", // 字符串简写写法
      "/api": {
        // 选项写法
        target: "http://jsonplaceholder.typicode.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  optimizeDeps: {
    // 依赖优化选项
    entries: [], // 检测需要预构建的依赖项
    exclude: ["jquery"], // 预构建中强制排除的依赖项
    include: [], //默认情况下,不在 node_modules 中的,链接的包不会被预构建。使用此选项可强制预构建链接的包。
    esbuildOptions: {}, // 部署扫描和优化过程中传递给EsBuild
    force: true, // 设置为 true 可以强制依赖预构建,而忽略之前已经缓存过的、已经优化过的依赖
    disabled: 'build', // 禁用依赖优化
  },
  ssr: {
    // SSR 选项
    external: [], // 列出的是要为 SSR 强制外部化的依赖
    noExternal: [], // 列出的是防止被 SSR 外部化依赖项。
    target: "node", // SSR 服务器的构建目标
    format: "esm", // SSR 服务器的构建语法格式 'esm' | 'cjs'
  },
  worker: {
    format: "iife", // worker 打包时的输出类型 'es' | 'iife'
    plugins: [], // worker 打包的 Vite 插件
    rollupOptions: {}, // 打包 worker 的 Rollup 配置项
  },
});

无注释版本

import { defineConfig } from "vite";
import { resolve } from "path";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
  plugins: [vue()],
  base: "./",
  publicDir: "public",
  resolve: {
    alias: {
      "@": resolve(__dirname, "./src"),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        charset: false,
        javascriptEnabled: true,
        additionalData: `@import "${path.resolve(
          __dirname,
          "src/assets/css/var.scss"
        )}";`,
      },
    },
  },
  json: {
    namedExports: true,
    stringify: false,
  },

  esbuild: {
    jsxFactory: "h",
    jsxFragment: "Fragment",
    jsxInject: `import Vue from 'vue'`,
  },

  build: {
    target: "modules",
    outDir: "dist",
    assetsDir: "assets",
    assetsInlineLimit: "4096",
    cssCodeSplit: true,
    sourcemap: false,
    minify: "terser",
    write: true,
    emptyOutDir: true,
    brotliSize: true,
    chunkSizeWarningLimit: 500,
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
  },
  server: {
    host: "127.0.0.1",
    port: 5173,
    open: "/publick/index.html",
    strictPort: false,
    https: false,
    cors: true,
    header: {},
    hmr: {},
    watch: {},
    middlewareMode: "ssr",
    base: "",
    fs: {
      strict: true,
      allow: [searchForWorkspaceRoot(process.cwd()), "/path/to/custom/allow"],
      deny: [".env", ".env.*", "*.{pem,crt}"],
    },
    origin: "http://127.0.0.1:8080",
    proxy: {
      "/foo": "http://127.0.0.1:4567",
      "/api": {
        target: "http://j127.0.0.1:4567",
        changeOrigin: true,
        rewrite: (path) => {
          path.replace(/^\/api/, "");
          console.log(path);
          return path;
        },
      },
      "^/*.*m3u8*": {
        target: "http://127.0.0.1:4567",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path,
      },
      "/api": {
        target: "http://jsonplaceholder.typicode.com",
        changeOrigin: true,
        configure: (proxy, options) => {},
      },
      "/socket.io": {
        target: "ws://localhost:3000",
        ws: true,
      },
    },
  },
  preview: {
    host: "localhost",
    port: "5173",
    strictPort: true,
    https: "",
    open: "/docs/index.html",
    cors: {},
    proxy: {
      "/foo": "http://localhost:4567",
      "/api": {
        target: "http://jsonplaceholder.typicode.com",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
  },
  optimizeDeps: {
    entries: [],
    exclude: ["jquery"],
    include: [],
    esbuildOptions: {},
    force: true,
    disabled: "build",
  },
  ssr: {
    external: [],
    noExternal: [],
    target: "node",
    format: "esm",
  },
  worker: {
    format: "iife",
    plugins: [],
    rollupOptions: {},
  },
});

webpack.config.js

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
    clean: true, // 自动将上次打包目录资源清空
  },
  module: {
    rules: [
      {
        // 用来匹配 .css 结尾的文件
        test: /\.css$/,
        // use 数组里面 Loader 执行顺序是从右到左
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"],
      },
      {
        test: /\.s[ac]ss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.styl$/,
        use: ["style-loader", "css-loader", "stylus-loader"],
      },
      {
        test: /\.(png|jpe?g|gif|webp)$/,
        type: "asset",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 小于10kb的图片会被base64处理
          },
        },
        generator: {
          // 将图片文件输出到 static/imgs 目录中
          // 将图片文件命名 [hash:8][ext][query]
          // [hash:8]: hash值取8位
          // [ext]: 使用之前的文件扩展名
          // [query]: 添加之前的query参数
          filename: "static/imgs/[hash:8][ext][query]",
        },
      },
      {
        test: /\.(ttf|woff2?)$/,
        type: "asset/resource",
        generator: {
          filename: "static/media/[hash:8][ext][query]",
        },
      },
      {
        test: /\.js$/,
        exclude: /node_modules/, // 排除node_modules代码不编译
        loader: "babel-loader",
      },
    ],
  },
  plugins: [
    new ESLintWebpackPlugin({
      // 指定检查文件的根目录
      context: path.resolve(__dirname, "src"),
    }),
    new HtmlWebpackPlugin({
      // 以 public/index.html 为模板创建文件
      // 新的html文件有两个特点:1. 内容和源文件一致 2. 自动引入打包生成的js等资源
      template: path.resolve(__dirname, "public/index.html"),
    }),
  ],
  // 开发服务器
  devServer: {
    host: "localhost", // 启动服务器域名
    port: "3000", // 启动服务器端口号
    open: true, // 是否自动打开浏览器
    proxy: { // 配置代理重写规则 
    '/api': { // 将 /api 开头的请求重写到另一个服务器或端口,例如:http://localhost:4000/api/some-endpoint 
    target: 'http://localhost:4000', // 目标服务器地址和端口 
    changeOrigin: true, // 改变请求源,避免跨域问题 
    pathRewrite: function (path, req) { 
        const newPath = path.replace('/api', '/base/api')
        console.log(newPath) // 调试输出
        return  newPath
    }
    },
  },
  mode: "development",
};

babel.config.js

module.exports = {  
  presets: [  
    [  
      '@babel/preset-env',  
      {  
        targets: {  
          browsers: ['last 2 versions', 'ie >= 11']  
        },  
        useBuiltIns: 'usage',  
        corejs: 3.8 // 根据你使用的 CoreJS 版本进行调整  
      }  
    ]  
  ],  
  plugins: [  
    '@babel/plugin-transform-runtime',  
    '@babel/plugin-proposal-class-properties'  
  ]  
};

tsconfig.json

{
  "compilerOptions": {
    // 目标代码(ts -> js(es5/6/7))
    "target": "esnext",
    // 目标代码需要使用的模块化方案(commonjs require/module.exports/es module import/export)
    "module": "esnext",
    // 严格一些严格的检查(any)
    "strict": true,
    // 对jsx进行怎么样的处理
    "jsx": "preserve",
    // 辅助的导入功能
    "importHelpers": true,
    // 按照node的方式去解析模块 import "/index.node"
    "moduleResolution": "node",
    // 跳过一些库的类型检测 (axios -> 类型/ lodash -> @types/lodash / 其他的第三方)
    // import { Person } from 'axios'
    "skipLibCheck": true,
    // export default/module.exports = {}
    // es module 和 commonjs
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    // 要不要生成映射文件(ts -> js)
    "sourceMap": true,
    // 文件路径在解析时, 基本url
    "baseUrl": ".",
    // 指定具体要解析使用的类型
    "types": ["element-plus/global"],
    // 路径解析(类似于webpack alias)
    "paths": {
      "@/*": ["./src/*"],
      "components/*": ["./src/components/*"]
    },
    // 可以指定在项目中可以使用哪里库的类型(Proxy/Window/Document)
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": [
    // "src/**/*.ts",
    // "src/**/*.tsx",
    "./src/**/*.vue"
  ],
  "exclude": ["./node_modules"]
}

.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@vue/prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ],
  parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off'
  }
}

.prettierrc

注释版

{  
  "singleQuote": true,  // 是否使用单引号,默认为 false
  "semi": true,  // 是否在语句末尾添加分号,默认为 true
  "trailingComma": "all",  // 否在对象或数组的最后一个元素后面添加逗号,默认为 none。可选值:none、es5、all
  "printWidth": 120, // 一行代码的最大宽度,默认为 80
  "tabWidth": 2,  // 缩进的空格数,默认为 2
  "useTabs": false,  // 是否使用制表符作为缩进,默认为 false
  "bracketSpacing": true,  // 对象字面量的括号之间是否添加空格,默认为 true
  "jsxBracketSameLine": false,  // 多行 JSX 元素的最后一行的右尖括号是否放在最后一行的结尾,默认为 false
  "arrowParens": "avoid",  // 只有一个参数的箭头函数的参数是否使用圆括号,默认为 avoid。可选值:avoid、always
  "rangeStart": 0,  // 指定格式化的代码范围开始行,默认为 0
  "rangeEnd": null,  // 指定格式化的代码范围结束行,可以不写 默认为 Infinity(或null)
  "requirePragma": false,  // 是否只格式化带有特定注释的文件,默认为 false
  "insertPragma": false,  // 是否在文件开头插入特定的注释,默认为 false
  "proseWrap": "preserve",  // 如何处理 prose(文本块),默认为 preserve。可选值:always、never、preserve
  "htmlWhitespaceSensitivity": "css",  // 如何处理 HTML 文件中的空格,默认为 css。可选值:css、strict、ignore
  "vueIndentScriptAndStyle": false,  // Vue 文件中是否对 `<script>` 和 `<style>` 标签进行缩进,默认为 false
  "endOfLine": "auto"  // 换行符的样式,默认为 auto。可选值:auto、lf、crlf
}

无注释版

{  
  "singleQuote": true,  
  "semi": true,  
  "trailingComma": "all",  
  "printWidth": 120,  
  "tabWidth": 2,  
  "useTabs": false,  
  "bracketSpacing": true,  
  "jsxBracketSameLine": false,  
  "arrowParens": "avoid",  
  "rangeStart": 0,  
  "rangeEnd": null,  
  "requirePragma": false,  
  "insertPragma": false,  
  "proseWrap": "preserve",  
  "htmlWhitespaceSensitivity": "css",  
  "vueIndentScriptAndStyle": false,  
  "endOfLine": "auto"  
}

package.json

{ 
    "name": "项目名称", 
    "version": "1.0.0", 
    "description": "项目描述", 
    "main": "index.js",
    "keywords": ["关键字1", "关键字2", "关键字3"], 
    "repository": { 
        "type": "git", 
        "url": "https://example.com/project.git"
    }, 
    "license": "MIT", 
    "author": "作者名称", 
    "contributors": [ 
        { "name": "贡献者1", "email": "贡献者1邮箱" }, 
        { "name": "贡献者2", "email": "贡献者2邮箱" } 
    ], 
    "dependencies": { 
        "模块1": "^1.0.0", 
        "模块2": "~2.0.0" 
    }, 
    "devDependencies": { 
        "模块3": "^3.0.0", 
        "模块4": "~4.0.0" 
    }, 
    "scripts": { 
        "start": "node index.js", 
        "test": "mocha test.js"
    },  
    "engines": { 
        "node": ">=12.0.0" 
    } 
}

.gitignore

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
/package-lock.json

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

jsconfig.json

  • 用来解决在vscode中webpack,vite,vue,react项目中alias别名@路径不能跳转的问题
  • 项目根目录下添加jsconfig.json文件,添加后重启vscode
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "target": "ES6",
    "allowSyntheticDefaultImports": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}