Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does require.ensure do in the react starter kit page routing

looking through the sample code from the react-starter-kit, I'm puzzled by what the statement require.ensure([], (require) => resolve(require('./Admin').default), 'admin'); does. I don't see that require.ensure is defined anywhere so I'm assuming it's a webpack function.

Is that an authorization check to make sure that the user has an admin role? If so, where is the user info and role info being instanciated?

Is it instead only to make sure the admin component is instanciated? What is the .default property and what is the string 'admin' being used for?

import React from 'react';
import Layout from '../../components/Layout';

const title = 'Admin Page';
const isAdmin = false;

export default {

  path: '/admin',

  async action() {
    if (!isAdmin) {
      return { redirect: '/login' };
    }

    const Admin = await new Promise((resolve) => {
      require.ensure([], (require) => resolve(require('./Admin').default), 'admin');
    });

    return {
      title,
      chunk: 'admin',
      component: <Layout><Admin title={title} /></Layout>,
    };
  },

};
like image 717
MonkeyBonkey Avatar asked Oct 18 '22 21:10

MonkeyBonkey


1 Answers

I believe require.ensure is for webpack 'chunking' or 'code splitting.' Basically it's an asynchronous way of loading components so that only the necessary components are rendered for any given page. Instead of requiring components at the top, we require them conditionally or only at certain routes. Here we don't want to load './Admin until we're sure that user is an admin. See the docs for more information.

Is that an authorization check to make sure that the user has an admin role?

I don't think so; looks to me like that's being done with if (!isAdmin).

What is the .default property and what is the string 'admin' being used for?

The 'default' property indicates that the module was exported using ES6 export default syntax. There is more than one way to export a module - with module.exports = { ... }, or with export default class SomeClass { ... }. This is something of a rabbit hole into the differences between CommonJS and ES6 (as I understand it), but this SO answer might be of interest to you.

As for the 'admin' string, that's the 'chunk name.' Again from the docs:

By passing the same chunkName to various require.ensure() calls, we can combine their code into a single chunk, resulting in only one bundle that the browser must load.

like image 181
Matthew Hinea Avatar answered Oct 21 '22 04:10

Matthew Hinea