Showing posts with label ReactJs. Show all posts
Showing posts with label ReactJs. Show all posts

Saturday, April 13, 2019

How to add tools for unit testing in react js project ?

Below are the packages and command which need to be installed for unit testing in reactjs app.

yarn add jest enzyme react-test-renderer enzyme-adapter-react-16

I have used several packages which are:

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

Enzyme is a JavaScript Testing utility for React that makes it easier to test React Components' output.

React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.

Enzyme adapter has peer dependencies on react and react-dom.

Tuesday, March 19, 2019

ReactJs Component Life Cycle - Creation/Update

Creation:

constructor() // Call super(props), Do: Set up State, Don't: Cause Side-Effects

getDerivedStateFromProps() // Do: Sync state, Don't: Cause Side-Effects

render() // Prepare & Structure JSX Code

Render Child Components //

componentDidMount() // Do: Cause Side-Effects, Don't: Update State (triggers re-render)

Update:

getDerivedStateFromProps(props, state) // Do: Sync state to props, Don't: Cause Side-Effects

shouldComponentUpdate(nextProps, nextState) // Do: Decide whether to continue or not, Don't: Cause side-effects

render() // Prepare & Structure JSX Code

Render Child Components //

getSnapshotBeforeUpdate(prevProps, prevState) // Do: Last minute DOM ops, Dont: Cause side-effects

componentDidUpdate() // Do: Cause Side-Effects, Don't: Update State (triggers re-render)

Friday, August 24, 2018

How To Setup GraphQL With NodeJs

We know about RESTFul API which has some complexity in different cases, for example nested http request like domain.com/api/user/frinds/positions/companies and also mutiple http requests concurrently which make the server slow down. And of-course chunk of information instead of full model.

To overcome such problems, GraphQL comes which is a query language for API and querying data as runtime.

To setup GraphQL with NodeJs following steps need to be followed:

npm init 

the above command is to initiate NodeJs environment.

npm install --save express express-graphql graphql lodash

through the above command we will install some dependency packages like express for NodeJs server express-graphql the middleware or bridge layer between express and graphql and lodash is for some utility features.

After installing dependency packages above we need to create express server by creating a file named server.js and add code as follows:

const express = require('express');
const expressGraphQL = require('express-graphql');

const app = express();

app.use('/graphql', expressGraphQL({
    graphiql: true
}));

app.listen(4000, () => {
    console.log('Listening');
});

in the above code we have created express nodejs http server to listen the port number 4000 and then bound graphql middleware with expressjs.

Tuesday, August 21, 2018

Configuring Webpack for Development Purpose


In my earlier post I have discussed about the installation of webpack and webpack-dev-server for a project. In this post I will discuss how to start/run webpack dev server configuring with webpack. To do so, first of all we need to add a command in scripts of package.json file as follows:

"start": "webpack-dev-server"

Make sure “webpack-dev-server” is the package name installed under devDependencies. And the full scripts will be looked like below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server"
  },

When we run npm start command the “webpack-dev-server” will be executed but it will seek a webpack config file which need to be created in the project root folder and the name should be webpack.config.js. We will add some configuration settings in this file as follows:

const path = require('path');
const autoprefixer = require('autoprefixer');
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    devtool: 'cheap-module-eval-source-map',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        chunkFilename: '[id].js',
        publicPath: ''
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: [
                    { loader: 'style-loader' },
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 1,
                            modules: true,
                            localIdentName: '[name]__[local]__[hash:base64:5]'
                        }
                     },
                     {
                         loader: 'postcss-loader',
                         options: {
                             ident: 'postcss',
                             plugins: () => [
                                 autoprefixer({
                                     browsers: [
                                        "> 1%",
                                        "Last 2 versions"
                                     ]
                                 })
                             ]
                         }
                     }
                ]
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                loader: 'url-loader?limit=8000&name=images/[name].[ext]'
            }
        ]
    },
    plugins: [
        new htmlWebpackPlugin({
            template: __dirname + '/src/index.html',
            filename: 'index.html',
            inject: 'body'
        })
    ]
};

In the above configuration code “devtool” is used to generate source map. The “entry” option is used to set entry point from where the webpack should start. And “output” option is used to set output location and filename of “bundle.js” that is the compressed version of all js into a single file. 

The “resolve” key is using for automatically finding extensions like .js or .jsx if we don’t add these extension with the file location while importing into the react code. 

The “module” key is used to add some rules on js/css or other files excluding certain unnecessary files to be optimized.

We also need to install some dependencies which are needed for this configuration as follows:

npm install –save-dev css-loader style-loader postcss-loader autoprefixer url-loader file-loader webpack-cli html-webpack-plugin rimraf

We also need to config babel which can found through this link below:


Monday, August 20, 2018

Configuring Babel with A Project

Babel is one of the architecture of modern javascript eco-system which works as a transpiler or converter to compile next generation javascript code to be worked with older browser. To work with babel we need to configure with the project. First of all we need to create babel config file in the project root folder as follows:

.babelrc

before going with the settings we need to install all the dependencies of babel using npm package as follows:

npm install --save-dev babel-loader babel-core babel-preset-react babel-preset-env babel-plugin-syntax-dynamic-import babel-preset-stage-2 babel-polyfill 

After installing babel dependencies we need to set those presets we have installed as npm package as follows:

{
    "presets": [
        ["env", {
            "targets": {
                "browsers": [
                    "> 1%",
                    "Last 2 versions"
                ]
            },
            "useBuiltIns": "entry"
        }],
        "stage-2",
        "react"
    ],
    "plugins": [
        "syntax-dynamic-import"
    ]
}

In the above settings we have added "env" preset to support target browsers from minimum to maximum version of browsers. Then we have added "react" preset to work with react jsx and next generation javascript code.

Sunday, August 19, 2018

Installing ReactJs Production Dependencies


It is crucial to know production dependencies for ReactJs application. And here are some listed as follows:

react
react-dom
react-router-dom

We basically import React for JSX and Component for class or container based component from dependency 'react'.

ReactDOM to render entry point component into DOM from 'react-dom' and Link, BrowserRouter from 'react-router-dom'.

Since these are production dependencies so we can install using npm package adding white spaces as follows:

npm install --save react react-dom react-router-dom

Wednesday, August 15, 2018

How to set up webpack for a project?

In one of my project I needed to work with webpack and for this I need to install webpack and other dependency modules using npm package as follows:

npm init
npm install --save-dev webpack webpack-dev-server

in above two commands the first one is to set up node package configuration file the package.json to install node modules.

And the second line is to install depedency modules like webpack and webpack-dev-server which is the developement server to test the application locally.