next.js bundle analyzer isn't creating pages to vew bundles - reactjs

I'm trying to reduce the bundle size of my site by using https://www.npmjs.com/package/#next/bundle-analyzer
At the moment, when I run npm analyze with
"analyze": "cross-env ANALYZE=true next build",
It isn't outputting the html files with the visualization needed.
This is my next.config.js
const withPWA = require('next-pwa')
const runtimeCaching = require('next-pwa/cache')
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withPWA({
pwa: {
dest: 'public',
runtimeCaching,
},
poweredByHeader: false,
},
withBundleAnalyzer(),
)
using this nextjs-analyze-app-bundle tutorial.
What is going wrong?

Looks like this has been answered on Vercel's issues board. Copying their solution here:
These plugins are functions that enhance the configuration object, so
you have to wrap them instead of providing them as arguments:
const withPWA = require('next-pwa')
const runtimeCaching = require('next-pwa/cache')
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer(withPWA({
pwa: {
dest: 'public',
runtimeCaching,
},
poweredByHeader: false,
}));

Before I was doing it like this,
module.exports = withBundleAnalyzer(
withPWA({
pwa: {
dest: 'public',
runtimeCaching,
},
poweredByHeader: false,
})
)
module.exports =
{
env: {
BASE_URL: process.env.BASE_URL,
},
future: {
webpack5: true,
},
reactStrictMode: true,
}
Not sure but I think you should only need to have one module.exports so I wrapped my other stuff inside the withBundleAnalyzer like this
module.exports = withBundleAnalyzer(
withPWA({
pwa: {
dest: 'public',
runtimeCaching,
},
poweredByHeader: false,
}),
{
env: {
BASE_URL: process.env.BASE_URL,
},
future: {
webpack5: true,
},
reactStrictMode: true,
}
)

Related

How to make www.mydomain.com work in nextjs

I am working on a project and trying to make www.mydomain.com work. I am working on localhost:3000 and when I put in url: mydomain.com:3000 it works but when I set www.mydomian.com:3000 it redirects me on mydomain.is which is my main page.
this is my code in next.config.js file
const path = require("path");
const redirects = require("./redirects");
/** #type {import('next').NextConfig} */
const nextConfig = async () => {
return {
reactStrictMode: false,
swcMinify: true,
sassOptions: {
includePaths: [path.join(__dirname, "src/styles")],
},
redirects() {
return Promise.resolve(redirects);
},
images: {
domains: ["mydomain.cdn.prismic.io", "images.prismic.io"],
},
i18n: {
// https://nextjs.org/docs/advanced-features/i18n-routing
localeDetection: false,
locales: ["is", "en"],
defaultLocale: "is",
domains: [
{
domain: 'mydomain.is',
defaultLocale: 'is',
},
{
domain: 'mydomain.com',
defaultLocale: 'en',
},
],
},
};
};
module.exports = nextConfig;`

Next.js vert slow to start on Windows OS

I have this big issue with starting Next.js, the same project on 2 different OS, it has completely different startup times, 1s on MacOSX vs 10s on Windows 11.
Has anyone else had the same problem? Is there any way to fix it?
enter image description here
Here's my next.js conf:
const { resolve } = require('path')
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
openAnalyzer: true,
})
module.exports = withBundleAnalyzer(
{
i18n: {
locales: ['en', 'it'],
defaultLocale: 'en',
localeDetection: true,
},
compiler: {
removeConsole: process.env.NODE_ENV !== 'development',
},
swcMinify: true,
eslint: {
ignoreDuringBuilds: true,
},
webpack: (config) => {
config.plugins = config.plugins || []
config.optimization.providedExports = true
config.resolve.alias = {
...config.resolve.alias,
'#': resolve(__dirname, './src/'),
}
config.resolve.fallback = { ...config.resolve.fallback, fs: false }
config.module.rules.push({
test: /\.(glsl|vs|fs|vert|frag)$/,
use: ['raw-loader', 'glslify-loader'],
})
return config
},
},
)

Next.js Module parse failed: Unexpected character '�' (1:0)

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
I tried multiple approaches on the web corresponding the issue but nothing seemed to work.
I have not been able to find a solution to this problem.
This is what my next.config.js file looks like
const withPlugins = require('next-compose-plugins')
const withImages = require('next-images')
const CompressionPlugin = require('compression-webpack-plugin')
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
let prefixUrl = ''
let imgLoaderUrl = ''
switch (process.env.ENV) {
case 'production':
prefixUrl = 'https://webstatic.circleslive.com'
imgLoaderUrl = 'https://webstatic.circleslive.com'
break
case 'staging':
prefixUrl = 'https://staging-webstatic.circleslive.com'
imgLoaderUrl = 'https://staging-webstatic.circleslive.com'
break
case 'development':
prefixUrl = ''
imgLoaderUrl = '/_next/image'
break
default:
prefixUrl = ''
imgLoaderUrl = '/_next/image'
break
}
const nextConfig = {
poweredByHeader: false,
trailingSlash: false,
compress: true,
future: {
webpack5: true,
},
env: {
ENV: process.env.ENV,
},
serverRuntimeConfig: {
STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
},
images: {
loader: 'default',
path: imgLoaderUrl,
},
webpack: (config) => {
config.optimization.minimize = true
config.plugins.push(
new CompressionPlugin({
test: /\.js$|\.css$|\.html$/,
}),
)
return config
},
build: {
extend(config) {
config.module.rules.push({
options: {
fix: true,
},
})
},
},
}
module.exports = withPlugins(
[
[
withImages,
{
assetPrefix: prefixUrl,
dynamicAssetPrefix: true,
inlineImageLimit: false,
},
],
[withBundleAnalyzer],
],
nextConfig,
)
Try the following:
module.exports = withPlugins(
[
[
{
assetPrefix: prefixUrl,
dynamicAssetPrefix: true,
inlineImageLimit: false,
},
],
[withBundleAnalyzer],
],
withImages(nextConfig)
)

Web Worker - Jest - Cannot use 'import.meta' outside a module

I'm working on a nextjs 10.1.3 built-in web application. We implemented a web worker to boost up the performance in one of the pages and the plan is to continue adding more workers; also, all the code is properly unit tested, and using the worker-loader in previous webpack versions (4th and below) we were able to test it.
With the new webpack 5 version, the worker-loader plugin is not needed anymore; instead, the way to load a web worker using the new version is new Worker(new URL("#/workers/task.worker.js", import.meta.url));.
Doing it this way, my code is working as expected with npm build && npm start; however, when I try to add the respective unit tests I got the following error: Cannot use 'import.meta' outside a module and everything happens because of the import.meta.url used to add the location of the worker in the browser.
I read many posts on the web regarding babel but I want to get away from that option. Is there any other option to mock the import.meta.url with jest?
Any help will be very welcome. This is the current configuration.
package.json
{
...
"#babel/core": "^7.8.6",
"next": "^10.1.3",
"react": "^16.13.0",
"webpack": "^5.37.1"
"devDependencies": {
...
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"jest": "^24.9.0",
"jest-cli": "^25.1.0",
...
}
...
}
next.config.js
const {
...
} = process.env;
const basePath = "";
const COMMIT_SHA = [];
const { parsed: localEnv } = require("dotenv").config();
const webpack = require("webpack");
const withBundleAnalyzer = require("#next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
const nextConfig = {
env: {
NEXT_PUBLIC_COMMIT_SHA: COMMIT_SHA,
},
images: {
domains: [
"...",
],
},
future: {
webpack5: true,
},
productionBrowserSourceMaps: true,
trailingSlash: true,
reactStrictMode: true,
webpack: (config, options) => {
if (localEnv) {
config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
} else {
config.plugins.push(new webpack.EnvironmentPlugin(process.env));
}
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
name: "[name].[ext]",
},
},
});
config.output = {
...config.output,
chunkFilename: options.isServer
? `${options.dev ? "[name]" : "[name].[fullhash]"}.js`
: `static/chunks/${options.dev ? "[name]" : "[name].[fullhash]"}.js`,
publicPath: `/_next/`,
globalObject: `(typeof self !== 'undefined' ? self : this)`,
};
config.plugins.push(new webpack.IgnorePlugin(/pages.*\/__tests__.*/));
config.plugins.push(
new options.webpack.DefinePlugin({
"process.env.NEXT_IS_SERVER": JSON.stringify(
options.isServer.toString()
),
})
);
return config;
},
};
module.exports = withBundleAnalyzer(nextConfig);
The useEffect worker
useEffect(() => {
if (pageData.data?.length) {
workerRef.current = new Worker(new URL("#/workers/task.worker.js", import.meta.url));
workerRef.current.addEventListener("message", result => {
if (result.error) {
setWorkerError();
} else {
updateData(result.data);
}
});
const ids = pageData.data.map(store => store.id);
workerRef.current.postMessage(ids);
} else {
setNoDataFound();
}
return () => {
workerRef.current && workerRef.current.terminate();
};
}, []);
jest.config.js
module.exports = {
moduleDirectories: ["node_modules", "src", "static", "store"],
modulePathIgnorePatterns: [
"<rootDir>/node_modules/prismjs/plugins/line-numbers",
],
testPathIgnorePatterns: [
"<rootDir>/src/components/component-library",
"<rootDir>/.next",
"jest.config.js",
"next.config.js",
],
collectCoverageFrom: [
"**/src/**",
"**/store/**",
"**/pages/**",
"!**/__tests__/**",
"!**/node_modules/**",
"!**/component-library/**",
],
testEnvironment: "node",
collectCoverage: true,
verbose: false,
automock: false,
setupFiles: ["./setupTests.js"],
moduleNameMapper: {
"#/components/(.*)$": "<rootDir>/src/components/$1",
"#/functions/(.*)$": "<rootDir>/src/components/functions/$1",
"#/services/(.*)$": "<rootDir>/src/components/services/$1",
"#/workers/(.*)$": "<rootDir>/src/components/workers/$1",
"#/scripts(.*)$": "<rootDir>/src/scripts/$1",
"#/src(.*)$": "<rootDir>/src/$1",
"#/__mocks__(.*)$": "<rootDir>/__mocks__/$1",
"#/pages(.*)$": "<rootDir>/pages/$1",
"#/store(.*)$": "<rootDir>/store/$1",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
},
coveragePathIgnorePatterns: ["/node_modules/"],
coverageThreshold: {
global: {
branches: 67,
functions: 66,
lines: 73,
statements: 72,
},
},
runner: "groups",
extraGlobals: [],
testTimeout: 10000,
};
In my setup (typescript + ts-jest) I prepended the following node option to make it work:
NODE_OPTIONS=--experimental-vm-modules
Reference can be found here: https://jestjs.io/docs/ecmascript-modules

How do I combine several module.exports in Next.js next.config.js?

In my next.config.js file, I want to export two module exports. But I can't do that without combining them. Is there a way to combine the two module.exports?
const withPWA = require("next-pwa");
module.exports = withPWA({
future: { webpack5: true },
pwa: {
dest: "public",
swSrc: "service-worker.js",
},
});
module.exports = {
env: {
SANITY_DATASET_NAME: process.env.SANITY_DATASET_NAME,
SANITY_PROJECT_ID: process.env.SANITY_PROJECT_ID,
},
};
You don't need to export two modules, you suppose to export a single configuration object.
Check all possible NextJS configurations here.
const withPWA = require("next-pwa");
module.exports = withPWA({
future: { webpack5: true },
pwa: {
dest: "public",
swSrc: "service-worker.js",
},
env: {
SANITY_DATASET_NAME: process.env.SANITY_DATASET_NAME,
SANITY_PROJECT_ID: process.env.SANITY_PROJECT_ID,
},
});

Resources