An Example React with Webpack File Structure

Now it’s time to set up our file structure before we write any code.

Firstly, let’s create a new file called .gitignore :

touch .gitignore

This file will contain a list of all the files and folders that are not to be included when we push our project to GitHub. There is a website that serves boilerplate code for .gitignore files, which is very useful, because often, a .gitignore file can be rather long and verbose, and we may forget some files or folders that we want Git to ignore.

Go to https://www.gitignore.io/ and type Node into the search bar, then click Generate . This will generate a file that looks like this:

# Created by https://www.gitignore.io/api/node

### Node ###
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

Now we can copy and paste that into our .gitignore file.

Notice that the .gitignore file should always include node_modules . This is extremely important, because we don’t want to include our node_modules folder with our Git commits, as they take up a lot of disk space, and can be installed with npm install , which refers to our package.json .

Most of the files and folders listed in our .gitignore file don’t exist in our project yet, but if they do in the future, they won’t be included in our Git commits, which is important and useful, because we must be selective about what we commit.

Now, we need to make a new folder that will contain the contents of our development code. Let’s call it src :

mkdir src

Then, we need to make a folder that will contain files that we use for production purposes. We’ll call this folder dist :

mkdir dist

Now that we have installed our packages and created empty src and dist folders, our tree will look like this (not including .gitignore , which is a hidden file):

.
├── dist
├── node_modules
├── package.json
├── src
└── webpack.config.js

Now, we can make a new js folder that goes into our src folder. This will contain all our React code:

mkdir src/js

We can go ahead and create an empty client.js in our src/js . This will be our main React file:

touch src/js/client.js

We also need an index.html that should not go into our src folder, rather into our dist folder, because it is required for the production of our app:

touch dist/index.html

So now, our tree looks something like this:

.
├── dist
│   └── index.html
├── node_modules
├── package.json
├── src
│   └── js
│       └── client.js
└── webpack.config.js
2 Likes