Appearance

webpack小技巧

coderzhouyu2023-10-08 10:45:51

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

1. 使用 html-webpack-plugin

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
      template: 'public/index.html',
      templateParameters: {
        BASE_URL: './',
        DIY_VAR: 'diy_var',
      },
    }),
  ],
};

2. 使用 webpack.DefinePlugin

// webpack.config.js
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      BASE_URL: JSON.stringify('./'),
      DIY_VAR: JSON.stringify('diy_var'),
    }),
  ],
};

3. 在vue.config.js 中配置

// vue.config.js
module.exports = {
  chainWebpack: (config) => {
    config.plugin('html').tap((args) => {
      args[0].BASE_URL = './';
      args[0].DIY_VAR = 'diy_var';
      return args;
    });
  },
};

4. 在html中直接使用

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>webpack <%= DIY_VAR %></title>
  </head>
  <body>
    <div id="app"></div>
    <script src="<%= BASE_URL %>main.js"></script>
  </body>
</html>
Last Updated 2023/10/8 10:53:01