使用Webpack的Index.html-如何在其中添加条件代码?

时间:2019-08-12 19:25:24

标签: webpack html-webpack-plugin

我正在使用“ HtmlWebpackPlugin”来启动webpack,我想添加一些Google解析代码,但当然我只希望将其放在生产服务器上。

有没有简单的方法可以做到这一点?

这是我的“ webpack.common.js”(我有一个用于生产,qa和dev)。

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require('webpack');

module.exports = {
  entry: ["@babel/polyfill", "./src/index.js"],
  output: {
    // filename and path are required
    filename: "main.js",
    path: path.resolve(__dirname, "dist"),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        // JSX and JS are all .js
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}  
          }
        ]
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
   })
  ]
};

我更新为

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');

module.exports = (env, argv) => {
  const ga = argv.mode === 'production' ? './index-google.html' : 'index.html';
  return {
    entry: ['@babel/polyfill', './src/index.js'],
    output: {
      // filename and path are required
      filename: 'main.js',
      path: path.resolve(__dirname, 'dist'),
      publicPath: '/'
    },
    module: {
      rules: [
        {
          // JSX and JS are all .js
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader'
          }
        },
        {
          test: /\.(eot|svg|ttf|woff|woff2)$/,
          use: [
            {
              loader: 'file-loader',
              options: {}
            }
          ]
        },
        {
          test: /\.(png|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
              options: {}
            }
          ]
        }
      ]
    },
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        template: './src/index.html'
      }),
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      })
    ]
  };
};

但是当我建造时我得到了

ERROR in ./src/index.js 35:4
Module parse failed: Unexpected token (35:4)
You may need an appropriate loader to handle this file type.
| ReactDOM.render(
| 
>     <Provider routingStore={routingStore} domainStores={DomainStores} uiStores={uiStores}>
|       <Router history={history}>
|         <ErrorBoundary FallbackComponent={ErrorFallbackComponent}>
 @ multi ./src main[0]

babel文件

{
  "presets": ["@babel/env", "@babel/react"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@babel/plugin-transform-object-assign",
    "@babel/plugin-proposal-object-rest-spread",
    "transform-class-properties",
    "emotion"
  ]
}

我有一个旧仓库,以我的真实代码为模型

https://github.com/chobo2/webpack-serve-example

1 个答案:

答案 0 :(得分:0)

您可以检查它是否是正式版本,从而满足您的喜好

new HtmlWebpackPlugin({
  filename: 'index.html',
  template: argv.mode === 'production' ? 'src/index-google.html' : 'src/index.html'
})

或看看这个stackoverflow

编辑
我看到您的webpack项目分为dev,prod,common和config。 从配置中删除HtmlWebpackPlugin,并使用适当的html文件插入到dev和prod中。

dev

new HtmlWebpackPlugin({
  template: "./src/index.html"
})

产品

new HtmlWebpackPlugin({
  filename: index.html,
  template: "./src/index-google.html"
})

我希望这可以解决问题