怎么把项目里的webpack换成vite?

237 阅读1分钟

" 首先,安装 Vite 和相关插件:

npm install vite @vitejs/plugin-vue

然后,将项目中的 webpack 相关配置文件删除,创建一个新的 vite.config.js 文件:

import { defineConfig } from 'vite';

export default defineConfig({
  // Vite 配置
});

接着,将 package.json 中的 scripts 替换为 Vite 命令:

\"scripts\": {
  \"dev\": \"vite\",
  \"build\": \"vite build\"
}

然后,根据项目需要,在 Vite 配置文件中添加相关配置,比如插件、代理、别名等:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\\/api/, '')
      }
    }
  },
  resolve: {
    alias: {
      '@': '/src'
    }
  }
});

接着,进行代码调整,比如将 webpack 相关代码替换为 Vite 相关代码,特别是在 vue 文件中的 import、export 部分:

// Before
import { createApp } from 'vue';
// After
import { createApp } from 'vue/dist/vue.esm-bundler';

// Before
export default {
  data() {
    return {
      message: 'Hello, Vite!'
    };
  }
};
// After
export default {
  data() {
    return {
      message: 'Hello, Vite!'
    };
  }
};

最后,运行 Vite 开发服务器并构建项目:

npm run dev
npm run build
```"