Appearance

vite小技巧

coderzhouyu2023-10-08 10:50:37

vite 中给 public/index.html 中注入变量

webpack小技巧

1. 使用 html-webpack-plugin

// vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import HtmlWebpackPlugin from 'html-webpack-plugin';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    new HtmlWebpackPlugin({
      template: 'public/index.html',
      templateParameters: {
        BASE_URL: './',
        DIY_VAR: 'diy_var',
      },
    }),
  ],
});

2. 使用 webpack.DefinePlugin

// vite.config.js

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    new webpack.DefinePlugin({
      BASE_URL: JSON.stringify('./'),
      DIY_VAR: JSON.stringify('diy_var'),
    }),
  ],
});

3. 在html中直接使用

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vite App</title>
    <script>
      window.BASE_URL = './';
      window.DIY_VAR = 'diy_var';
    </script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
Last Updated 2023/10/8 10:53:01