React: configuring webpack.config.js for production

First of all, here we will be using es6 syntax so we will need to rename our webpack.config.js file to webpack.config.babel.js so that it can be compiled.

Once we do so, we can use import instead of require and export default {} instead of module.exports = {}

Then we need to add the following:

Import webpack:

import webpack from 'webpack'

Check for production:

const LAUNCH_COMMAND = process.env.npm_lifecycle_event

const isProduction = LAUNCH_COMMAND === 'production'

const productionPlugin = new webpack.DefinePlugin({
  'process.env': {
    NODE_ENV: JSON.stringify('production')
  }
})

Add common properties such as ‘base’, ‘output’, and ‘module’ in base json:

const base = {
  entry: [ ... ],
  output: { ... },
  module: {
    loaders: [ ... ]
  }
}

Specify dev and production configs:

const devConfig = {
  plugins: [...]
}

const productionConfig = {]
  plugins: [productionPlugin, ...]
}

Merge objects to export:

export default Object.assign({}, base,
  isProduction === true
    ? productionConfig
    : devConfig
)
Advertisements

Using eslint with react

When developing a big project in React, it is important to maintain some standard code practises. This is where lint comes in. I will be using the common standardjs.com rules in the article.

NPM

In your project install the following commands using npm:

npm install --save-dev eslint eslint-{config-standard,plugin-standard,plugin-promise,plugin-import,plugin-node,plugin-react}
npm install --save-dev babel-eslint@next

.eslintrc

In your project root add a file called ‘.eslintrc’ and add the following json:

{
  parser: "babel-eslint",
  env: {
    es6: true,
    "browser": true
  },
  parserOptions: {
    ecmaversion: 6,
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
      experimentalObjectRestSpread: true
    }
  },
  extends: ["eslint:recommended","plugin:react/recommended","standard"],
  plugins: [
    "react"

  ]
}

Parser will be used to specify that we need to parse lint using babel, for which we installed theĀ babel-eslint@next in npm.

Env and parserOptions are optional and will simply specify the env options that lint may encounter during parsing.

Extends is the most important since it will specify what kind of rules will be set. You can use only “standard” if you would like however both eslint and react lint plugin come with inbuilt recommendations that I decided to use above too.

Plugins above is simply there to tell lint that react is used to avoid getting react errors such as unused imports etc.

package.json

In our package.json, add 2 scripts that will help you use lint quicker:

"scripts": {
  "lint": "eslint app/.",
  "fix": "eslint --fix app/.; exit 0;"
}

“lint” script will check for errors while “fix” script will TRY to auto fix as many errors/warnings as possible such as end of file line, extra spacings, etc.