I'm trying to learn ReactJS and I'm finding a lot of tutorials confusing because they layer NodeJS, Babel, and Webpack into their explanations all at once and gloss over a lot of what's going on. I'm trying to do a basic Hello World app and add these tools one at a time so I can understand what is doing what better.
I start with a basic static HTML and JS file:
index.html:
<!DOCTYPE html>
<html>
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="index.js"></script>
</body>
</html>
index.js (not using JSX yet):
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
}
}
ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('app')
);
Okay so this works as expected. Now I want to set up a NodeJS project that serves this exact content so I start with:
npm init -y
And that gives me a package.json. How do I configure NodeJS to serve this basic Hello World code at say localhost:8080? My next step would be to add Babel so I can use JSX, but I don't want to skip to that step until I understand the server setup better.
The simplest way would be using a lib like node-static (npm install node-static --save-dev
) and adding it as the start
script in your package.json
"scripts": {
"start": "static ./"
},
Start it with the npm start
command.
Though this will work, if you plan to add babel I highly recommend you to jump into webpack (or any other build tool, I personally think webpack is the best option) because webpack already have a development server that will serve static files during development for you ( witch a lot of goodies like hot reload ) and webpack is not that hard to learn, the official documentation is somewhat difficult for beginners, I recommend you to read this how-to first.