在react項目中使用 webpack-dev-server
1、什么是 webpack-dev-server
The webpack-dev-server is a little node.js Express server, which uses the webpack-dev-middleware to serve a webpack bundle
- webpack-dev-server 是一個服務(wù)器(應(yīng)該是這么理解)
2、安裝與運行
Using this config webpack-dev-server will serve the static files in your build folder. It’ll watch your source files for changes and when changes are made the bundle will be recompiled. This modified bundle is served from memory at the relative path specified in publicPath (see API). It will not be written to your configured output directory. Where a bundle already exists at the same url path the bundle in memory will take precedence (by default)
安裝
- 安裝:
npm install webpack-dev-server --save-dev
配置
- 根據(jù)文檔描述,是需要配置publicPath的。所以webpack.config.js配置為
module.exports = {
context: __dirname + "/app",
entry: [
"./entry"
],
output: {
path: __dirname + "/build",
publicPath: "/build",
filename: "bundle.js"
}
};
- 并且在package.json中配置
"scripts": {
"iframe-start": "webpack-dev-server",
"inline-start": "webpack-dev-server --inline"
},
運行
The webpack-dev-server supports multiple modes to automatic refresh the page:
Iframe mode (page is embedded in an iframe and reloaded on change)
Inline mode (a small webpack-dev-server client entry is added to the bundle which refresh the page on change)
- 使用命令行開啟服務(wù)
- 開啟iframe mode:
npm run iframe-start - 開啟inline mode:
npm run inline-start
- 開啟iframe mode:
訪問頁面
- Iframe mode:
http://localhost:8080/webpack-dev-server/index.html - Inline mode:
http://localhost:8080/index.html
3.拓展:使用node自己配置一個server
Hot Module Replacement with node.js API
Similar to the inline mode the user must make changes to the webpack configuration.
Three changes are needed:
1.add an entry point to the webpack configuration: webpack/hot/dev-server.
2.add the new webpack.HotModuleReplacementPlugin() to the webpack configuration.
3.add hot: true to the webpack-dev-server configuration to enable HMR on the server.
創(chuàng)建一個server.js
var webpack = require('webpack')
var config = require('./webpack.config.js')
/**
* 沒有添加這段代碼時,是不會自動刷新頁面的(有的時候不希望自動刷新)
* 添加了這段代碼,就需要配置webpack.config.js
*/
//config.entry.unshift("webpack-dev-server/client?http://localhost:3000/", "webpack/hot/dev-server")
var WebpackDevServer = require('webpack-dev-server')
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
noInfo: true,
historyApiFallback: true
}).listen(3000, '127.0.0.1', function( err, result ){
if ( err ) {
console.log( err )
}
console.log( 'Listening at localhost:3000' );
})
配置webpack.config.js
var webpack = require('webpack');
module.exports = {
......
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};