一. 使用express.js搭建一个简易服务器demo地址,热替换的
先看包
// 清除重复的文件
"clean-webpack-plugin"
// css加载器
"css-loader"
// node框架
"express"
// 自动加载模板和js
"html-webpack-plugin"
// style加载器
"style-loader"
// 局部的webpack
"webpack"
// 局部的webpack-cli
"webpack-cli"
// 开发的中间件
"webpack-dev-middleware"
// 热替换的中间件
"webpack-hot-middleware"
下载完了之后,编写webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = {
// 必须是数组,后面会添加进来东西
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
hot: true,
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
},
plugins: [
// 名字改变
new webpack.NamedModulesPlugin(),
// 模块替换
new webpack.HotModuleReplacementPlugin(),
// 清理插件
new CleanWebpackPlugin(),
// 自动加载
new HtmlWebpackPlugin({
title: 'Development',
template: './index.html'
})
],
};
再来开发server.js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const app = express();
// 引入配置
const config = require('./webpack.config.js');
const compiler = webpack(config);
// 加入入口文件
config.entry.unshift(
'webpack-hot-middleware/client?reload=true',
)
// express app这里是用use使用中间件,接受一个函数
// 通知webpack-dev-middleware
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath,
noInfo: true,
hot: true,
inline: true,
}));
app.use(webpackHotMiddleware(compiler));
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
在package.json中 添加
"scripts": {
"start": "node server"
},
最后 yarn start
localhost:3000
可以看到效果
源码: node-server demo
二. 使用 webpack 搭建一个简单的热替换服务器 demo 地址 热替换
package.json
"clean-webpack-plugin";
"css-loader";
"html-webpack-plugin";
"style-loader";
"webpack";
"webpack-cli";
// 加入webpack自带的服务器插件
"webpack-dev-server";
webpack.config.js 中添加
devServer: {
contentBase: './dist',
hot: true,
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Development',
template: './index.html'
})
],
最后 package.json
"scripts": {
"start": "webpack-dev-server --config"
},
yarn start
localhost:8080