Вы находитесь на странице: 1из 11

Follow

HOME LEARN WEB DEVELOPMENT WEB DEV COURSES WRITE FOR US FREE $10 IN BITCOIN GET WEEKLY EMAILS

Manoj Singh Negi Follow


Built http://mousecomp.com. I write about Javascript http://eepurl.com/co0DYj. Solving people
problems. Javascript developer, Writer. http://manojsinghnegi.com
Aug 24, 2017 · 5 min read

Setting up a React project from scratch

Setting up a React project from scratch can be a daunting task for beginners.
Lots of npm modules to install, lots of con guration and other tasks.

( This is the rst part for second part click here )

There are lots of react project seeds we can use in place of starting a project
from scratch but then they come with a lot of boilerplate hard to make sense
for a beginner who is just starting out.

I was rebuilding my personal website in react and come with the idea to share
with you all how I will be building that project from scratch.

So let’s just get started. Fire up your terminal. :)

The entire tutorial code is hosted on Github here.

let’s start by creating a node project. In your terminal type these command.

1 mkdir reactProject
2 cd reactProject
3 npm init // start a node project

project.sh hosted with ❤ by G i t H u b view raw

In the above snippet rstly we are creating a directory named reactProject


and then inside it, we are running the command npm init to start a new
node project.

You will be prompted to input information about your project. You can just
press enter for every choice. if you wish to add information about your project
go ahead.

Now our node project is up and running.

Our next step will be installing react & react-dom

1 npm install ‐‐save react react‐dom

install‐react.sh hosted with ❤ by G i t H u b view raw

We are going to use webpack for bundling our code into one js le. So our
Next step is to install webpack and webpack-dev-server .

1 npm install ‐‐save webpack webpack‐dev‐server

w e b p a c k . s h hosted with ❤ by G i t H u b view raw

The webpack lib is used to bundle and output out js code in the location we
speci ed. The webpack-dev-server lib will help us to run development server
which will give use bene ts like hmr & live reload .

Now we will be needing babel to convert our es6 code to es5 browser
understandable code. Let’s install babel

1 npm install ‐‐save‐dev babel‐cli babel‐core babel‐loader babel‐plugin‐transform‐object‐rest‐spread babel‐preset‐es2015 babel‐preset‐react

install‐babel.sh hosted with ❤ by G i t H u b view raw

We have installed babel and its supporting libs. Let’s con gure our react app
so it will make use of babel transpile our code into es5. Inside your
package.json write

1 // your package.json file


2
3 "babel": {
4 "presets": [
5 "es2015",
6 "react",
7 "stage‐0"
8 ],
9 "plugins": [
10 "transform‐object‐rest‐spread"
11 ]
12 }

package‐babel.json hosted with ❤ by G i t H u b view raw

Basically, we told our app to make use of babel presets. By adding presets
now babel can understand our es6/react code and can convert it to es5.
We also installed a babel plugin which can understand the new rest/spread
operator syntax.

Let’s move on to webpack . As you already know we have to con gure the
webpack to make use of our babel loader to transpile and output our
bundle.js le.

in your project root dir create a folder named webpack

1 mkdir webpack
2 cd webpack
3 touch webpack.dev.config.js

webpack‐dir.sh hosted with ❤ by G i t H u b view raw

We created a folder named webpack and inside it created an empty le


webpack.dev.config.js .

in your webpack.dev.config.js import webpack and de ne a entry point

1 var webpack = require('webpack');


2 var path = require('path');
3
4 module.exports = {
5 e n t r y: [
6 path.join(__dirname, '../index.js')
7 ]
8 }

e n t r y ‐ p o i n t . j s hosted with ❤ by G i t H u b view raw

let’s add some loaders which will be responsible to bundle our source les.

inside your webpack.dev.config.js below entry add these lines.

1 var webpack = require('webpack');


2 var path = require('path');
3
4 module.exports = {
5 e n t r y: [
6 path.join(__dirname, '../index.js')
7 ] ,
8 m o d u l e: {
9 l o a d e r s: [{
10 t e s t: /\.(js|jsx)$/,
11 e x c l u d e: /node_modules/,
12 l o a d e r: 'babel‐loader'
13 } , {
14 t e s t: /\.less$/,
15 l o a d e r s: ["style‐loader", "css‐loader", "less‐loader"]
16 }
17 ]
18 } ,
19 }

module‐loader.js hosted with ❤ by G i t H u b view raw

As you can see we setup babel-loader for loading js/jsx les and used less-

loader for loading less les.

In order to user less-loader we also have to install style-loader and css-

loader which will directly append CSS to our index.html

we didn’t install style-loader , css-loader & less-loader before so let’s


install them.

1 npm install ‐‐save‐dev style‐loader css‐loader less‐loader


2 npm install ‐‐save‐dev less

style‐loaders.sh hosted with ❤ by G i t H u b view raw

Okay now let’s tell our webpack con g where to output our bundle.js le

1 output: {
2 path: __dirname + '/dist',
3 filename: 'bundle.js'
4 }

o u t p u t . j s hosted with ❤ by G i t H u b view raw

Our last step to end our webpack con guration will be providing the options
for our dev server.

1 devServer: {
2 contentBase: __dirname + '/dist',
3 historyApiFallback: true
4 }

devserver.js hosted with ❤ by G i t H u b view raw

Here is what our whole webpack.dev.config.js looks like I also added the
parentDir variable to make referencing our parent directory easy.

1 var webpack = require('webpack');


2 var path = require('path');
3
4 var parentDir = path.join(__dirname, '../');
5
6 module.exports = {
7 entry: [
8 path.join(parentDir, 'index.js')
9 ],
10 module: {
11 loaders: [{
12 test: /\.(js|jsx)$/,
13 exclude: /node_modules/,
14 loader: 'babel‐loader'
15 },{
16 test: /\.less$/,
17 loaders: ["style‐loader", "css‐loder", "less‐loader"]
18 }
19 ]
20 },
21 output: {
22 path: parentDir + '/dist',
23 filename: 'bundle.js'
24 },
25 devServer: {
26 contentBase: parentDir,
27 historyApiFallback: true
28 }
29 }

webpack.dev.config.js hosted with ❤ by G i t H u b view raw

Now let’s create our index.html . Inside your project root dir create an
index.html le.

1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title> Ideal React Seed </title>
5 </head>
6 <body>
7 <div id="app"></div>
8 <script type="text/javascript" src="/bundle.js"></script>
9 </body>
10 </html>

i n d e x . h t m l hosted with ❤ by G i t H u b view raw


In our index.html we have a mount point <div id="app"></div> and we also
added the source to our bundle.js le.

Next step will be building our index.js le which will be the entry point for
our webpack con guration. Inside you dir create index.js

1 import React from 'react';


2 import ReactDOM from 'react‐dom';
3
4 // main app
5 import App from './containers/App';
6
7 ReactDOM.render(<App />, document.getElementById('app'))

index.js hosted with ❤ by G i t H u b view raw

We imported react & react-dom from their respective packages. Our main
app will be inside the ./containers/App . Atlast we rendered our app into
our main html node which is <div id="app"></div> .

Now let’s quickly create an App.js to hold our whole application. Inside your
app directory create a folder named containers and inside that App.js

1 mkdir containers
2 cd containers
3 touch App.js

t o u c h ‐ a p p . s h hosted with ❤ by G i t H u b view raw

Open your App.js le inside it add this code.

1 import React, {Component} from 'react';


2
3 export default class App extends Component {
4 render () {
5 return <p>This is my new react app</p>
6 }
7 }

InitialApp.js hosted with ❤ by G i t H u b view raw

We create a simple component which will display This is my new react app

when rendered.

let’s check our app in the browser to see if it works or not.

but before that let’s add a npm script which will help us to launch the dev
server by just typing npm run dev in the console.

in your package.json inside script object add a dev script

1 "scripts": {
2 "test": "echo \"Error: no test specified\" && exit 1",
3 "dev": "./node_modules/.bin/webpack‐dev‐server ‐‐config ./webpack/webpack.dev.config.js"
4 }

dev‐script.json hosted with ❤ by G i t H u b view raw

now you are good to go.

in your console type npm run dev and goto http://localhost:8080 you will
see your app working perfectly.
App running perfectly :)

This is it for now. You can play with this setup for a while Here is the
second part where I will be using redux & react-router in this project.

Also there will be third a part as well where I will show you how to use
webpack for deploying this project from development to production.

Until then share this tutorial with everyone who can nd this tutorial
helpful.

. . .

Hi, My name is Manoj Singh Negi. I am a Javascript Developer and writer follow
me at Twitter or Github.

I am available to give a public talk or for a meetup hit me up at


justanothermanoj@gmail.com if you want to meet me.

Really loved this article ?


Please subscribe to my blog. You will receive articles like this one directly in
your Inbox frequently.

Here are more articles for you.

1. Implementing redux and react-router v4 in your react app

2. Why credibility matters?

3. Be an Artist.

4. Javascript Closures by example

5. The fundamental of everything in life

Peace.

let people know on twitter.

Manoj Singh Negi


@manojnegiwd

Setting up a #reactjs project from


scratchmedium.com/@manojsinghneg…#es6 #javascript
#programmers #webdev #webdevelopment #webpack @medium
7:30 PM - Aug 23, 2017
Setting up a React project from scratch – codeburst
Setting up a React project from scratch can be a daunting task for
beginners. Lots of npm modules to install, lots of configuration
codeburst.io

13 25 people are talking about this

JavaScript React Reactjs ES6 Webpack

One clap, two clap, three clap, forty?


By clapping more or less, you can signal to us which stories really stand out.

2K 25

Manoj Singh Negi Follow codeburst Follow


Built Bursts of code to power
http://mousecomp.com. through your day. Web
I write about Javascript Development articles,
http://eepurl.com/co0DYj tutorials, and news.
. Solving people
problems. Javascript
developer, Writer.
http://manojsinghnegi.co
m

More from codeburst More from codeburst


How to Create a Dynamic Website Why You shouldn’t use lodash
in 30 Minutes with fullpage.js anymore and use pure JavaScript…
instead
Brandon Morelli 1.1K Vladislav Stepanov 498
7 min read 4 min read

Responses

Write a response…

Conversation between Stanley Sathler and Manoj Singh Negi.

Stanley Sathler
Dec 16, 2017

One of the best topics about setting up a React application that I have ever
seen so far.

Clear, detailed, with short steps. Not tons of con gurations, just the basic.

Thank you, Manoj Singh Negi. You got a new follower.

34 1 response

Manoj Singh Negi


Dec 16, 2017

Thanks Stanley Sathler.

1
Conversation between Karthik P and Manoj Singh Negi.

Karthik P
Jan 13

Any reason for not using Facebook Incubator’s create-react-app command?

9 1 response

Manoj Singh Negi


Jan 31

Karthik P I will recommend using create-react-app. The only reason I had


written this guide is to help people understand what happens under the hood.
If we know how build system works then we can avoid a lot of problems
which will cross our path in the future. So, if I had used the create-react-app
there will be no point to write this article.

15

Conversation between Gricel Sepúlveda and Manoj Singh Negi.

Gricel Sepúlveda
Jan 30

Hi, I was following all steps and when I type “npm run dev” the browser
doesn’t start the proyect automatically, when I go manually to
http://localhost:8080 I get the following message:

“CANNOT GET /”

My project repository:

https://github.com/gricelsepulveda/react-meeta

I hope you could help me.

2 1 response

Manoj Singh Negi


Jan 31 · 1 min read

Gricel Sepúlveda In your webpack.json you added

devServer: {
contentBase: __dirname + '/dist',
historyApiFallback: true
}

But in the article the con guration of webpack is something like this

devServer: {
contentBase: parentDir,
historyApiFallback: true
}

Read more…

Conversation between Stephanie K and Manoj Singh Negi.

Stephanie K
Jan 4

Thanks for the article. Small question: When adding the dev script, why are
you refering to “./node_modules/.bin/webpack-dev-server” instead of just
“webpack-dev-server”?
12 1 response

Manoj Singh Negi


Jan 8

Stephanie K Because the webpack-dev-server is installed locally in the Project


not globally. We would write webpack-dev-server if the webpack-dev-server
installed globally by using the command npm install -g webpack-dev-server

Conversation between KuanYu Chu and Manoj Singh Negi.

KuanYu Chu
Jan 28

package.json

Isn’t it .babelrc

1 1 response

Manoj Singh Negi


Jan 31

KuanYu Chu You can either add this in your .babelrc or package.json both will
work.

Conversation between Luis Garcia and Manoj Singh Negi.

Luis Garcia
Dec 13, 2017

nice! …thanks a lot

10 1 response

Manoj Singh Negi


Dec 16, 2017

Welcome Luis Garcia

Conversation between Manohar Prabhu and Manoj Singh Negi.

Manohar Prabhu
Nov 17, 2017

Very good article, I am struggling with React Project setup, this article helps
me to setup the react and it is up and running smoothly. Thanks for you
article.

13 1 response

Manoj Singh Negi


Dec 16, 2017

Welcome Manohar Prabhu

Conversation with Manoj Singh Negi.


Hosward Villoria
Jan 20

fails,

Project is running at http://localhost:8080/


webpack output is served from /
Content not from webpack is served from /foo

404s will fallback to /index.html

1 response

Manoj Singh Negi


Jan 31

Can you explain your problem here?

Conversation with Manoj Singh Negi.

Tacy Nathan
Nov 18, 2017 · 1 min read

Doesn’t work! Throws an Error: Cannot nd module ‘webpack’ …

Pulled your code from github and bang! The same error.

Tried the following: sudo npm install -g webpack-dev-server

Addedthis package.json "scripts": {


"start": "webpack-dev-server -d --config …
Read more…

1 response

Manoj Singh Negi


Nov 18, 2017

Try doing sudo npm install -g webpack .

Conversation with Manoj Singh Negi.

codeKameleon
Jan 12

Great article. As a React newbie, helped me a lot. However, i can’t nd the


bundle.js le anywhere. Is it not supposed to go in the dist folder ? I can’t see
the le. What do i miss here ?

1 response

Manoj Singh Negi


Jan 31

codeKameleon The bundle.js le will be created when you will generate the
build using this command

./node_modules/.bin/webpack --config ./webpack/webpack.prod.config.js

Inside your project.

Show all responses


2K 25 Next story
60+ JavaScript Tutorials & Walk…

Вам также может понравиться