Nextjs Error: Must use import to load ES Module - reactjs

Hi i am creating a project using nextjs and reactjs ,i am facing an issue, when I am trying to import datetime from npm date-time package ,its throwing this error.I am using this npm package https://www.npmjs.com/package/date-time. The error in my code is shown in the picture attached
This is my next.config.js what i need to
const path = require("path");
const withCss = require("#zeit/next-css");
const withSass = require("#zeit/next-sass");
const withImages = require("next-images");
module.exports = withImages(
withSass(
withCss({
webpack: (config, { isServer }) => {
if (isServer) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
name: "[name].[ext]",
},
},
});
}
return config;
},
cssLoaderOptions: {
url: false,
},
})
)
);

Related

How to fix Error 400 Image not displaying Next App firebase ssr

Still in my journey of deploying my ssr app on firebase. Almost there.
I only have an issue with my images. I am getting a 400 error message on the console. Pictures are from an external url. The data fetched is correct but it does display somehow. You will see below my server.js file and next.config.js.
Can someone tell me what is missing, please?
server.js
const { https } = require('firebase-functions');
const { default: next } = require('next');
const isDev = process.env.NODE_ENV !== 'production';
const server = next({
dev: isDev,
//location of .next generated after running -> yarn build
conf: { distDir: '.next' },
image :{ domain :['assets.coingecko.com'],}
});
const nextjsHandle = server.getRequestHandler();
exports.nextServer = https.onRequest((req, res) => {
return server.prepare()
.then(() => {
return nextjsHandle(req, res)
});
});
next.config.js
const webpack = require('webpack');
const path = require('path');
//const withPlugins = require('next-compose-plugins');
//const optimizedImages = require('next-optimized-images');
module.exports = {
images: {
domains: ['assets.coingecko.com'],
loader: 'imgix',
path: 'https://assets.coingecko.com/',
},
reactStrictMode: true,
entry: './src/index.js',
sassOptions: {
includePaths: [path.join(__dirname, 'styles')],
},
module: {
rules: [
//...
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]',
},
},
],
},
],
},
//...
}
first i wanted to thank you for your help #juliomalves. I found answer to my issue. I have answered the questions in details here [1][ https://stackoverflow.com/questions/69974890/how-to-set-up-next-image-loader-url-correctly-for-external-url/70052871#70052871]
if anyone find himself in the same situation.

SyntaxError: pragma and pragmaFrag cannot be set when runtime is automatic

I'm migrating a project from Next 9 to Next 11 which uses webpack5 by default. After fixing the loader issue as shown in the next.config.js file, I get this error:
SyntaxError: pragma and pragmaFrag cannot be set when runtime is automatic
I've tried debugging with these solutions, and I still trigger the same error.
My code:
next.config.js
const withImages = require("next-images");
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
const withYaml = require("next-plugin-yaml");
const babel = require('babel-plugin-import-glob-array');
module.exports = (phase) =>
withYaml(
withImages(
({
target: "serverless",
env: {
isDev: phase === PHASE_DEVELOPMENT_SERVER,
},
webpack5: true,
webpack: (config, options) => {
config.module.rules.push({
test: /\.mdx/,
use: [
options.defaultLoaders.babel,
{
loader: '#mdx-js/loader',
options: babel.options,
},
],
});
config.module.rules.unshift({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
console.log(options.webpack.version); // 5.18.0
// eslint-disable-next-line no-param-reassign
config.experiments = {};
return config;
},
})
)
);
babel.config.json
{
"presets": ["next/babel", "#emotion/babel-preset-css-prop"],
"plugins": ["import-glob-array", "emotion"]
}
.tsx files
/** #jsx jsx */
import { css, jsx } from "#emotion/core";

Configure multiple next plugins: withMDX, withBundleAnalyzer

I started a nextjs site with a tailwind blog starter that already comes with withBundleAnalyzer in next.config.js.
I am now trying to get .mdx files to work from the pages directly. Documentation says I need withMDX in my nextjs.config file. How do I get the two to play together? Should I only keep one or the other? I have installed next-compose-plugins but not sure how to set it all up.
Update
This is my next config file; it's still failing. Error:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
TypeError: undefined is not a function
at _withPlugins (/home/xxx/xxx/nodeapps/my-web/node_modules/next-compose-plugins/lib/index.js:17:22)
at Object.<anonymous> (/home/xxx/xxx/nodeapps/my-web/next.config.js:11:18)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at loadConfig (/home/xxx/xxx/nodeapps/my-web/node_modules/next/dist/next-server/server/config.js:8:94)
at async NextServer.loadConfig (/home/xxx/xxx/nodeapps/my-web/node_modules/next/dist/server/next.js:1:2962)
const withPlugins = require('next-compose-plugins')
const withMDX = require('#next/mdx')({
extension: /\.mdx$/,
})
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withPlugins(
withMDX(
withBundleAnalyzer({
pageExtensions: ['js', 'jsx', 'md', 'mdx'],
future: {
webpack5: true,
},
webpack: (config, { dev, isServer }) => {
config.module.rules.push({
test: /\.(png|jpe?g|gif|mp4)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/_next',
name: 'static/media/[name].[hash].[ext]',
},
},
],
})
config.module.rules.push({
test: /\.svg$/,
use: ['#svgr/webpack'],
})
if (!dev && !isServer) {
// Replace React with Preact only in client production build
Object.assign(config.resolve.alias, {
react: 'preact/compat',
'react-dom/test-utils': 'preact/test-utils',
'react-dom': 'preact/compat',
})
}
return config
},
})
)
)
As you mentioned you can use next-compose-plugins like this
const withPlugins = require('next-compose-plugins');
const withMDX = require('#next/mdx');
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withPlugins([
// add a plugin with specific configuration
[withMDX, {
// MDX plugin specific options
}],
// add it like this if no plugin configuration is needed
[withBundleAnalyzer],
]);
EDIT:
Here is your complete config file:
const withPlugins = require("next-compose-plugins");
const withMDX = require("#next/mdx")({
extension: /\.mdx?$/,
});
const withBundleAnalyzer = require("#next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
module.exports = withPlugins([[withBundleAnalyzer], [withMDX]], {
pageExtensions: ["js", "jsx", "md", "mdx"],
future: {
webpack5: true,
},
webpack: (config, { dev, isServer }) => {
config.module.rules.push({
test: /\.(png|jpe?g|gif|mp4)$/i,
use: [
{
loader: "file-loader",
options: {
publicPath: "/_next",
name: "static/media/[name].[hash].[ext]",
},
},
],
});
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"],
});
if (!dev && !isServer) {
// Replace React with Preact only in client production build
Object.assign(config.resolve.alias, {
react: "preact/compat",
"react-dom/test-utils": "preact/test-utils",
"react-dom": "preact/compat",
});
}
return config;
},
});
You can setup the config without using next-compose-plugins as well.
const withMDX = require('#next/mdx')({
extension: /\.mdx$/,
})
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withMDX(withBundleAnalyzer({
// Your Next.js configs, including withMDX-specific options
}))

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?

Next JS config multiple plugin configuration

const {
DEVELOPMENT_SERVER,
PRODUCTION_BUILD
} = require("next/constants");
require('dotenv').config()
const path = require('path')
const Dotenv = require('dotenv-webpack')
const nextConfig = {
webpack: config => ({ ...config, node: { fs: "empty" } })
};
module.exports = phase => {
if (phase === DEVELOPMENT_SERVER || phase === PRODUCTION_BUILD) {
const withCSS = require("#zeit/next-css");
return withCSS(nextConfig);
}
return nextConfig;
};
*module.exports = {
webpack: (config) => {
config.plugins = config.plugins || []
config.plugins = [
...config.plugins,
// Read the .env file
new Dotenv({
path: path.join(__dirname, '.env'),
systemvars: true
})
]
return config
}
}*
let prefix;
switch (process.env.NODE_ENV) {
case "test":
prefix = "https://test.domain.com/providers";
break;
case "stage":
prefix = "https://state.domain.com/providers";
break;
case "production":
prefix = "https://production.domain.com/providers";
break;
default:
prefix = "";
break;
}
module.exports = {
distDir: "build",
assetPrefix: prefix
};
Here my next.config.js configuration.
But when I am trying to run then getting the message like
Error! Network error: Unexpected token N in JSON at position 0
But when I am trying to run whatever into the bold(*) and kept only that thing into the next.config.js then working fine.
How to configure multiple plugin into the module.export
Here is a simple way to use multiple nested plugins in Next.js
const withImages = require('next-images');
const withCSS = require('#zeit/next-css');
module.exports = withCSS(withImages({
webpack(config, options) {
return config
}
}))
If you want to using single one plugin then do this:
const withImages = require('next-images');
module.export = withImages();
For further information about Next.js plugins and their documentation click here:
https://github.com/zeit/next-plugins/tree/master/packages
next-compose-plugins plugin provides a cleaner API for enabling and configuring plugins for next.js.
Install npm install --save next-compose-plugins
Use it in next.config.js:
// next.config.js
const withPlugins = require('next-compose-plugins');
const images = require('next-images');
const sass = require('#zeit/next-sass');
const typescript = require('#zeit/next-typescript');
// optional next.js configuration
const nextConfig = {
useFileSystemPublicRoutes: false,
distDir: 'build',
};
module.exports = withPlugins([
// add a plugin with specific configuration
[sass, {
cssModules: true,
cssLoaderOptions: {
localIdentName: '[local]___[hash:base64:5]',
},
}],
// add a plugin without a configuration
images,
// another plugin with a configuration
[typescript, {
typescriptLoaderOptions: {
transpileOnly: false,
},
}],
], nextConfig);
Next.js version >10.0.3
Images are now built-in, so to add plugin and image code below will work:
const withPlugins = require('next-compose-plugins');
const withCSS = require('#zeit/next-css');
const nextConfig = {
images: {
domains: ['sd.domain.com'], // your domain
},
};
module.exports = withPlugins([
[withCSS]
], nextConfig);
This worked for me:
// next.config.js
const withLess = require("next-with-less");
const withPWA = require('next-pwa')
const pwa = withPWA({
pwa: {
dest: 'public'
}
})
module.exports = withLess({
lessLoaderOptions: {
},
reactStrictMode: true,
typescript: {
ignoreBuildErrors: true,
},
eslint: {
ignoreBuildErrors: true,
},
...pwa // using spread to merge the objects
});

Resources