使用WebpackDevServer
wepack --watch
package.json
| "scripts": {
"watch": "webpack --watch"
},
|
npm run watch
使用 webpack-dev-server
https://www.webpackjs.com/configuration/dev-server/
npm install webpack-dev-server -D
package.json
| "scripts": {
"watch": "webpack --watch",
"start": "webpack-dev-server"
},
|
webpack.config.js
| entry: './src/index.js',
devServer: {
contentBase: './dist'
},
|
运行`npm run start
,会启动一个服务器,默认地址为http://localhost:8080/
修改后会自动刷新页面,大大提高开发效率
还可以配置
| entry: './src/index.js',
devServer: {
contentBase: './dist',
open: true
},
|
会自动打开浏览器
使用服务器,可以很方便使用ajax
| devServer: {
contentBase: './dist',
open: true,
proxy: {
'/api': 'http://localhost:3000'
}
},
|
node中使用webpack
package.json
| "scripts": {
"bundle": "webpack",
"watch": "webpack --watch",
"start": "webpack-dev-server",
"server": "node server.js"
},
|
npm install express webpack-dev-middleware -D
webpack.config.js
| output: {
publicPath: '/',
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
|
server.js
| const express = require('express');
const webpack = require('webpack');
const app = express();
app.listen(3000, () => {
console.log('server is running');
});
|
| ➜ lesson npm run server
> lesson@1.0.0 server /Users/nocilantro/Desktop/nocilantro/lesson
> node server.js
server is running
|
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13 | const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const config = require('./webpack.config.js');
const complier = webpack(config);
const app = express();
app.use(webpackDevMiddleware(complier, {
publicPath: config.output.publicPath
}));
app.listen(3000, () => {
console.log('server is running');
});
|
| ➜ lesson npm run server
> lesson@1.0.0 server /Users/nocilantro/Desktop/nocilantro/lesson
> node server.js
server is running
|
可以去掉server.js
中的publicPath
| app.use(webpackDevMiddleware(complier, {
// publicPath: config.output.publicPath
}));
|
去掉webpack.config.js
中的publicPath
| output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
}
|
所以webpack还可以在一个node中直接使用
命令行接口
https://www.webpackjs.com/api/cli/
Node.js API
https://www.webpackjs.com/api/node/