webpack生成多个文件名,非一级页面刷新报错,返回404。

问题描述

  1. 用CommonsChunkPlugin把bundle.js分割到不同文件。能正常访问,但在非一级页面下刷新就会从当前路径下获取静态资源(静态资源都在根路径下),然后报错。不分割,全打包在bundle.js下则无此问题。

  2. 错误如下:
    图片描述

这些js文件实际是在根路径下,但不知为何,浏览器没在根路径下请求这些js文件

webpack.config.js如下:

const webpack = require('webpack');
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
  entry:  ["babel-polyfill",__dirname + "/app/index.js"],
  output: {
    path: __dirname + "/public",
    filename: "[name].[hash].js",
    // filename: "bundle.js",
  },

  module: {
      rules: [
          {
            test: /\.json$/,
            use: 'json-loader'
          },
          {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader?cacheDirectory=true',
            
          }
        },
        {
            test: /\.css$/,
            use: ['style-loader','css-loader']
          },
          {
            test: /\.(png|jpg|gif|eot|svg|ttf|woff|woff2)$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'url-loader?limit=1024&name=images/[name].[ext]',
                options: {
                  limit: 8192
                }
              }
            ]
          },
          {
            test: /\.less$/,
            use: [{
                    loader: "style-loader" // creates style nodes from JS strings
                }, {
                    loader: "css-loader" // translates CSS into CommonJS
                }, {
                    loader: "less-loader" // compiles Less to CSS
                }]
          }
          ]
  },
  plugins:[
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new webpack.DefinePlugin({
      "process.env": {
        NODE_ENV: JSON.stringify("development")
      }
    }),
     new HtmlWebpackPlugin(),
      new webpack.optimize.CommonsChunkPlugin({
        name: "vendor",
        minChunks: function(module){
          return module.context && module.context.indexOf("node_modules") !== -1  ;
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        name: "manifest",
        minChunks: Infinity
      }),
      // new BundleAnalyzerPlugin(),
  ],
  devServer: {
      contentBase: path.join(__dirname, "public"),
      compress: true,
      port: 9000,
      historyApiFallback: true,
      quiet: true,
      inline: true,
    },
    
}

补充
如果output.fileName不是动态的,而是写成“bundle.js”,则没有问题。哪怕在2、3级链接下刷新,浏览器也会从根路径下请求js。
webpack版本:
"webpack": "^3.0.0",
"webpack-dev-server": "^2.5.0"

阅读 2.7k
1 个回答

解决了,路径问题。output.publicPath设置为"/"就好了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进