Skip to content

使用WebpackDevServer

wepack --watch

package.json

1
2
3
"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

1
2
3
4
"scripts": {
  "watch": "webpack --watch",
  "start": "webpack-dev-server"
},

webpack.config.js

1
2
3
4
entry: './src/index.js',
devServer: {
  contentBase: './dist'
},

运行`npm run start,会启动一个服务器,默认地址为http://localhost:8080/

修改后会自动刷新页面,大大提高开发效率

还可以配置

1
2
3
4
5
entry: './src/index.js',
devServer: {
  contentBase: './dist',
  open: true
},

会自动打开浏览器

使用服务器,可以很方便使用ajax

1
2
3
4
5
6
7
devServer: {
  contentBase: './dist',
  open: true,
  proxy: {
    '/api': 'http://localhost:3000'
  }
},

node中使用webpack

package.json

1
2
3
4
5
6
"scripts": {
  "bundle": "webpack",
  "watch": "webpack --watch",
  "start": "webpack-dev-server",
  "server": "node server.js"
},

npm install express webpack-dev-middleware -D

webpack.config.js

1
2
3
4
5
output: {
  publicPath: '/',
  filename: '[name].js',
  path: path.resolve(__dirname, 'dist')
}

server.js

1
2
3
4
5
6
7
const express = require('express');
const webpack = require('webpack');

const app = express();
app.listen(3000, () => {
  console.log('server is running');
});
1
2
3
4
5
6
➜  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');
});
1
2
3
4
5
6
➜  lesson npm run server

> lesson@1.0.0 server /Users/nocilantro/Desktop/nocilantro/lesson
> node server.js

server is running

可以去掉server.js中的publicPath

1
2
3
app.use(webpackDevMiddleware(complier, {
  // publicPath: config.output.publicPath
}));

去掉webpack.config.js中的publicPath

1
2
3
4
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/