vite.config.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { defineConfig } from 'vite'
  2. import { createVuePlugin } from 'vite-plugin-vue2'
  3. import viteCompression from 'vite-plugin-compression'
  4. import path from 'path'
  5. import glob from 'glob'
  6. import fs from 'fs'
  7. // 多页面入口配置
  8. const entryConfig = function () {
  9. const viteconfig = {}
  10. // 含有.ts的文件
  11. const entryFiles = glob.sync('./src/pages/*/*.js')
  12. // 获取模板
  13. const temp = fs.readFileSync('./index.html')
  14. // 模板增加ts入口
  15. entryFiles.forEach((entry) => {
  16. const projectName = entry.split('/')[3]
  17. try {
  18. fs.accessSync(`./${projectName}.html`)
  19. } catch (error) {
  20. // 重构模板
  21. const html = temp.toString().replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, `<script type="module" src="${entry}"></script>`)
  22. fs.writeFile(`./${projectName}.html`, html, (err) => {
  23. if (err) console.error(err)
  24. })
  25. }
  26. viteconfig[projectName] = path.resolve(__dirname, `./${projectName}.html`)
  27. })
  28. return viteconfig
  29. }
  30. export default ({ mode }) => defineConfig({
  31. resolve: {
  32. alias: {
  33. /*
  34. 路径别名
  35. 若为文件系统路径必须是绝对路径的形式,否则将以别名原样呈现,不会解析为文件系统路径路径
  36. */
  37. '@': path.resolve(__dirname, './src')
  38. }
  39. },
  40. plugins: [createVuePlugin(), viteCompression()],
  41. server: {
  42. host: '0.0.0.0',
  43. port: 5000,
  44. open: true,
  45. strictPort: false,
  46. https: false
  47. // 反向代理
  48. // proxy: {
  49. // '/admin': {
  50. // target: 'http://api.vite-admin.com',
  51. // changeOrigin: true,
  52. // rewrite: (path) => path.replace(/^\/admin/, '')
  53. // },
  54. // }
  55. },
  56. build: {
  57. rollupOptions: {
  58. input: entryConfig(),
  59. output: { //静态资源分类打包
  60. chunkFileNames: 'js/[name]-[hash].js',
  61. entryFileNames: 'js/[name]-[hash].js',
  62. assetFileNames: 'static/[name]-[hash].[ext]',
  63. // 拆分node_modules包
  64. manualChunks: (id) => {
  65. if (id.includes("node_modules")) {
  66. return id
  67. .toString()
  68. .split("node_modules/")[1]
  69. .split("/")[0]
  70. .toString();
  71. }
  72. }
  73. }
  74. }
  75. },
  76. define: { //环境变量配置
  77. 'process.env': {
  78. 'SERVERURL': mode === 'development' ? '':''
  79. }
  80. }
  81. })