Skip to content

Instantly share code, notes, and snippets.

@HoverBaum
Last active May 24, 2016 02:18
Show Gist options
  • Save HoverBaum/5b1ca3fdc0207a9e191ee58d4a219710 to your computer and use it in GitHub Desktop.
Save HoverBaum/5b1ca3fdc0207a9e191ee58d4a219710 to your computer and use it in GitHub Desktop.
Webpack setup for React projects

Developing react based applications using webpack

Since this just took me a day to get to work. Let me tell you how I did it.

My filestructure for this looks like this:

.
├── package.json
├── src
│   ├── js
│   │   └── app.js
│   └── www
│       └── index.html
├── tpl
│   ├── index.html
│   └── js
│       └── app.js
└── webpack.config.js

With src being the source folder for my project and tpl being the folder I am building my project into. (Lagacy reasons)

Now there are a few things I want to do:

  1. Compile my react, including JSX Code with babel and pack it into a nice bundle file
  2. Copy All static assets (like my index page)
  3. Watch all of it and serve it to a browser with live reload features

React

To get react to work we need Babel. My .babelrc is quite simple:

{ "presets": ["es2015", "react"] }

And basically copied from the react docs.

Now we can use webpack to pack that all into a bundled and transpiled ES5 file. Check out the webpack config file.

Static file

Here I want to copy over my HTML file. You could include that in you entry JS file. But that feels wrong to me. So I rather use copy-webpack to simply copy it over.

Live server

There are many servers with live reloading features you could use. I personally like live-server.

So I have webpack compile and watch my source files and live-server serve them. Which requires to consoles to be open but ohh well.

NPM script

To make my live easier I installed webpack as a local development dependency and in my package.json added a script.

"scripts": {
    "webpack": "node node_modules/webpack/bin/webpack.js --progress --colors --watch"
  }

Now I ca just run

npm run webpack

Usefull links

var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: "./src/js/app.js",
output: {
path: path.join(__dirname, 'tpl', 'js'),
filename: "app.js"
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}]
},
plugins: [
new CopyWebpackPlugin([
{
from: 'src/www/index.html',
to: '../index.html'
}
])
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment