问题描述
用CommonsChunkPlugin把bundle.js分割到不同文件。能正常访问,但在非一级页面下刷新就会从当前路径下获取静态资源(静态资源都在根路径下),然后报错。不分割,全打包在bundle.js下则无此问题。
错误如下:
这些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"
解决了,路径问题。output.publicPath设置为"/"就好了。