vite.config.js 8.29 KB
/*
 * @Date: 2024-08-26 10:12:56
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2024-12-13 10:26:07
 * @FilePath: /hager/vite.config.js
 * @Description: 文件描述
 */
// import vue from '@vitejs/plugin-vue'
import vue from "@vitejs/plugin-vue2";
import legacy from "@vitejs/plugin-legacy";
import dynamicImport from 'vite-plugin-dynamic-import';
import { defineConfig, loadEnv } from 'vite';
import { createProxy } from './build/proxy';
import Components from 'unplugin-vue-components/vite';
import { ElementUiResolver } from 'unplugin-vue-components/resolvers';
import commonjs from 'vite-plugin-commonjs';
import sitemap from 'vite-plugin-sitemap'; // 生成网站的站点地图,以便搜索引擎可以更容易地抓取网站上的页面
import { createHtmlPlugin } from 'vite-plugin-html';

// var path = require('path');
import path from 'path-browserify';
// const fs = require('fs');

const names = [
  '/',
  'product/index',
  'product/detail',
  'solution/index',
  'solution/detail',
  'solution/case',
  'about',
  'about/global',
  'about/china',
  'about/design',
  'about/product',
  'about/development',
  'about/honors',
  'contact',
  'news',
  'news/detail',
  'recruit',
]
const dynamicRoutes = names.map(name => `${name}`)

// https://vitejs.dev/config/
export default ({ command, mode }) => {
const root = process.cwd();

const viteEnv = loadEnv(mode, root);
// let isProd = (command === 'serve'); // 情景配置是否为开发模式 serve 或 build

return defineConfig({
  base: viteEnv.VITE_BASE, // 开发或生产环境服务的公共基础路径。
  plugins: [
    vue(),
    legacy({
      targets: ["android 4", "ios 8", "chrome 52", "ie 11"],
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
      renderLegacyChunks: true,
      polyfills: [
        "es.symbol",
        "es.array.filter",
        "es.promise",
        "es.promise.finally",
        "es/map",
        "es/set",
        "es.array.for-each",
        "es.object.define-properties",
        "es.object.define-property",
        "es.object.get-own-property-descriptor",
        "es.object.get-own-property-descriptors",
        "es.object.keys",
        "es.object.to-string",
        "web.dom-collections.for-each",
        "esnext.global-this",
        "esnext.string.match-all",
      ],
    }),
    dynamicImport(),
    Components({ // 自动按需求引入组件
      resolvers: [ElementUiResolver()],
    }),
    commonjs(), // 将 CommonJS 模块转换为 ES Modules
    sitemap({
      hostname: 'http://www.hager-electric.com/', // 设置网站根 URL
      outDir: 'hager',
      exclude: ['**/user'],
      lastmod: true,
      changefreq: 'daily',
      priority: 0.7,
      ignore: ['**/*.json', '**/*.md'],
      dynamicRoutes,
      generateRobotsTxt: false, // 禁用 robots.txt 生成
      readable: true,
    }),
    createHtmlPlugin({
      minify: false,
      inject: {
        data: {
          sitemapUrl: 'sitemap.xml'
        },
        tags: [
          {
            tag: 'link',
            attrs: {
              rel: 'sitemap',
              type: 'application/xml',
              title: 'Sitemap',
              href: 'sitemap.xml'
            }
          }
        ]
      },
      // 只修改特定的标签,不覆盖其他插件的插入
      transformIndexHtml: (html, ctx) => {
        return html.replace(
          /<link rel="sitemap" type="application\/xml" title="Sitemap" href="\/sitemap\.xml">/,
          `<link rel="sitemap" type="application/xml" title="Sitemap" href="${ctx.data.sitemapUrl}">`
        );
      }
    })
  ],
  publicDir: 'public', // 作为静态资源服务的文件夹。这个目录中的文件会在开发中被服务于 /,在开发模式时,会被拷贝到 outDir 的根目录,并没有转换,永远只是复制到这里。该值可以是文件系统的绝对路径,也可以是相对于项目的根目录路径。
  // cacheDir: '', // 存储缓存文件的目录。此目录下会存储预打包的依赖项或 vite 生成的某些缓存文件,使用缓存可以提高性能。如需重新生成缓存文件,你可以使用 --force 命令行选项或手动删除目录。此选项的值可以是文件的绝对路径,也可以是以项目根目录为基准的相对路径。
  resolve: {
    alias: {
      // 将会被传递到 @rollup/plugin-alias 作为 entries 的选项。也可以是一个对象,或一个 { find, replacement } 的数组. 当使用文件系统路径的别名时,请始终使用绝对路径。相对路径的别名值会被原封不动地使用,因此无法被正常解析。 更高级的自定义解析方法可以通过 插件 实现。
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@composables': path.resolve(__dirname, 'src/composables'),
      '@utils': path.resolve(__dirname, 'src/utils'),
      '@images': path.resolve(__dirname, 'src/assets/images'),
      '@css': path.resolve(__dirname, 'src/assets/css'),
      '@mock': path.resolve(__dirname, 'src/assets/mock'),
      common: path.resolve(__dirname, 'src/common'),
    },
    // dedupe: [''], // 如果你在你的应用程序中有相同依赖的副本(比如 monorepos),使用这个选项来强制 Vite 总是将列出的依赖关系解析到相同的副本(从项目根目录)。
    // conditions: [''], // 在解析包的 情景导出 时允许的附加条件。
    // mainFields: [''], // package.json 中,在解析包的入口点时尝试的字段列表。注意,这比从 exports 字段解析的情景导出优先级低:如果一个入口点从 exports 成功解析,主字段将被忽略。
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'], // 导入时想要省略的扩展名列表。注意,不 建议忽略自定义导入类型的扩展名(例如:.vue),因为它会干扰 IDE 和类型支持。
  },
  css: {
    preprocessorOptions: {
      less: {
        additionalData: `@import "@/styles/variables.less";`, // 自动导入变量文件
      },
    },
  },
  logLevel: 'info', // 调整控制台输出的级别,默认为 'info'。
  // clearScreen: true, // 设为 false 可以避免 Vite 清屏而错过在终端中打印某些关键信息。命令行模式下请通过 --clearScreen false 设置。
  server: {
    host: '0.0.0.0',
    port: viteEnv.VITE_PORT, // 本地服务端口
    // strictPort: true, // 设为true时若端口已被占用则会直接退出, 而不是尝试下一个可用端口
    // https: {
    //   key: fs.readFileSync(path.resolve(__dirname, 'keys/localhost+2-key.pem')),
    //   cert: fs.readFileSync(path.resolve(__dirname, 'keys/localhost+2.pem')),
    // },
    // open: false, // 在服务器启动时自动在浏览器中打开应用程序. 当此值为字符串时, 会被当作URL的路径名.
    // proxy: { // 代理
    //   '/srv/': {
    //     // target: 'http://voice.onwall.cn',
    //     target: viteEnv.VITE_PROXY_TARGET,
    //     changeOrigin: true,
    //     // rewrite: (path) => path.replace(/^\/api/, '')
    //   },
    // },
    proxy: createProxy(viteEnv.VITE_PROXY_PREFIX, viteEnv.VITE_PROXY_TARGET),
    // cors: '', // 为开发服务器配置 CORS。默认启用并允许任何源,传递一个 选项对象 来调整行为或设为 false 表示禁用。
    // force: '', // 设置为 true 强制使依赖预构建。
    // hmr: '', // 禁用或配置 HMR 连接(用于 HMR websocket 必须使用不同的 http 服务器地址的情况)。 设置 server.hmr.overlay 为 false 可以禁用服务器错误遮罩层。
    // watch: '', // 传递给 chokidar 的文件系统监视器选项。
  },
  build: {
    // outDir: 'voice', // 指定输出路径(相对于项目根目录).
    outDir: viteEnv.VITE_OUTDIR, // 指定输出路径(相对于项目根目录).
    assetsDir: 'static',
    rollupOptions: {
      output: {
        chunkFileNames: 'static/js/[name]-[hash].js',
        entryFileNames: 'static/js/[name]-[hash].js',
        assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
      },
      input: {
        // 多页面应用模式, 打包时配置,运行配置要处理root
        main: path.resolve(__dirname, 'index.html'),
        // mono1: path.resolve(__dirname, 'src/packages/mono1/index.html'),
        // mono2: path.resolve(__dirname, 'src/packages/mono2/index.html'),
      },
    },
    // target: 'es2015'
  },
});
};