2016-03-07 125 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目录。

相关问题