Categories
JavaScript

Good NPM Packages You May Have Missed

NPM packages are used by both browser and Node.js apps alike. NPM is the biggest repository of JavaScript libraries.

In this article, we’ll look at the popular JavaScript packages on NPM.

q

A promise library to let us create promises without the native promise implementation.

This is useful when we didn’t have promises natively built into JavaScript.

ramda

A utility library with functional programming methods.

It includes many methods like array manipulation methods, string manipulation methods, math methods, and much more.

They’re all written and used in a functional way.

ora

The ora library lets add a spinner to the command line Node programs to indicate loading.

file-loader

The Webpack file-loader plugin lets us load static files into our front end apps.

We’ll need it to load images and other static resources within our JavaScript code.

eslint-plugin-import

A ESLint plugin that checks for how we write import and exporter statements in modules.

It’s very handy for checking the syntax automatically so that we don’t make mistakes and commit back practices when writing and using JavaScript modules.

styled-components

A React library that lets us create HTML elements and components that are styled and can be used with React.

It supports static and dynamic styles.

And we create a component by writing out the styles and there transforming them to React components with the functions that are built into the library.

eslint-plugin-react

An ESLint plugin for checking React syntax.

It’s great for helping us from committing syntax errors and bad practices in React apps.

Checks include prop types, names, destructuring assignments, and a lot more.

request-promise

Request-Promise is an HTTP client that lets us make HTTP requests with promises.

It can use native promises or any-promise as the promise to use with the request-promise-native and request-promise-any respectively.

handlebars

Handlebars is a template engine that we can use on templates for various frameworks like Express or Koa.

It includes template tags that we can use to render arrays and conditionally render items as we wish to.

jsonwebtoken

The jsonwebtoken package lets us create JSON web tokens that are secure.

We can sign tokens with them with various expiry dates.

It can encode any object to tokens.

Also, then token issued can expire at any time that we wish.

It also has the functionality to verify tokens.

mongoose

Mongoose is an ODM library for letting us read and write MongoDB documents easier than with the MongoDB library.

We can specify models with data types and constraints so that we can specify models together so that we can always save the right kind of data.

Not only can we specify the type, but we can also specify the format of the data with regex.

url-loader

We can use the url-loader Webpack plugin to load base64 URLs as images with our JavaScript apps.

gulp

Gulp is a package that lets us build JavaScript files automatically without hassle.

We can write many kinds of automated build tasks without running all the commands ourselves.

The tasks can be run in series or in parallel as we wish to.

Also, there’re many plugins written for it so that we don’t have to write tasks ourselves all the time.

Plugins or concatenation, uglifying code is available.

mongodb

MongoDB is the official MongoDB driver for Node.js

It can be used to do common CRUD operations.

@babel/polyfill

If we’re targeting browsers that don’t have full ES6 support, then we can use babel-polyfill to add the polyfills needs to run ES6 code in unsupported browsers.

It includes new array methods, string methods, support for syntaxes like spread and rest, maps, sets, and much more.

object-assign

object-assign is a polyfill for the Object.assign method.

It’s very handy for copying and merging objects.

ws

A WebSocket client and server made for Node apps.

It supports many options like compression, concurrency, sending various kinds of data, and more.

It also works with Node’s HTTP server.

The client is also made for Node apps and can be used to connect to any WebSocket server.

Conclusion

Polyfills, WebSocket libraries, and spinners are all great packages that we can use in our Node apps.

Also, MongoDB is a popular choice for some use cases as we can see from their popularity in NPM.

Categories
JavaScript

Top NPM Packages You May Have Missed

NPM packages are used by both browser and Node.js apps alike. NPM is the biggest repository of JavaScript libraries.

In this article, we’ll look at the top JavaScript packages on NPM.

lodash

Lodash is the most popular utility library used in JavaScript programs.

It lets us do math operations, manipulate objects, and work with arrays easily.

Some of them have plain JavaScript equivalents, but there’re many that still have no equivalent in the JavaScript standard library.

Therefore, it’s still a useful library for many JavaScript projects.

react

React is one most of the most popular JavaScript libraries for building browser web apps.

It has its own unique JSX syntax which lets us manipulate the DOM in an easy way.

Therefore it’s one library that we should learn how to use if we want to be a front end developer.

chalk

Chalk is a library for Node.js command-line apps to let us style text the way we want them to be displayed on the screen.

We can set colors, and compose styles easily with it.

request

Request is an HTTP client that can be used in Node.js apps.

We can make HTTP and HTTPS requests with it. Headers, bodies, and responses can all be processed with this library.

However, it’s deprecated so we may want to find another library like Axios for making HTTP requests.

commander

Commander lets us run shell command automatically within a Node.js program.

It allows us a lot more flexibility than running with commands with spawn or other built-in Node.js programs for running child processes within a Node program.

moment

Since the JavaScript Date constructor is deficient in features, many JavaScript date manipulation libraries have been made to address the issues with it.

One of them is the moment.js library. We can use it to parse date strings, add and subtract dates, get elapsed time, and do many other things that are hard with the native Date contructor.

express

Express is a micro-framework for building back end web apps.

It works by chaining together a bunch of middleware that are bound together by the Express framework.

It’s very basic. All it has is routing and abilities to listen to HTTP requests out of the box.

Anything else has to be done with its own middleware, 3rd party middleware, or we can write our own.

react-dom

React DOM is a core library that goes with React. It lets React manipulate the DOM so that we can mount our app into a web page so that the React app can be run.

prop-types

Prop-types is the library for validation prop types of React components.

We can watch the value of the props and validate them as they’re being passed in from parent components.

By default, we can pass in any values as props, which isn’t good since it’s error-prone as there’s no validation for data types or formats.

This library lets us do the required validation so that we can deal with props easier.

debug

The debug library is used for making debugging Node apps easier.

We can just include this library and use it to add debug messages in the places that we wish to find out what’s going on with our app.

fs-extra

fs-extra has file manipulation methods that aren’t present in the Node’s built-in fs module.

It includes methods for copying files, making directories, checking for empty directories, reading JSON, and more.

Both synchronous and promise-based versions of the methods are available.

axios

Axios is a popular HTTP client that can be used by browser and Node apps.

We can make any kind of HTTP request with it with various HTTP headers, and bodies.

Also, it can handle different kinds of responses with ease, including text and JSON, binary responses.

It also has HTTP interceptors to let us configure requests before they’re made, thereby eliminating repetition.

async

The async library has methods for doing various operations asynchronously, including iteration, filtering, concatenation, mapping values, and much more.

It has many other methods for control for and error handling, all done asynchronously.

Conclusion

We can do a lot with the top libraries.

They can be used to make full-featured front end and back end apps when we incorporate them with other supporting libraries.

We can make simple apps just with these libraries alone.

Categories
Vue 3

Vue Router 4–Per-Route Transition and Fetch Data During Navigation

Vue Router 4 is in beta and it’s subject to change.

To build a single page app easily, we got to add routing so that URLs will be mapped to components that are rendered.

In this article, we’ll look at how to use Vue Router 4 with Vue 3.

Per-Route Transition

We can add transition effects for individual routes.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
    <style>
      .fade-enter-active,
      .fade-leave-active {
        transition: opacity 0.15s ease;
      }
      .fade-enter-from,
      .fade-leave-to {
        opacity: 0;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar">bar</router-link>
      </p>
      <router-view v-slot="{ Component, route }">
        <transition :name='route.path.includes("foo") ? `fade`:``'>
          <component :is="Component" />
        </transition>
      </router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>bar</div>"
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar",
          component: Bar
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });
      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

We set the name prop dynamically by checking the route object.

The path property has the path of the route.

Therefore, we can check the path to set the value of name to the transition we want.

Data Fetching

We sometimes want to fetch data from the server when a route is activated.

This can be done with various hooks.

For instance, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar">bar</router-link>
      </p>
      <router-view></router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>{{bar}}</div>",
        data() {
          return {
            bar: ""
          };
        },
        created() {
          this.fetchData();
        },
        watch: {
          $route: "fetchData"
        },
        methods: {
          async fetchData() {
            this.bar = "bar";
          }
        }
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar",
          component: Bar
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });
      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

We watch the $route object and call the fetchData method when $route changes.

Fetching Before Navigation

We can also run methods to fetch data in the before before navigation hooks.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar/1">bar 1</router-link>
        <router-link to="/bar/2">bar 2</router-link>
      </p>
      <router-view></router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>{{id}}</div>",
        data() {
          return {
            id: ""
          };
        },
        beforeRouteEnter(to, from, next) {
          next((vm) => vm.fetchData(to.params.id));
        },
        beforeRouteUpdate(to, from, next) {
          this.fetchData(to.params.id);
          next();
        },
        methods: {
          async fetchData(id) {
            this.id = id;
          }
        }
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar/:id",
          component: Bar
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });
      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

We have the beforeRouterEnter and beforeRouteUpdate hooks that runs before the component is rendered and when the route params change respectively.

The fetchData method is run in the callback to get the data.

We have 2 router-link that goes to the /bar route with its own parameter.

We get the id parameter in the navigation guard methods and called fetchData to set its value to the this.id state.

Therefore, we’ll see them in the template.

Conclusion

We have a new way to add per-route transition with Vue Router 4.

Also, we can fetch data in Vue Router hooks with Vue Router 4.

Categories
Vue 3

Vue Router 4–Navigation Guards

Vue Router 4 is in beta and it’s subject to change.

To build a single page app easily, we got to add routing so that URLs will be mapped to components that are rendered.

In this article, we’ll look at how to use Vue Router 4 with Vue 3.

Navigation Guards

We can add navigation guards to guard navigation by redirecting or canceling it.

The guards are only triggered when we navigate to different routes.

URL parameters and query changes won’t trigger enter or leave navigation guards.

Global Before Guards

We can add a global before guard by passing a callback to the router.beforeEach method.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar">bar</router-link>
      </p>
      <router-view></router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>bar</div>",
        props: ["id"]
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar",
          component: Bar
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });

      router.beforeEach((to, from, next) => {
        console.log(to, from);
        next();
      });
      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

We call the router.beforeEach method with a callback.

The callback takes a to , from and next parameters.

to is a route object being navigated to.

from is a route object being navigated away from.

A route object has the fullPath , metadata, query parameters, URL parameters, and more.

next is a function that must be called to resolve the hook.

We need to call next to show the to route.

The next function can take an argument.

If we pass in false , then the current navigation is aborted.

If the browser URL is changed, then it’ll reset to the one in the from route.

We can also pass in a path string or an object with the path property with the path string.

Either way, we redirect to a different location.

The current navigation is aborted and a new one will be started.

The object can have extra options like the replace and name properties from the route.

Any properties that are accepted by router.push is accepted.

We can also pass in an Error instance if there are any errors.

Then the navigation will be aborted and the error will be passed to callbacks registered with router.onError().

We should make sure that next is called exactly once in the callback.

Otherwise, the navigation may never resolve or errors may result.

So instead of writing:

router.beforeEach((to, from, next) => {
  if (to.name !== 'login' && !isAuthenticated) {
    next({ name: 'login' })
  }
  next()
})

We write:

router.beforeEach((to, from, next) => {
  if (to.name !== 'login' && !isAuthenticated) {
    next({ name: 'login' });
  }
  else {
    next();
  }
})

Global Resolve Guards

We can register a global guard with router.beforteResolve .

It’s similar to router.beforeEach except that it’ll be called right before the navigation is confirmed.

Conclusion

We can add navigation guards to control navigation with Vue Router 4.

Categories
Vue 3

Vue Router 4–Navigation Guard Hooks

Vue Router 4 is in beta and it’s subject to change.

To build a single page app easily, we got to add routing so that URLs will be mapped to components that are rendered.

In this article, we’ll look at how to use Vue Router 4 with Vue 3.

Global After Hooks

We can create global after navigation hooks.

To do that, we call the router.afterEach method with a callback.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar">bar</router-link>
      </p>
      <router-view></router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>bar</div>"
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar",
          component: Bar
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });

      router.afterEach((to, from) => {
        console.log(to, from);
      });
      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

to add our after navigation hook.

It’s called after we navigated to the route.

to is a route object being navigated to.

from is a route object being navigated away from.

A route object has the fullPath , metadata, query parameters, URL parameters, and more.

There’s no next function to let us do redirects or throw errors.

Per-Route Guard

We can add navigation guards per route.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar">bar</router-link>
      </p>
      <router-view></router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>bar</div>"
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar",
          component: Bar,
          beforeEnter: (to, from, next) => {
            console.log(to, from);
            next();
          }
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });

      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

We have the beforeEnter method in the /bar route object.

The next function lets us resolve the navigation since it’s run before we enter the route.

In-Component Guards

We can add navigation guards inside a component.

For example, we can write:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/vue-router@4.0.0-beta.7/dist/vue-router.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <p>
        <router-link to="/foo">foo</router-link>
        <router-link to="/bar">bar</router-link>
      </p>
      <router-view></router-view>
    </div>
    <script>
      const Foo = {
        template: "<div>foo</div>"
      };
      const Bar = {
        template: "<div>bar</div>",
        beforeEnter(to, from, next) {
          console.log(to, from);
          next();
        },
        beforeRouteUpdate(to, from, next) {
          console.log(to, from);
          next();
        },
        beforeRouteLeave(to, from, next) {
          console.log(to, from);
          next();
        }
      };
      const routes = [
        {
          path: "/foo",
          component: Foo
        },
        {
          path: "/bar",
          component: Bar
        }
      ];
      const router = VueRouter.createRouter({
        history: VueRouter.createWebHistory(),
        routes
      });

      const app = Vue.createApp({});
      app.use(router);
      app.mount("#app");
    </script>
  </body>
</html>

to add the navigation guards to our Bar component.

The beforeRouteEnter method is called before that renders the component is confirmed.

It doesn’t have access to this component instance since it hasn’t been created yet.

The beforeRouterUpdate method is called when the route that renders the component has changed.

For instance, when a route with dynamic parameters changed, then it’ll be run.

It has access to the this component instance.

beforeRouterLeave is called when the route that renders the component is about to be navigated from.

It also has access to the this component instance.

Conclusion

We can add navigation guard hooks in various locations with Vue Router 4.