next-pwa icon indicating copy to clipboard operation
next-pwa copied to clipboard

Mono Repo Shared folder next-transpile-modules with next pwa not working

Open parmarravi opened this issue 2 years ago • 4 comments

I am getting two issues due to which the PWA application is not able to run correctly

1.)Writing down custom server code with if case to handle sw.js

2.)Adding Webpack in next. config

  "dependencies": {
    "next": "12.1.5",
    "next-pwa": "^5.5.2",
    "next-transpile-modules": "^9.0.0",
    "react": "18.0.0",
    "react-dom": "18.0.0"
  },

Sample code for testing the issue.

https://github.com/parmarravi/MonoRepoPWANextJs

THIS WORKS Both Shared and PWA

next.config.js

const withTM = require("next-transpile-modules")(["shared"]);
const withPWA = require("next-pwa");

module.exports = withPWA(
  withTM({
    pwa: {
      dest: "public",
      register: true,
      skipWaiting: false,
      fallbacks: {
        image: "/static/images/fallback.png",
      },
    },
  })
);

server.js

const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const { join } = require("path");

const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 8081;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
  createServer(async (req, res) => {
    const parsedUrl = parse(req.url, true);
    const { pathname } = parsedUrl;
    console.log(`>> ${pathname}`);
    handle(req, res, parsedUrl);
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://${hostname}:${port}`);
  });
});

THIS DOES NOT WORK

Adding condition to handle SW.js does not able to render PWA install on chrome.

server.js

const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const { join } = require("path");

const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 8081;
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
  createServer(async (req, res) => {
    const parsedUrl = parse(req.url, true);
    const { pathname } = parsedUrl;
    console.log(`>> ${pathname}`);
     if (
       pathname === "/sw.js" ||
       /^\/(workbox|worker|fallback)-\w+\.js$/.test(pathname)
     ) {
       const filePath = join(__dirname, "_next", pathname);
       app.serveStatic(req, res, filePath);
     } else {
       handle(req, res, parsedUrl);
     }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://${hostname}:${port}`);
  });
});

Adding Webpack with PWA does not work

module.exports = withPWA(
  withTM({
    pwa: {
      dest: "public",
      register: true,
      skipWaiting: false,
      fallbacks: {
        image: "/static/images/fallback.png",
      },
    },
 webpack: (config, options) => {
      config.module.rules.push({
        test: /\.(eot|woff|woff2|ttf)$/,
        use: {
          loader: "url-loader",
          options: 100000,
          name: "[name].[ext]",
        },
      });
      return config;
    },
  })
);

NOR this works


module.exports = withTM(
  withPWA({
    webpack: (config, options) => {
      config.module.rules.push({
        test: /\.(eot|woff|woff2|ttf)$/,
        use: {
          loader: "url-loader",
          options: 100000,
          name: "[name].[ext]",
        },
        pwa: {
          dest: "public",
          register: true,
          skipWaiting: false,
          fallbacks: {
            image: "/static/images/fallback.png",
          },
        },
      });
      return config;
    },
  })
);

parmarravi avatar Apr 26 '22 16:04 parmarravi

Hi, @parmarravi were you able to find a solution?

Bur0 avatar Aug 23 '22 08:08 Bur0

Having the exact issue too. I managed to have it running, but it throws some warnings in the console


const path = require('path');
const webpack = require('webpack');

const withTM = require('next-transpile-modules')(['@my-org/design-system']);

const dotEnvConfig = require('dotenv').config({
  path: path.join(__dirname, '.env'),
});

const localEnv = dotEnvConfig?.parsed || { NODE_ENV: 'development' };

const isDev = process.env.NODE_ENV === 'development';

// Progressive Web App configs -------------------------------------------------
const withPWA = require('next-pwa')({
  register: true,
  disable: isDev,
  dest: 'public',
  // scope: '/',
  fallbacks: {
    image: '/images/fallback.png', // Update this to a decent placeholder
    document: '/offline', // if you want to fallback to a custom page other than /_offline
    // font: '/static/font/fallback.woff2',
    // audio: ...,
    // video: ...,
  },
});

// The rest of the app config with custom webpack font loader ------------------

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = withTM(withPWA({
  reactStrictMode: true,
  productionBrowserSourceMaps: true,
  swcMinify: true,
  i18n: {
    locales: [
      'en-AE',
      'en-SA',
      'ar-AE',
      'ar-SA',
    ],
    defaultLocale: 'en-AE',
  },
  webpack(appConfig) {
    const config = { ...appConfig };

    config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
    config.resolve.alias.images = path.join(__dirname, 'src/assets/images');
    config.module.rules.push({
      test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 8192,
            fallback: 'file-loader',
            publicPath: '../_next/static/chunks/fonts/',
            outputPath: `${config.isServer ? '../' : ''}static/chunks/fonts/`,
            name: '[name]-[hash].[ext]',
          },
        },
      ],
    });

    return config;
  },
}));

module.exports = nextConfig;

The warnings I get in the console in development when the pwa.disabled===true, mildly uncomfortable, otherwise, it runs without errors or warning if the pwa is enabled.

ready - started server on 0.0.0.0:3004, url: http://localhost:3004
info  - Loaded env from /Volumes/path-to/my-org-monorepo-monorepo/apps/web/.env
info  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled
info  - automatically enabled Fast Refresh for 1 custom loader
> [PWA] PWA support is disabled
> [PWA] PWA support is disabled
info  - Using external babel configuration from /Volumes/path-to/my-org-monorepo-monorepo/apps/web/.babelrc
event - compiled client and server successfully in 4.7s (175 modules)
wait  - compiling /_error (client and server)...
event - compiled client and server successfully in 133 ms (176 modules)
warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works
wait  - compiling / (client and server)...
event - compiled client and server successfully in 359 ms (222 modules)
<w> [webpack.cache.PackFileCacheStrategy/webpack.FileSystemInfo] Resolving 'next/dist/compiled/webpack/webpack-lib' in /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa for build dependencies doesn't lead to expected result '/Volumes/path-to/my-org-monorepo-monorepo/node_modules/next/dist/compiled/webpack/webpack-lib.js', but to '/Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/node_modules/next/dist/compiled/webpack/webpack-lib.js' instead. Resolving dependencies are ignored for this path.
<w>  at unknown 4 next/dist/compiled/webpack/webpack-lib
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/build-fallback-worker.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/build-fallback-worker.js
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/index.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/index.js
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/packages/build-configs/next.config.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/packages/build-configs/next.config.js
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/apps/web/next.config.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/apps/web/next.config.js
<w>  at resolve commonjs /Volumes/path-to/my-org-monorepo-monorepo/apps/web/next.config.js
<w> [webpack.cache.PackFileCacheStrategy/webpack.FileSystemInfo] Resolving 'next/dist/compiled/webpack/webpack-lib' in /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa for build dependencies doesn't lead to expected result '/Volumes/path-to/my-org-monorepo-monorepo/node_modules/next/dist/compiled/webpack/webpack-lib.js', but to '/Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/node_modules/next/dist/compiled/webpack/webpack-lib.js' instead. Resolving dependencies are ignored for this path.
<w>  at unknown 4 next/dist/compiled/webpack/webpack-lib
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/build-custom-worker.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/build-custom-worker.js
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/index.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/node_modules/next-pwa/index.js
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/packages/build-configs/next.config.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/packages/build-configs/next.config.js
<w>  at file dependencies /Volumes/path-to/my-org-monorepo-monorepo/apps/web/next.config.js
<w>  at file /Volumes/path-to/my-org-monorepo-monorepo/apps/web/next.config.js
<w>  at resolve commonjs /Volumes/path-to/my-org-monorepo-monorepo/apps/web/next.config.js


Note: I have a shared next.config.js at my-org-monorepo-monorepo/packages/build-configs/next.config.js

Sowed avatar Sep 24 '22 18:09 Sowed

@Sowed

Can you share the repository? (Full code)

I don't get what you mean by

Note: I have a shared next.config.js at my-org-monorepo-monorepo/packages/build-configs/next.config.js

softmarshmallow avatar Nov 04 '22 14:11 softmarshmallow

Same with me, i ran the https://github.com/parmarravi/MonoRepoPWANextJs, and the same situation happen like appone

alexcastrodev avatar Jan 04 '23 19:01 alexcastrodev