【问题标题】:Webpack HtmlWebpackPlugin - Bundled file serves up HTML?Webpack HtmlWebpackPlugin - 捆绑文件提供 HTML?
【发布时间】:2017-09-19 01:44:20
【问题描述】:

我正在使用带有 HtmlWebpackPlugin 的 webpack。使用 Flask 服务器提供生成的 index.html。 index.html 从 Flask 服务器调用得很好。但是,我认为我的 webpack 配置中有一个错误导致 app.bundle.js 变坏。

在浏览器开发工具上我可以看到错误是

Uncaught SyntaxError: Unexpected token

浏览器加载app.bundle.js时,似乎认为是index.html的副本。但是在我的本地计算机上,我可以看到 app.bundle.js 是 webpack Javascript 包。

Webpack 配置文件

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

module.exports = {
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, "static/dist"),
    filename: '[name].bundle.[hash].js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'index.template.ejs'),
      showErrors: true,
      hash: true,
    })
  ],
  module: {
    rules: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
      {
        test: /\.css$/,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: { importLoaders: 1, modules: true },
          },
          "sass-loader"
        ],
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {}
          }
        ]
      },
      {
        test: /\.svg$/,
        loader: 'svg-inline-loader'
      }
    ],

  },
  resolve: {
    alias:{
      components: path.resolve(__dirname, './components'),
      containers: path.resolve(__dirname, './containers'),
      channels: path.resolve(__dirname, './channels'),
      models: path.resolve(__dirname, './models'),
      stores: path.resolve(__dirname, './stores'),
      lib: path.resolve(__dirname, './lib')
    },
    modules: ['components', "node_modules"],
    extensions: ['.js', '.jsx']
  }
};

【问题讨论】:

    标签: webpack html-webpack-plugin


    【解决方案1】:

    这个问题是由于没有正确加载JS源引起的。它比实际 main.bundle.[hash].js 源所在的位置低两个级别。

    <script type="text/javascript" src="main.bundle.[hash].js"></script>
    

    应该是

    <script type="text/javascript" src="static/dist/main.bundle.[hash].js"></script>
    

    但真正的问题是浏览器的回退。它无法正确找到源,并挖掘了需要包含失败脚本的 HTMl 文件。当它拉取 HTML 时,它最终读取了一个 JS 文件。

    我通过在我的 webpack 配置中添加一个 publicPath 来解决这个问题。

    module.exports = {
    ...
      output: {
          ...
          publicPath: 'static/dist'
          ...
      }
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 2017-02-05
      • 2016-10-05
      • 1970-01-01
      • 2017-02-27
      • 2022-07-10
      相关资源
      最近更新 更多