這幾天在學習webpack使用中,發現的一個問題,記錄一下
問題:
1.webpack devServer 沒法自動刷新瀏覽器,可是能夠自動編譯
2.沒法加載js文件(不使用devServer狀況下,能夠正常加載js)css
webpack.config.js的配置以下:html
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); // 封裝自動生成html插件須要的參數 var getHtmlConfig = function(name){ return { filename : 'view/' + name + '.html', template : './src/view/' + name + '.html', inject : 'true', hash : 'true', chunks :['common',name] }; } module.exports = { mode : 'development',/*三種打包模式,development(用於開發,方便閱讀)、production(用於上線,壓縮優化)、none(啥都不設置,給機器看的)*/ entry : {//入口 'common' : './src/page/common/index.js', 'index' : './src/page/index/index.js', 'login' : './src/page/login/index.js' }, devServer : {//告訴開發服務器(dev server),在哪裏查找文件 contentBase : path.join(__dirname, 'dist'), inline : true }, output : {//輸出 filename : 'js/[name].js', path : path.resolve(__dirname,'dist'),//絕對路徑,當前目錄下的dist。後面設置的輸出路徑都以此爲基礎 }, module : {//loader rules : [ { test : /\.css$/, use : ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader", publicPath : '../'//用於CSS文件url路徑查找:url(../resource/xxx.jpg) }) }, { test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/, use: { loader : 'url-loader', options : { limit : 10000, name : 'resource/[name]-[hash].[ext]' } } } ] }, plugins : [ // 抽離css文件 new ExtractTextPlugin({ filename: "css/bundle.css", disable: false, allChunks: true }), // 自動生成html文件 new HtmlWebpackPlugin(getHtmlConfig("index")), new HtmlWebpackPlugin(getHtmlConfig("login")), //熱模塊更新 new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin() ], /* 把optimization註釋掉以後,devserver能夠加載成功js文件和自動刷新了。命令行打包顯示: js/vendors~common~index~login.js 345 KiB vendors~common~index~login [emitted] vendors~common~index~login 估計是由於把js文件都抽離到vendors~common~index~login.js這裏了,因此在devserver下,index.html引用index.js和common.js沒有效 */ // optimization: { // // splitChunks: { // chunks: 'initial', // minSize: 30000, // maxSize: 0, // minChunks: 1, // maxAsyncRequests: 5, // maxInitialRequests: 3, // automaticNameDelimiter: '~', // name: true, // cacheGroups: { // vendors: { // test: /[\\/]node_modules[\\/]/, // priority: -10 // }, // commons: { // test: /page\//, // name: 'page', // priority: 10, // enforce: true // } // } // } // } };
命令行打包後顯示信息:
node
解決:
把optimization註釋掉以後,devserver能夠加載成功js文件和自動刷新了。估計是由於把js文件都抽離到vendors~common~index~login.js這裏了,因此在devserver下,index.html引用index.js和common.js沒有效。
只是估計,新手上路,目前對webpack的使用仍是摸石過河。你們知道緣由麻煩評論告知webpack