簡體   English   中英

WebPack:在 html 中編譯 JS 文件時出現問題

[英]WebPack: problem when compiling JS files in html

我在使用 Webpack 時遇到問題。 I'm using a JS file to call an API, but this API should be called only in escudos.html, but when I do the Webpack build, the JS file calls the API int both (index.html, escudos.html). I only want that the./src/js/teams.js call API when I am in the escudos.html, not in in both (index.html, escudos.html) HTML.

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

module.exports = {
  entry: {
    index: './src/js/index.js',
    teams: './src/js/teams.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].bundle.js',
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/index.html',
    }),
    new HtmlWebpackPlugin({
      filename: 'escudos.html',
      template: './src/escudos.html',
    }),
  ],
  devServer: {
    static: './dist',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: { loader: 'babel-loader' },
      },
    ],
  },
};

出於某種原因,我的 webpacked 文件 index.html 也有team.js

問題(和解決方案)在 HtmlWebpackPlugin 中。 默認情況下,HtmlWebpackPlugin 會在每個頁面中注入所有條目。
我能想到三個解決方案:

  1. inject: false : 這將禁用<script>標簽自動注入模板。 您必須使用正確的 src 手動編寫<script>標記。 (pss:不要)
  2. chunks :指定要包含在此模板中的條目。 EG:(解決 OP 問題,在大多數情況下您將需要/使用什么)
     new HtmlWebpackPlugin({ template: "./src/index.html", chunks: ["index"] }), new HtmlWebpackPlugin({ template: "./src/escudos.html", chunks: ["teams"] })
  3. exclude :注入除此數組中指定的條目之外的所有條目。 例如
    new HtmlWebpackPlugin({ template: "./src/test.html", exclude: ["index"] })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM