Vue3系列(一)之初始化项目及Vite 2.0配置

一.vite介绍

vite官网:https://cn.vitejs.dev/
Vite 是由 Vue 作者尤雨溪开发的一套一种新的、更快地 web 开发工具,它具快速的冷启动、即时的模块热更新、真正的按需编译几个特点。

二.项目搭建- vue3.0 + vite2

注意事项:
1.官方发布:Vite 目前只适用于 Vue 3.x,这也意味着开发的过程中不能使用与 Vue 3 不兼容的库。
2.Vite默认端口为3000,和webpack的8080有所区别,需要注意
3.和用Cli构建工具创建的项目不同,Vite初始化的项目比较纯净,相关依赖需要自行添加,如常用的vue-router/vuex等
//npm用户
npm init @vitejs/app
cd <项目名称>
npm install
npm run dev
npm run build
//yarn用户
yarn create @vitejs/app
cd <项目名称>
yarn install
yarn dev
yarn run build

在这里插入图片描述

三.配置留存 vite.config.js

import {
    
     defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import styleImport from 'vite-plugin-style-import';
import viteCompression from 'vite-plugin-compression';

const path = require('path');

// https://vitejs.dev/config/
export default defineConfig({
    
    
  build: {
    
    
    // outDir: "./www", //打包后的文件目录
    publicDir: 'assets',
    // 去除console
    terserOptions: {
    
    
      compress: {
    
    
        drop_console: true,
        drop_debugger: true
      }
    },
    rollupOptions: {
    
    
      output: {
    
    
        assetFileNames: 'css/[name].[hash].css',
        chunkFileNames: 'js/[name].[hash].js',
        entryFileNames: 'js/[name].[hash].js'
      }
    }
  },
  server: {
    
    
    host: '0.0.0.0', // 默认为localhost
    port: 7000, // 端口号
    open: true, // 是否自动打开浏览器
    base: './', // 生产环境路径
    strictPort: true,
    optimizeDeps: {
    
    
      include: ['axios', 'element-plus'] // 引入第三方插件
    },
    proxy: {
    
    
      // 本地开发环境通过代理实现跨域,生产环境使用 nginx 转发
      '^/api': {
    
    
        target: 'http://127.0.0.1', // 后端服务实际地址
        changeOrigin: true,
        rewrite: () => path.replace(/^\/api/, '')
      }
    }
  },
  resolve: {
    
    
    alias: {
    
    
      '@': path.resolve(__dirname, 'src') // 设置 `@` 指向 `src` 目录
    }
  },
  css: {
    
    
    preprocessorOptions: {
    
    
      scss: {
    
    
        modifyVars: {
    
    },
        javascriptEnabled: true
      }
    }
  },
  plugins: [
    vue(),
    styleImport({
    
    
      // css样式按需加载
      libs: [
        {
    
    
          libraryName: 'element-plus',
          esModule: true,
          ensureStyleFile: true,
          resolveStyle: name => {
    
    
            if (name === 'locale') return '';
            return `element-plus/lib/theme-chalk/${
      
      name}.css`;
          },
          resolveComponent: name => {
    
    
            return `element-plus/lib/${
      
      name}`;
          }
        }
      ]
    }),
    viteCompression({
    
    
      // 开启gzip模式
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz'
    })
  ]
});



这样,一个基本Vite配置就完成了,具体的配置根据自有的项目进行调整

猜你喜欢

转载自blog.csdn.net/r657225738/article/details/115505602