Giter VIP home page Giter VIP logo

fastify-webpack-hot's Introduction

fastify-webpack-hot 🔥

NPM version Canonical Code Style Twitter Follow

A Fastify plugin for serving files emitted by Webpack with Hot Module Replacement (HMR).

fastify-webpack-hot in action

(fastify-webpack-hot immediately propagates hot updates to the server and browser.)

Recipes

Basic HMR Setup

All you need to enable Webpack Hot Module Replacement is:

  • Register fastify-webpack-hot Fastify plugin
  • Enable HotModuleReplacementPlugin Webpack plugin
  • Prepend fastify-webpack-hot/client entry script

Example:

import webpack from 'webpack';
import {
  fastifyWebpackHot,
} from 'fastify-webpack-hot';

const compiler = webpack({
  entry: [
    'fastify-webpack-hot/client',
    path.resolve(__dirname, '../app/main.js'),
  ],
  mode: 'development',
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
});

void app.register(fastifyWebpackHot, {
  compiler,
});

For more thorough instructions, refer to the Project Setup Examples.

Accessing Webpack Stats

Stats instance is accessible under request.webpack.stats:

app.get('*', async (request, reply) => {
  const stats = request.webpack.stats.toJson({
    all: false,
    entrypoints: true,
  });

  // ...
);

The most common use case for accessing stats is for identifying and constructing the entrypoint assets, e.g.

for (const asset of stats.entrypoints?.main.assets ?? []) {
  if (asset.name.endsWith('.js')) {
    htmlBody +=
      '<script defer="defer" src="/' + asset.name + '"></script>\n';
  }
}

Accessing Output File System

You can access Output File System by referencing compiler.outputFileSystem. However, this will have the type of OutputFileSystem, which is incompatible with memfs, which is used by this package. Therefore, a better way to access outputFileSystem is by referencing request.webpack.outputFileSystem:

app.get('*', async (request, reply) => {
  const stats = JSON.parse(
    await request.webpack.outputFileSystem.promises.readFile(
      path.join(__dirname, '../dist/stats.json'),
      'utf8'
    )
  );

  // ...
);

This example shows how you would access stats.json generated by webpack-stats-plugin.

Note: You likely won't need to use this because fastify-webpack-hot automatically detects which assets have been generated and serves them at output.publicPath.

Compressing Response

This plugin is compatible with compression-webpack-plugin, i.e. This plugin will serve compressed files if the following conditions are true:

  • Your outputs include compressed file versions (either .br or .gz)
  • Request includes a matching accept-encoding header

Example compression-webpack-plugin configuration:

new CompressionPlugin({
  algorithm: 'brotliCompress',
  deleteOriginalAssets: false,
  filename: '[path][base].br',
  compressionOptions: {
    level: zlib.constants.BROTLI_MIN_QUALITY,
  },
  minRatio: 0.8,
  test: /\.(js|css|html|svg)$/,
  threshold: 10_240,
})

Project Setup Examples

These are complete project setup examples that you can run locally to evaluate fastify-webpack-hot plugin:

Difference from webpack-dev-server and webpack-hot-middleware

webpack-dev-server and webpack-hot-middleware were built for express framework and as such they require compatibility plugins to work with Fastify. Additionally, both libraries are being maintained with intent to support legacy webpack versions (all the way to webpack v1). As a result, they contain a lot of bloat that makes them slower and harder to maintain.

fastify-webpack-hot is built from the ground up leveraging the latest APIs of Fastify and webpack, and it encompasses functionality of both libraries. It is faster and easier to maintain.

Troubleshooting

Browser Logging

This project uses roarr logger to output the application's state.

In order to output logs in browser, you need to provide output interface. The easiest way of doing it is by including @roarr/browser-log-writer in your project.

import '@roarr/browser-log-writer/init';

Afterwards, to output all logs set ROARR_LOG=true in localStorage:

localStorage.setItem('ROARR_LOG', 'true');

Note: Ensure that you have enabled verbose logs in DevTools to see all fastify-webpack-hot logs.

Node.js Logging

This project uses roarr logger to output the program's state.

Export ROARR_LOG=true environment variable to enable log printing to stdout.

Use roarr-cli program to pretty-print the logs.

fastify-webpack-hot's People

Contributors

gajus avatar

Stargazers

Kelly Peilin Chan avatar Jingsong Gao avatar Aralic avatar Jonghyuk Max Kim avatar Matias Gonzalez avatar Vitalii Dub avatar GT avatar Renée avatar Ian VanSchooten avatar  avatar Tang Weinan avatar Emmanuel Salomon avatar Kibeom Kwon avatar Masaki Utsumiya avatar Paweł Słowik avatar Nikita Popov avatar Donald Pakkies avatar  avatar

Watchers

 avatar  avatar

fastify-webpack-hot's Issues

HMR not working for the examples

Steps to Reproduce:

Clone project
Run: npm i;
Go to one of the examples folder
Run: npm i;
Run: npm start
Change something in one of the files and save it.
After these steps I can't see the changes, only after reloading the page.

Node.js versions: 16.20.1, 18.11.0
OS: Ubuntu 20.04.6 LTS

Note: you'll need the fixes from this PR

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Allow multiple instances

First off, thanks a ton for making this. I'm spiking out a conversion of Storybook from express to fastify, and I nearly despaired when I realized that the webpack middleware was tightly coupled to express. Then I found this from a post on reddit, and hope was restored.

One issue I'm having right now, is that I need to be able to start up two webpack servers, one for the "manager" (the sidebar and addons and such), and another for the "preview" (the actual stories themselves). However, when I do, I get an error message of:

ERR! FastifyError: Method 'GET' already declared for route '/__fastify_webpack_hot'
ERR!     at Object.addNewRoute (/Users/ianvs/code/storybook/storybook/node_modules/fastify/lib/route.js:261:19)
ERR!     at Object.route (/Users/ianvs/code/storybook/storybook/node_modules/fastify/lib/route.js:196:19)
ERR!     at Object.prepareRoute (/Users/ianvs/code/storybook/storybook/node_modules/fastify/lib/route.js:143:18)
ERR!     at Object._get [as get] (/Users/ianvs/code/storybook/storybook/node_modules/fastify/fastify.js:244:34)
ERR!     at /Users/ianvs/code/storybook/storybook/node_modules/fastify-webpack-hot/dist/src/index.js:61:13
ERR!     at Plugin.exec (/Users/ianvs/code/storybook/storybook/node_modules/avvio/plugin.js:131:19)
ERR!     at Boot.loadPlugin (/Users/ianvs/code/storybook/storybook/node_modules/avvio/plugin.js:273:10)
ERR!     at processTicksAndRejections (node:internal/process/task_queues:83:21)
ERR!  FastifyError [Error]: Method 'GET' already declared for route '/__fastify_webpack_hot'
ERR!     at Object.addNewRoute (/Users/ianvs/code/storybook/storybook/node_modules/fastify/lib/route.js:261:19)
ERR!     at Object.route (/Users/ianvs/code/storybook/storybook/node_modules/fastify/lib/route.js:196:19)
ERR!     at Object.prepareRoute (/Users/ianvs/code/storybook/storybook/node_modules/fastify/lib/route.js:143:18)
ERR!     at Object._get [as get] (/Users/ianvs/code/storybook/storybook/node_modules/fastify/fastify.js:244:34)
ERR!     at /Users/ianvs/code/storybook/storybook/node_modules/fastify-webpack-hot/dist/src/index.js:61:13
ERR!     at Plugin.exec (/Users/ianvs/code/storybook/storybook/node_modules/avvio/plugin.js:131:19)
ERR!     at Boot.loadPlugin (/Users/ianvs/code/storybook/storybook/node_modules/avvio/plugin.js:273:10)
ERR!     at processTicksAndRejections (node:internal/process/task_queues:83:21) {
ERR!   code: 'FST_ERR_DUPLICATED_ROUTE',
ERR!   statusCode: 500
ERR! }

Is there any chance something can be done so that I can run two webpacks at the same time?

Thanks!

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.