问题描述
开始正常,但是在使用webpack-dev-middleware 与webpack-hot-middlewae后导致javascript的响应头Conten-type发生改变,致使火狐浏览器和谷歌浏览器阻止javascript执行。
火狐提示
来自“http://localhost:3000/javascripts/dist/manifest.bundle.js”的资源已被阻止,因为 MIME 类型不匹配(X-Content-Type-Options: nosniff)。[详细了解] login来自“http://localhost:3000/javascripts/dist/main.bundle.js”的资源已被阻止,因为 MIME 类型不匹配(X-Content-Type-Options: nosniff)。[详细了解] login来自“http://localhost:3000/javascripts/dist/vendor.bundle.js”的资源已被阻止,因为 MIME 类型不匹配(X-Content-Type-Options: nosniff)。[详细了解] login来自“http://localhost:3000/javascripts/dist/main.bundle.js”的资源已被阻止,因为 MIME 类型不匹配(X-Content-Type-Options: nosniff)。[详细
增加的代码
const webpack=require('webpack');const webpackConfig = require('./public/javascripts/webpack.config');const compiler = webpack(webpackConfig);//使用webpacl-dev-middlewareapp.use(require("webpack-dev-middleware")(compiler,{ noInfo:true,publicPath:webpackConfig.output.publicPath}));//使用webpack-hot-middlewareapp.use(require("webpack-hot-middleware")(compiler));
webpack配置文件
const webpack = require('webpack');const path=require('path');const config={ entry:{ main:'./public/javascripts/login.js', vendor:['react','react-dom'] }, output:{ filename:'[name].bundle.js', path:path.resolve(__dirname,'dist') }, module: { rules: [ { test: /\.(js|jsx)$/, loader: 'babel-loader' } ] }, plugins:[ new webpack.optimize.CommonsChunkPlugin({ name:['vendor','manifest'] }) ]};module.exports=config;
解决方案
上述问题已经解决。
问题原因是没有将webpack-dev-middleware中关于publicPath的配置与href,src等请求路径对应起来,但是在使用webpack-dev-middleware之前,使用的是webpack cli编译的方式,href和src的路径是与webpack cli编译输出文件相对应的,这样就导致每次客户端发起请求,能找到文件,但是会导致content-type类型错误,导致浏览器不执行。