vite.config.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // 含有.js的文件
  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(/\.\/src\/[^\s]*/g, `${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. base: './',
  32. resolve: {
  33. alias: {
  34. /*
  35. 路径别名
  36. 若为文件系统路径必须是绝对路径的形式,否则将以别名原样呈现,不会解析为文件系统路径路径
  37. */
  38. '@': path.resolve(__dirname, './src')
  39. }
  40. },
  41. plugins: [createVuePlugin(), viteCompression({ //gzip压缩
  42. disable: true,
  43. })],
  44. server: {
  45. host: 'localhost',
  46. port: 6547,
  47. open: true,
  48. strictPort: false,
  49. https: false,
  50. // 反向代理
  51. // proxy: {
  52. // '/': {
  53. // target: 'http://172.16.1.215:5000',
  54. // changeOrigin: true,
  55. // rewrite: (path) => path.replace(/^\//, '')
  56. // },
  57. // }
  58. },
  59. build: {
  60. rollupOptions: {
  61. input: entryConfig(),
  62. output: { //静态资源分类打包
  63. chunkFileNames: 'js/[name]-[hash].js',
  64. entryFileNames: 'js/[name]-[hash].js',
  65. assetFileNames: 'assets/[name]-[hash].[ext]'
  66. }
  67. },
  68. terserOptions: { //去掉打印
  69. compress: {
  70. drop_console: true,
  71. drop_debugger: true,
  72. },
  73. },
  74. },
  75. define: { //环境变量配置
  76. 'process.env': {
  77. 'SERVERURL': mode === 'development' ? 'http://127.0.0.1:5000':'http://127.0.0.1:5000'
  78. }
  79. }
  80. })