1.2.1 • Published 3 years ago

quasar-app-extension-ssg-fork v1.2.1

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

Static Site Generator App Extension for Quasar, the Vue.js Framework

A Quasar App Extension to generate static site AKA JAMstack.

npm GitHub code size in bytes GitHub repo size npm David Commitizen friendly

This project was created to fill this Feature Request from Quasar.

Installing | Uninstalling | Upgrading | Developing | Usage | Configuration | Infos

Installing

Run this command into your Quasar project:

quasar ext add ssg

This will find and install the extension’s module. After installation is complete, there will be prompts asking you to make choices.

Prompts

  • add scripts into your package.json?: Extends your package.json by adding scripts.

    scripts: {
      'build:ssg': 'quasar ssg generate',
      'serve:ssg': 'quasar ssg serve dist/ssg'
    }
  • inline critical CSS?: Use a fork of Critters to generate critical CSS, inline it and lazy load stylesheets for each route generated.

Uninstalling

quasar ext remove ssg

Upgrading

This is done with the same command as used for installation:

quasar ext add ssg

If you are upgrading this extension from not yet published to NPM versions (before v1.0.0), you probably need to clean the extension from the yarn global cache, before upgrading it.

yarn remove quasar-app-extension-ssg

yarn cache clean quasar-app-extension-ssg

quasar ext add ssg

Developing

To help developing the extension, start by cloning this repository:

git clone https://github.com/freddy38510/quasar-app-extension-ssg.git && cd quasar-app-extension-ssg

Register the App Extension through yarn:

yarn link

Create a new Quasar project then link the App Extension:

quasar create <project-name> && cd <project-name>

yarn link quasar-app-extension-ssg

Finally install the App Extension:

quasar ext invoke ssg

Now, you can developp this App Extension without uninstall/install it each time you change something in it.

Usage

Generate

To generate a static site run this command from your quasar project folder:

quasar ssg generate

Do not forget to set the routes you want to generate in the configuration.

Generate Options

  • -h, --help: Display usage instructions.
  • --force-build: Force to build the application with webpack.
  • --fail-on-error: Exit with non-zero status code if there are errors when generating pages.
  • -d, --debug: Build for debugging purposes.

Serve

This extension provides a command to create a server for testing your static site locally:

quasar ssg serve <dist-folder>

Notes: This server is based on the Quasar cli server adapted for static site. It handles SPA or PWA fallback.

Serve Options

  • --port, -p: Port to use (default: 4000).
  • --hostname, -H: Address to use (default: 0.0.0.0).
  • --prefix-path: Create a virtual path prefix (default: /).
  • --gzip, -g: Compress content (default: true).
  • --silent, -s: Suppress log message.
  • --colors: Log messages with colors (default: true).
  • --open, -o: Open browser window after starting.
  • --cache, -c <number>: Cache time (max-age) in seconds. Does not apply to /service-worker.js (default: 86400 - 24 hours).
  • --micro, -m <seconds>: Use micro-cache (default: 1 second).
  • --https: Enable HTTPS.
  • --cert, -C [path]: Path to SSL cert file (Optional).
  • --key, -K [path]: Path to SSL key file (Optional).
  • --proxy <file.js>: Proxy specific requests defined in file. File must export Array ({ path, rule }). "rule" is defined at: https://github.com/chimurai/http-proxy-middleware/tree/v0.19.1#readme.

    module.exports = [
      {
        path: '/api',
        rule: { target: 'http://www.example.org' },
      },
    ]
    // will be transformed into app.use(path, httpProxyMiddleware(rule))
  • --cors: Enable CORS for all requests.

  • --help, -h: Display usage instructions.

Inspect

This command can be used to inspect the Webpack config generated by this app extension.

quasar ssg inspect

Inspect Options

  • -d, --depth: Number of levels deep (default: 5).
  • -p, --path: Path of config in dot notation.

    Examples:

    quasar ssg inspect -p module.rules
    quasar ssg inspect -p plugins
  • -h, --help: Display usage instructions.

Configuration

You can pass options with ssg key in /quasar.conf.js.

// quasar.conf.js

module.exports = function (/* ctx */) {
  return {
    // ...

    ssg: {
      // pass options here
    },

    // ...
  }
}

See all availables options below:

concurrency

Type: Number

Default: 10

The generation of routes are concurrent, ssg.concurrency specifies the amount of routes that run in one thread.

interval

Type: Number

Default: 0

Interval between two render cycles to avoid flooding a potential API with API calls from the web application.

routes

Type: String[] or Function

Default: ['/']

An Array of Strings for routes to be generated.

Example:

ssg: {
  routes: ['/', '/about', '/users', '/users/someone']
}

With a Function which returns a Promise:

// quasar.conf.js

const axios = require('axios')

module.exports = function (/* ctx */) {
  return {
    // ...

    ssg: {
      routes() {
        return axios.get('https://my-api/users').then((res) => {
          return res.data.map((user) => {
            return '/users/' + user.id
          })
        })
      },
    },

    // ...
  }
}

With a Function which returns a callback(err, params):

// quasar.conf.js

const axios = require('axios')

module.exports = function (/* ctx */) {
  return {
    // ...

    ssg: {
      routes(callback) {
        axios
          .get('https://my-api/users')
          .then((res) => {
            const routes = res.data.map((user) => {
              return '/users/' + user.id
            })
            callback(null, routes)
          })
          .catch(callback)
      },
    },

    // ...
  }
}

buildDir

Type: String

Default: '<project-folder>/node_modules/.cache/quasar-app-extension-ssg' or '<project-folder>/.ssg-build' if cache is set to false.

The webpack build output folder from where the extension can prerender pages.

cache

Type: Object or false

Default:

{
  ignore: [
    join(ssg.__distDir, '/**'), // dist/ssg
    join(ssg.buildDir, '/**'), // node_modules/.cache/quasar-app-extension-ssg
    'dist/**',
    'public/**',
    'src-ssr/**',
    'src-cordova/**',
    'src-electron/**',
    'src-bex/**',
    'node_modules/**',
    '.**/*',
    '.*',
    'README.md'
  ],
  globbyOptions: {
    gitignore: true
  }
}

This option is used to avoid re-building when no tracked file has been changed.

  • ignore is a Globby patterns to ignore tracked files. If an array is provided, it will be merged with default options, you can give a function to return an array that will remove the defaults.

    Example with an Array:

    ssg: {
      cache: {
        ignore: ['renovate.json'] // ignore changes applied on this file
      }
    }

    With a Function:

    ssg: {
      cache: {
        ignore: (defaultIgnore) =>
          defaultIgnore.push('renovate.json') && defaultIgnore
      }
    }
  • globbyOptions can be used to add globby options.

fallback

Type: String

Default: '404.html'

The filename of the full SPA or PWA page as a fallback when an index.html file does not exist for a given route.

Notes:

  • Overrides build.htmlFilename and build.ssrPwaHtmlFilename.
  • This file is created with html-webpack-plugin with defaults options set by Quasar. You can extend it with some plugins.

rendererOptions

Type: Object

Default: {}

The options merged with Quasar defaults options, then pass to the BundleRenderer as in the Vue SSR Guide.

criticalCss

Type: Boolean

Default: true

Use a fork of Critters to generate critical CSS, inline it and lazy load stylesheets for each route generated.

Note: Useful to replace the initialized value when installing the app extension.

onRouteRendered(html, route, distDir)

Type: Function

Run hook after a route is pre-rendered just before writing it to index.html.

Can use async/await or directly return a Promise.

afterGenerate(files, distDir)

Type: Function

Run hook after all pages has been generated.

Can use async/await or directly return a Promise.

Note: files parameter is an Array of all generated routes paths + filenames (including the fallback file).

Tips

Deployment

It could be useful to return a non-zero status code when a page error is encountered and let the CI/CD fail the deployment or build. To achieve that use the --fail-on-error argument.

process.env.STATIC

The property STATIC is added to process.env once the App Extension is installed.

process.env.STATIC is true when your app was built with the command quasar ssg generate, and false when it don't.

It could be useful if you mixed several builds with differents modes to differentiate runtime procedures.

Infos

About Boot File

This Extension is using a boot file called body-classes.js, only at client-side, to set platform classes to <body> tag like Quasar does it originally.

This is necessary because the server used to prerender pages can't know the platform (desktop or mobile, etc) of the client at build time.

About PWA

Quasar is using workbox-webpack-plugin to generate a complete service worker and a list of assets to precache that is injected into a service worker file.

This means that all generated pages could not be precached when webpack is compiling because they do not exist yet at this time. To fix this issue, the extension uses workbox-build replacing the workbox-webpack-plugin after all pages have been generated.

Consequently, when PWA is enabled in Quasar, you should passing options from workbox-build in the key workboxOptions in quasar.conf.js instead of options from workbox-webpack-plugin. All others PWA options are valids and used following Quasar documentation.

About Cache Feature

The cache mechanism to avoid rebuilding the app when this is not necessary is heavily inspired by Nuxt. See the Nuxt blog post about that feature.