4#webpack express

接着前面3章的项目,添加一个server.js

npm install --save-dev express webpack-dev-middleware

#server.js 

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));

// Serve the files on port 3000.
app.listen(3000, function () {
  console.log('Example app listening on port 3000!\n');
});


#webpack.config.js

output: {
    filename: '[name].bundle.js',
    publicPath: '/',
    path: path.resolve(__dirname, 'dist')
  },

#package.json 加一个server script

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server",
    "server": "node server.js",
    "build": "webpack"
  },

执行命令:npm run server

如果报确实一些莫名其妙的模块,比如body-parser,fsevents,qs,depd之类的;删除node_modules文件夹,重新install一遍,应该就好了。

如果命令成功执行,那么打开浏览器输入:http://localhost:3000
不是我们在devServer中设置的port:9999。
这时为什么呢?
因为我们现在开启的是一个express服务,可以把它当成Java里面的tomcat类似的东西,反正就是创建了一个本地web服务,而express端口默认的是3000。

你可能感兴趣的:(4#webpack express)