Skip to content

Instantly share code, notes, and snippets.

@developit
Last active March 10, 2021 14:38
Show Gist options
  • Save developit/0c523c74237d3b4d0209867897b48716 to your computer and use it in GitHub Desktop.
Save developit/0c523c74237d3b4d0209867897b48716 to your computer and use it in GitHub Desktop.

suspense-loader

Installation (sorry)

npm i THIS_URL

Usage

import Burger from 'suspense-loader!./burger';

const Sidebar = (props) => (
  <React.Suspense fallback={<span>loading...</span>}>
    <Burger {...props} />
  </React.Suspense>
);

Automatic Route-based Code Splitting

// webpack.config.js
module: {
  rules: [
    {
      test: /src\/routes\/[^/](\/index)?\.[jt]sx?$/,
      loader: 'suspense-loader'
    }
  ]
}
{
"name": "suspense-loader",
"version": "0.1.0",
"main": "suspense-loader.js",
"dependencies": {
"loader-utils": "*"
}
}
const loaderUtils = require('loader-utils');
module.exports = function () {};
module.exports.pitch = function (remainingRequest) {
this.cacheable && this.cacheable();
const query = loaderUtils.getOptions(this) || {};
const name = typeof query.name=='function' ? query.name(this.resourcePath) : query.name;
const chunkName = name ? ` /* webpackChunkName: ${JSON.stringify(name)} */` : '';
return `
import React from 'react';
export default React.lazy(
() => import(${loaderUtils.stringifyRequest(this, "!!" + remainingRequest)}${chunkName})
);
`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment