npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mikojs/koa-react

v1.10.0

Published

Collect the react files to build the pages automatically.

Downloads

13

Readme

@mikojs/koa-react · npm npm-size

Collect the react files to build the pages automatically.

Install

yarn add koa react react-dom @mikojs/koa-react
yarn add --dev webpack

Use @mikojs/koa-react to server

  1. Add the middleware to server.
import Koa from 'koa';
import React from '@mikojs/koa-react';

const app = new Koa();
const react = new React('./path-to-react-folder');

(async () => {
  app.use(await react.middleware());
})();
  1. Write the react file in the ./path-to-react-folder.
// @flow

export default () => 'Home';

You can see here to lerna more about writing the components.

Update page with babel watch

const react = new React('./path-to-react-folder');

chokidar
  .watch('./path-to-react-folder', {
    ignoreInitial: true,
  })
  .on('change', (filePath: string) => {
    react.update(filePath);
  });

With the custom options

const react = new React('./path-to-react-folder', {
  dev: true,
  headler: routesData => routesData, // use to handle the all routes data. You can use this to sort the path or add the custom routeData.
  basename: '/basename',
  exclude: /ignore/,
});

Give the options to koa-webpack

You can get the defailt config options from the argument and you need to return the new config options to the middleware.

const react = new React('./path-to-react-folder', {
  config: prevConfig => newConfig,
});

Use to build js

  1. Write a bin file or make server file to be a bin file.
#! /usr/bin/env node

import Koa from 'koa';
import React from '@mikojs/koa-react';

const app = new Koa();
const react = new React('./path-to-react-folder');

(async () => {
  if (process.env.BUILD_JS) {
    await react.buildJs();
    process.exit();
  }

  app.use(await react.middleware());
})();
  1. Run command with the bin file.
BUILD_JS=true node ./server.js

Use to build the static files

  1. Write a bin file or make server file to be a bin file.
#! /usr/bin/env node

import Koa from 'koa';
import React from '@mikojs/koa-react';

const app = new Koa();
const react = new React('./path-to-react-folder');

(async () => {
  if (process.env.BUILD_STATIC) {
    await react.buildStatic();
    process.exit();
  }

  app.use(await react.middleware());
})();
  1. Run command with the bin file.
BUILD_STATIC=true node ./server.js
With the custom options
...
await react.buildStatic({
  baseUrl: 'http://localhost:8000',
  folderPath: path.resolve('./custom-output-dir'),
});
...

How to write the components

This middleware is like next.js. However, this middleware is base on react-router-dom, react-helmet and koa-webpack. You can use all the feature of those library.

Page component

Each component will be used to build the page like next.js. If you want to use the url parameters, you can add a file like [foo].js or make a folder like [foo]. Then, you can get the variables from the match in the arguments of the getInitialProps. You can see here to lerna the more information about match.

export default class Page extend React.PureComponent {
  /**
   * This function is optional. You only need to add this function when you need to get the initial props or set the helmet.
   *
   * @param {ctx} ctx - koa context in server and react-router-dom context in client
   * @param {boolean} isServer - is in Server or not
   *
   * @return {object} - the initial props and head(optional)
   */
  static getInitialProps = ({ ctx, isServer }) => {
    // do some thing

    return { ... };
  };

  render() {
    const { ...initialProps } = this.props;

    return (
      <div>...</div>
    );
  }
}

.template folder

In your pages folder, you can add a .templates folder to add ths custom template component. You can see the default templates here to lerna more about how to write the custom template component.

In our components, we use react-helmet to build the head of the document. You can use this in Documenet, Main and the page components to control the head of the document.

Document

Only run in the server. Use to add meta, scripts and so on, and you can get the react-helmet object from the props.

export default class Document extend React.PureComponent {
  /**
   * This function is optional. You only need to add this function when you need to get the initial props or set the helmet.
   *
   * @param {ctx} ctx - koa context
   * @param {boolean} isServer - is in Server or not
   *
   * @return {object} - the initial props and head(optional)
   */
  static getInitialProps = ({ ctx, isServer }) => {
    // do some thing

    return { ... };
    // or
    return {
      head: (
        <Helmet>
          <title>mikojs</title>
        </Helmet>
      )
    };
  };

  render() {
    const { helmet, children, ...initialProps } = this.props;

    return (
      <html>
        <head>
          {helmet.meta.toComponent()}
          {helmet.title.toComponent()}
          {helmet.link.toComponent()}
        </head>

        {...}
        {children}
      </html>
    );
  }
}
Main

The main component is used to controll the providers and you can get the page Component from the props.

export default class Main extend React.PureComponent {
  /**
   * This function is optional. You only need to add this function when you need to get the initial props or set the helmet.
   *
   * @param {ctx} ctx - koa context in server and react-router-dom context in client
   * @param {boolean} isServer - is in Server or not
   * @param {Component} Component - page component
   * @param {Object} pageProps - page inital props
   *
   * @return {object} - the initial props and head(optional)
   */
  static getInitialProps = ({ ctx, isServer, Component, pageProps }) => {
    // do some thing

    return { ... };
    // or
    return {
      head: (
        <Helmet>
          <title>mikojs</title>
        </Helmet>
      )
    };
  };

  render() {
    const { Componet, children, ...initialProps } = this.props;

    return (
      <div>
        ...
        {children(/** you can pass the data to page component */)}
      </div>
    );
  }
}
Error

When component trigger componentDidCatch, this will not render the page. It will render Error.

const Error = (
  { error, errorInfo } /** the data from componentDidCatch in react */,
) => <div>...</div>;

export default Error;
Loading

When page is changed, this will render Loading. We use Loading with react suspense.

const Loading = () => <div>...</div>;

export default Loading;

Use in the unit testing

import React from '@mikojs/koa-react';

const react = new React('./path-to-react-folder');

test('test', async () => {
  expect((await react.render('/')).contains('<div />')).toBeTruthy();

  // or add root props
  expect((await react.render('/', rootProps)).contains('<div />')).toBeTruthy();
});

You can see rootProps to lerna the more information.