2016-03-07 63 views
3

我在一個非常簡單的設置中使用webpack-dev-server。 我發現即使服務器在index.js文件更改時自動觸發瀏覽器重新加載,而不是index.html更改時會觸發重新加載。我怎樣才能做到這一點?當index.html更改時瀏覽器自動重新加載

這裏是我的設置:

的package.json

{ 
    "name": "html-reload", 
    "version": "1.0.0", 
    "description": "", 
    "main": "src/index.js", 
    "scripts": { 
     "build": "node_modules/webpack/bin/webpack.js", 
     "start": "webpack-dev-server --host 0.0.0.0 --port 8383 --content-base dist" 
    }, 
    "author": "", 
    "license": "ISC", 
    "devDependencies": { 
    "webpack": "^1.12.14", 
    "webpack-dev-server": "^1.14.1" 
    } 
} 

webpack.config.js

module.exports = { 
    entry: './src/index.js', 
    output: { 
     path: 'dist', 
     filename: 'bundle.js' 
    } 
}; 

我啓動webpack-dev-server有:npm run start和我點我的瀏覽器到:

http://localhost:8383/webpack-dev-server/index.html 

我在src/index.js中所做的每個更改都會在瀏覽器中自動刷新,但在dist/index.html中所做的更改不會自動刷新。

回答

5

我終於絆倒了html-webpack-pluginin this guide所述。

我運行:

npm i -D html-webpack-plugin 

和編輯我webpack.config.js看起來像這樣:

'use strict'; 
const path = require('path'); 

const APPDIR = 'app/'; 

const HtmlWebpackPlugin = require('html-webpack-plugin'); 
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({ 
    template: path.resolve(__dirname, APPDIR, 'index.html'), 
    filename: 'index.html', 
    inject: 'body' 
}); 

const config = { 
    context: path.resolve(__dirname, APPDIR), 
    entry: './main.js', 
    output: { 
     path: path.resolve(__dirname, 'build'), 
     filename: 'bundle.js' 
    }, 
    module: { 
     loaders: [ 
      { 
       test: /\.js$/, 
       loader: 'babel', 
       include: path.resolve(__dirname, 'app/') 
      },{ 
       test: /\.css$/, 
       loaders: ['style', 'css'] 
      } 
     ] 
    }, 
    plugins: [HTMLWebpackPluginConfig] 
}; 

module.exports = config; 

「模板」 index.html文件現在駐留在我的app目錄,並在建立項目生成的index.html文件被放置在build目錄中。後者文件包含對捆綁輸出文件bundle.js的正確引用(這是兩個文件之間的唯一區別)。

「模板」 的index.html文件中應用:運行webpack-dev-server

<!doctype html> 
<html> 
    <head> 
    <script src="http://localhost:8090/webpack-dev-server.js"></script> 
    </head> 
    <body> 
    <div id='app'></div> 
    <script type="text/javascript" src="bundle.js"></script></body> 
</html> 

現在:

<!doctype html> 
<html> 
    <head> 
    <script src="http://localhost:8090/webpack-dev-server.js"></script> 
    </head> 
    <body> 
    <div id='app'></div> 
    </body> 
</html> 

生成的輸出的index.html文件中構建更改爲index.html也會立即在br中刷新owser。 這就是說,index.html是如此之小,編輯它並希望編輯自動刷新瀏覽器的用例似乎微不足道。 儘管如此,感覺更好的是index.html駐留在我的app目錄中,而不是build目錄。

相關問題