too much .css files are generated in nextjs - reactjs

I'm using nextjs. I'm using sass For style layout. All styles are named with *.module.scss, and they are placed in the components folder and its subfolders and not in the styles folder mentioned by the nextjs document. I don't know how to config this situation in next.config.js. Content of my next.config.js is now:
const withPlugins = require("next-compose-plugins");
const nextTranslate = require("next-translate");
const withPWA = require("next-pwa");
const withBundleAnalyzer = require("#next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
// next.js configuration
const nextConfig = {
images: {
domains: ['ibexcdn.com'],
},
};
module.exports = withPlugins(
[
[
nextTranslate,
{
webpack: (config, { isServer, webpack }) => {
return config;
},
},
],
withBundleAnalyzer,
[
withPWA,
{
pwa: {
disable: process.env.NODE_ENV === "development",
dest: 'public',
runtimeCaching: [
{
urlPattern: /.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,
handler: 'NetworkFirst',
options: {
cacheName: 'static-font-assets',
expiration: {
maxEntries: 4,
maxAgeSeconds: 7 * 24 * 60 * 60 // 7 days
}
}
}
]
},
},
],
],
nextConfig,
);

Related

Images are missing in chromatic build

I have configured chromatic for my stories:
When I pushed my chromatic build it always shows images are missing(but actually on baseline images are there but in chromatic build it shows images are missing): please check screenshot below:
Below is my story code:
export const WideExample = () => {
stubMetadata();
stubMainMenu();
stubFooterMenu();
stubFooterMetaMenu();
let views = [];
let args = {
pageContext: {
slug: "test",
id: "1",
language: "en-US",
views: [],
settings: {
productSelector: dynamicProductSelector
}
},
...productNode,
};
return (
<LocationProvider>
<Product {...args} />;
</LocationProvider>
);
};
WideExample .parameters = {
storyshots: { disable: true },
};
and my .storybook/main.js file:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
'storybook-css-modules-preset',
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-postcss",
// 'storybook-addon-mock/register',
'storybook-addon-fetch-mock',
],
core: {
builder: "webpack5",
},
staticDirs: ['../public', '../static', '../storybook-assets', ],
my webpack.config.js file:
const path = require('path');
module.exports = ({ config, mode }) => {
config.module.rules.push({
test: /\.module\.css$/,
use: [
{
loader: 'postcss-loader',
options: {
sourceMap: true,
postcssOptions: {
config: './.storybook/',
},
},
},
],
include: path.resolve(__dirname, '../storybook/'),
});
return config;
};
Can anyone look where I am wrong and need fix?

Craco plugin not loading

I'm trying to add this plugin, which is uses this webpack plugin to my craco config file, followed the guide but it's not working.
const CracoAlias = require('craco-alias');
const imageOptimizer = require('craco-image-optimizer-plugin');
module.exports = function ({ env }) {
return {
reactScriptsVersion: 'react-scripts',
style: {
postcss: {
plugins: [
require('tailwindcss'),
require('postcss-focus-visible'),
require('autoprefixer'),
],
},
},
plugins: [
{
plugin: imageOptimizer,
// image-webpack-plugin options
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.9],
speed: 4,
},
gifsicle: {
interlaced: false,
},
// the webp option will enable WEBP
webp: {
quality: 75,
},
},
},
{
plugin: CracoAlias,
options: {
//CracoAlias options
},
},
],
};
};
The plugin is supposed to optimize the images, but it's not happening. Any ideas? Is it something wrong with my config file? Thanks.
Seems like it was a problem with react-scripts. Had to add the plugin manually like this:
const { getLoaders, loaderByName } = require('#craco/craco');
module.exports = {
overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions }) => {
const config = { ...webpackConfig };
const urlLoaderCandidates = getLoaders(config, loaderByName('url-loader'));
const urlLoader = urlLoaderCandidates.matches.find(
m =>
m.loader &&
m.loader.test &&
(Array.isArray(m.loader.test)
? m.loader.test.some(r => r.toString().indexOf('jpe?g') >= 0)
: m.loader.test.toString().indexOf('jpe?g') >= 0)
);
if (!urlLoader) {
throw Error(
'could not find correct url-loader. did you change react-scripts version?'
);
}
const loader = urlLoader.loader;
loader.use = [
{
loader: loader.loader,
options: Object.assign({}, loader.options),
},
{
/**
* #see https://github.com/tcoopman/image-webpack-loader
*/
loader: 'image-webpack-loader',
options: pluginOptions,
},
];
delete loader.loader;
delete loader.options;
return config;
},
};
And then import the file instead of the package.

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,
},
});

Import fonts to next.js react project with webpack and styled components

For some reason with next.js I just cant get importing local fonts into this project I have done it multiple times before but with next.js + react + webpack + styled components it seems to store the font in a _next folder which is or isn't right.
next.config.js
require('dotenv').config();
const autoPrefixer = require('autoprefixer');
const hash = require('string-hash');
const path = require('path');
const transpileModules = require('next-transpile-modules');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const withPlugins = require('next-compose-plugins');
const runtimeConfig = {
EXAMPLE_CONFIG: process.env.EXAMPLE_CONFIG || ''
};
const nextConfig = {
distDir: 'build',
publicRuntimeConfig: runtimeConfig,
webpack: (config) => {
// Next.js currently ignores "baseUrl" in tsconfig.json. This fixes it.
if (config.resolve.plugins) {
config.resolve.plugins.push(new TsconfigPathsPlugin);
} else {
config.resolve.plugins = [new TsconfigPathsPlugin];
}
// For inline SVGs.
config.module.rules.push({
test: /\.svg$/,
use: ({
issuer,
resource
}) => ({
loader: '#svgr/webpack',
options: {
dimensions: false,
svgo: true,
svgoConfig: {
plugins: [{
cleanupListOfValues: true
},
{
cleanupNumericValues: true
},
{
removeDesc: true
},
{
removeEmptyAttrs: true
},
{
removeEmptyContainers: true
},
{
removeEmptyText: true
},
{
removeRasterImages: true
},
{
removeTitle: true
},
{
removeUselessDefs: true
},
{
removeUnusedNS: true
},
{
cleanupIDs: {
prefix: `${hash(issuer + resource)}`
}
}
]
}
}
})
});
// For loading file types.
config.module.rules.push({
test: /\.(eot|otf|woff|woff2|ttf|png|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
limit: 100000,
name: '[name].[ext]',
},
},
});
return config;
}
};
// node_module packages that contain TypeScript that we want to compile.
const withTm = transpileModules([
'frontend-utilities'
]);
const withFonts = require('next-fonts');
module.exports = withPlugins([
[withTm],
[withFonts],
], nextConfig);
fonts.ts
import { css } from 'styled-components';
import CircularStdFont from '../public/static/fonts/CircularStdFont.otf';
export const GlobalFonts = css`
#font-face {
font-family: 'CircularStdFont';
src: url(${CircularStdFont}) format('opentype');
font-weight: normal;
font-style: normal;
}
`;
fonts folder
--- public
-- fonts
- CircularStdFont.otf
Error
Any ideas?
Please see screenshot below for the 404 get error.

Updating nextjs from 8 to 9.3.3 broke styling

I just updated nextjs from 8 to 9.3.3, and some of my styling broke.
Previously I was importing .scss files and they were locally scoped to their respective components.
After updating to 9.3.3, it seems that components with classNames that are named the same are now sharing styles, so that leads me to believe that something with the sass-loader or css-loader in next.config.js seems off.
this is my next.config.js
const path = require('path');
const dotenv = require('dotenv');
const withSass = require('#zeit/next-sass');
const webpack = require('webpack');
const envConfig = dotenv.config();
const config = withSass({
cssModules : true,
cssLoaderOptions : {
modules : true,
sourceMap : true,
importLoaders : 1,
},
sassLoaderOptions: {
includePaths: [path.resolve(__dirname, './')], //eslint-disable-line
},
useFileSystemPublicRoutes: false,
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { // eslint-disable-line
const ENV = {};
for (let entry in envConfig.parsed) {
ENV[`process.env.${entry}`] = JSON.stringify(envConfig.parsed[entry]);
}
config.plugins.push(new webpack.DefinePlugin(ENV));
return config;
},
});
module.exports = config;
What I've tried
I've changing my config around like this:
const config = withSass({
cssModules : true,
cssLoaderOptions : {
modules : {
mode: 'local',
exportGlobals: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
context: path.resolve(__dirname, 'src'), //eslint-disable-line
hashPrefix: 'my-custom-hash',
},
sourceMap : true,
importLoaders : 1,
},
sassLoaderOptions: {
includePaths: [path.resolve(__dirname, './')], //eslint-disable-line
},
useFileSystemPublicRoutes: false,
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { // eslint-disable-line
const ENV = {};
for (let entry in envConfig.parsed) {
ENV[`process.env.${entry}`] = JSON.stringify(envConfig.parsed[entry]);
}
config.plugins.push(new webpack.DefinePlugin(ENV));
return config;
},
});
module.exports = config;
which didn't work.
My last resort which does work is manually going into each .scss file and changing them to x.module.scss, which would take a lot of time going into each file. Is there something wrong with my config?

Resources