React with Typescript and Webpack – Hacker Noon

Let’s Build!

You can now actually manually build your application. We will get to building automatically before running our server later. but for now if you want to take a look at your efforts until now, just add a ‘build’ script to your package.json file and execute the webpack command.

package.json:

...
scripts: {
...
"build": "./node_modules/.bin/webpack",
...
}
...

If you go to the terminal and run this command, you can look at your bundled application in the dist folder.

Run this in your terminal:

npm run build

Output in the terminal:

npm run build
bundled code

Let’s Express!

If you do not want to use express to run a server for you react application to be served, you can use webpack-dev-server which takes care of it and you do not have to write a server yourself but if you want to have the flexibility of a custom server for you to write middlewares, handle routes and modify requests and responses then it is recommended that you write your own server. At the time of writing this article, webpack-dev-server has no new features planned and is in maintenance only mode.

https://www.npmjs.com/package/webpack-dev-server

server.js:

const path = require('path'),
express = require('express'),
webpack = require('webpack'),
webpackConfig = require('./webpack.config.js'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port, () => { console.log(`App is listening on port ${port}`) });
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
let compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true, publicPath: webpackConfig.output.publicPath, stats: { colors: true }
}));
app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.resolve(__dirname, 'dist')));

Now you can go to your package.json and add the start script

"start": "npm run build && node server.js"

read original article here