Setting up a JS project

I’m sure the instructions for this change all the time, but at the moment this is how I set up my latest JS repo.

To create the package.json file that will contain all the meta data for your project:

yarn init

Add a linter so that you can get into the practise of writing good JS

yarn add eslint --dev

Add webpack, which will bundle all your javascript, libraries and what you have written, into a single JavaScript file.

yarn add webpack webpack-dev-server --dev

Install babel, so that you can write in whatever JS you want, and browsers will be able to read it. E.g. you can write in ES6 and Babel will translate it for you.

yarn add babel-loader babel-core babel-preset-es2015 --dev

or

npm install --save-dev babel-preset-es2015

Then set up your .babelrc file to include that preset:

{
  "presets": ["es2015"]
}

Set up your webpack.config.js – making sure to include Babel details in it.

module.exports = {
  entry: "./src/app.js",
  output: {
    filename: "./src/index.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/, 
        loader: 'babel-loader', 
        exclude: /node_modules/ 
      }
    ]
  }
}

Finally, you probably want to ignore the node_modules folder with a .gitignore file.

Set up your HTML and JS pages
Create an index.html page and an app.js. Note that the html page shouldn’t call your
app.js file, it should call whatever is the name of your output JS file in your webpack.config.js. In this case it is ./src/index.js.

Run locally
Run your app locally using hot reloading

webpack-dev-server ./src/app.js --hot --inline

You can use your linter by running

eslint ./src/app.js

Adding React

I wanted to make this repo a React App, so I added React and ReactDom

yarn add react react-dom

Then I added the Babel preset

npm install --save-dev babel-cli babel-preset-react

And updated my .babelrc

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

To get started with React I referenced a ‘root’ div in my HTML and then imported React into my App.js

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
MyElementsGoHere
,
document.getElementById('root')
);

And this is what that repo would look like at that point  

Leave a reply