Giter Site home page Giter Site logo

afterjs-assets's Introduction

This problem is fixed in After.js v3

you don't need this librray any more read more: https://github.com/jaredpalmer/after.js/releases/tag/v3.0.0

After.js Assets

afterjs-assets-status npm version

The Problem with After.js

If you ever tried to build an Server Side Renderd App with After.js you well notice that when you code spilit your components, After.js only send the main css and js files then in client side in ensureReady method tries to fetch javascript and css files. it's too slow (even Google PageSpeed Insights warns about it)

After.js Assets solves problem by adding a plugin to razzle and call a fucntion in custom Document file

Setup

First Install afterjs-assets:

yarn add afterjs-assets

then create a razzle.config.js file in root of project (next to the package.json) and put this content inside it:

// razzle.config.js

module.exports = {
  plugins: ["manifest"],
}

this will load razzle-plugin-manifest, this plugin will generate manifest.json file next to the server.js file in build folder. (we will use this file in next steps). checkout it's repo for more options and configuration.

Add name and chunkName to routes

// ./src/routes.js

import React from "react"
import Home from "./Home"
import { asyncComponent } from "@jaredpalmer/after"

export default [
  // normal route
  {
    name: "HomePage", // pick a random name
    path: "/",
    exact: true,
    component: Home,
  },
  // codesplit route
  {
    name: "AboutUs", // pick a random name
    path: "/about",
    exact: true,
    component: asyncComponent({
          // this must be as same as name property ๐Ÿ‘‡
      loader: () => import(/* webpackChunkName: "AboutUs" */ "./About"), // required
      Placeholder: () => <div>...LOADING...</div>, // this is optional, just returns null by default
    }),
  },
]

Note 1: name must be uniqe and all routes must have a name with uniqe value.

Note 2: we used webpackChunkName with dynamic import, chunk name Must be as same as name property.

{
  name: "AboutUs",
  path: '/about',
  component: asyncComponent({
          // this must be as same as name property ๐Ÿ‘‡
    loader: () => import(/* webpackChunkName: "AboutUs" */ './About'),
  }),
},
{
  name: "Shop",
  path: '/shop',
  component: asyncComponent({
        // this must be as same as name property ๐Ÿ‘‡
    loader: () => import(/* webpackChunkName: "Shop" */ './ShopComponent'),
  }),
},

Create Custom <Document>

Based on After.js Guide create a file in ./src/Document.js like so:

// ./src/Document.js

import React from "react"
import { AfterRoot, AfterData } from "@jaredpalmer/after"

class Document extends React.Component {
  static async getInitialProps({ assets, data, renderPage }) {
    const page = await renderPage()
    return { assets, data, ...page }
  }

  render() {
    const { helmet, assets, data } = this.props
    // get attributes from React Helmet
    const htmlAttrs = helmet.htmlAttributes.toComponent()
    const bodyAttrs = helmet.bodyAttributes.toComponent()

    return (
      <html {...htmlAttrs}>
        <head>
          <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {helmet.title.toComponent()}
          {helmet.meta.toComponent()}
          {helmet.link.toComponent()}
          {assets.client.css && (
            <link rel="stylesheet" href={assets.client.css} />
          )}
        </head>
        <body {...bodyAttrs}>
          <AfterRoot />
          <AfterData data={data} />
          <script
            type="text/javascript"
            src={assets.client.js}
            defer
            crossOrigin="anonymous"
          />
        </body>
      </html>
    )
  }
}

export default Document

Then import getAssets from afterjs-assets and call it in static getInitialProps:

Note: manifest.json will get generated at build time so don't worry if it's not already exist.

// ./src/Document.js

import manifest from '../build/manifest.json';
import { getAssests } from 'afterjs-assets';
import routes from './routes';

const prefix =
  process.env.NODE_ENV === "production"
    ? "/"
    : `http://${process.env.HOST}:${parseInt(process.env.PORT, 10) + 1}/`


class Document extends React.Component {

  static async getInitialProps({ assets, data, renderPage, req }) {
    const page = await renderPage();

    // call getAssests and pass styles and scripts to component
    const { styles, scripts } = getAssests({ req, routes, manifest });
    return { assets, data, styles, scripts, ...page };
  }

}

then in render method just loop through scripts and styles

  render() {
    const { helmet, assets, data } = this.props;
    const htmlAttrs = helmet.htmlAttributes.toComponent();
    const bodyAttrs = helmet.bodyAttributes.toComponent();

    return (
      <html {...htmlAttrs}>
        <head>
          <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {helmet.title.toComponent()}
          {helmet.meta.toComponent()}
          {helmet.link.toComponent()}
          {assets.client.css && (
            <link rel="stylesheet" href={assets.client.css} />
					)}
          {styles.map((path) => (
            <link key={path} rel="stylesheet" href={path} />
          ))}
        </head>
        <body {...bodyAttrs}>
          <AfterRoot />
          <AfterData data={data} />
          <script
            type="text/javascript"
            src={assets.client.js}
            defer
            crossOrigin="anonymous"
          />
          {scripts.map((path) => (
            <script
              key={path}
              defer
              type="text/javascript"
              src={prefix + path}
              crossOrigin="anonymous"
            />
          ))}
        </body>
      </html>
    );
  }

To use your custom <Document>, pass it to the Document option of your After.js render function.

// ./src/server.js
import express from 'express';
import { render } from '@jaredpalmer/after';
import routes from './routes';
import MyDocument from './Document';

const assets = require(process.env.RAZZLE_ASSETS_MANIFEST);

const server = express();
server
  .disable('x-powered-by')
  .use(express.static(process.env.RAZZLE_PUBLIC_DIR))
  .get('/*', async (req, res) => {
    try {
      // Pass document in here.
      const html = await render({
        req,
        res,
        document: MyDocument,
        routes,
        assets,
      });
      res.send(html);
    } catch (error) {
      console.log(error);
      res.json(error);
    }
  });

export default server;

Call ensureReady after Window Load

if we call ensureReady on browser (client), it will try to download styles and scripts for second time, (i don't know why browsers allow this). to fix this just call ensureReady on windows.onload method:

window.onload = () => {
  ensureReady(routes).then(data =>
    hydrate(
      <BrowserRouter>
        <After data={data} routes={routes} />
      </BrowserRouter>,
      document.getElementById("root")
    )
  )
}

Typescript Support

This Project Written in TypeScript and types available in index.d.ts so there is no need to install any @types/ package.

Contribution

Feel free to propose changes or open issues.

I'm really thinking about duplicate values in routes (name and webpackChunkName) but couldn't find any suitable solution.

we can use webpackChunkName with dynamic import to name chunks by requested filename.

// routes.js

function myAsyncComponentLoader(page) {
  return asyncComponent({
    loader: () => import(/* webpackChunkName: "[request]" */ `./pages/${page}`),
  })
}

const routes = [
  {
    name: "About", // About.js file which located in ./pages/About.js
    path: "/about",
  },
  {
    name: "Home", // Home.js file which located in ./pages/Home.js
    path: "/",
    exact: true,
  },
]

export default routes.map(route => {
  const { name: componentName } = route
  return { component: myAsyncComponentLoader(componentName), ...route }
})

Author


This project was bootstrapped with TSDX.


MIT License

afterjs-assets's People

Contributors

nimaa77 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.