Getting error from Next.js basic example walkthrough - next.js

I get this error when running the code from the Next JS starter walkthrough:
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.remark (C:\*******\***********\.next\server\pages\index.js:3249:18)
at __webpack_require__ (C:\*******\***********\.next\server\webpack-runtime.js:25:42)
at Object../lib/posts.js (C:\*******\***********\.next\server\pages\index.js:132:64)
at __webpack_require__ (C:\*******\***********\.next\server\webpack-runtime.js:25:42)
at Object../pages/index.js (C:\*******\***********\.next\server\pages\index.js:2933:68) {
code: 'ERR_REQUIRE_ESM'
}
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\**********\********\node_modules\remark\index.js
require() of ES modules is not supported.
require() of C:\*******\***********\node_modules\remark\index.js from C:\*******\***********\.next\server\pages\index.js is an ES module file as
it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename C:\***********\********\node_modules\remark\index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\*******\***********\node_modules\remark\package.json.
Here is the file focused on in that part of the tutorial ([id].js):
import { getAllPostIds, getPostData } from '../../lib/posts'
export async function getStaticProps({ params }) {
const postData = await getPostData(params.id)
return {
props: {
postData
}
}
}
export async function getStaticPaths() {
const paths = getAllPostIds()
return {
paths,
fallback: false
}
}
export default function Post({ postData }) {
return (
<html>
{postData.title}
<br />
{postData.id}
<br />
{postData.date}
<br />
<div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
</html>
)
}
And this is the package.json file:
{
"name": "abhayrajio",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"fs": "0.0.1-security",
"gray-matter": "^4.0.3",
"next": "11.0.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"remark": "^14.0.1",
"remark-html": "^13.0.1"
},
"devDependencies": {
"eslint": "7.32.0",
"eslint-config-next": "11.0.1"
}
}
I'm new to this and am just trying to understand how the code works. What is going wrong and what should I do to correct it?
This is the walkthrough link: https://nextjs.org/learn/basics/create-nextjs-app

You can use the previous version of remark and remark-html
"remark": "^13.0.0",
"remark-html": "^13.0.1"

I believe the transpiled code is trying to require() remark which is released as a ES Module which is not entirely supported by Next's webpack config.
It appears to be the same issue raised here https://github.com/vercel/next.js/issues/23725
They recently released a fix on their canary branch, you can try it on your project with npm install next#canary

import { remark } from "remark";

Related

Tailwind with Next.js Error: Expected a backslash preceding the semicolon

I've been struggling with this one for quite a while. Everything was working perfectly and suddenly started failing to compile.
When running npm run dev I get this error:
error - ./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[2]!./styles/global.css
Error: Expected a backslash preceding the semicolon.
at resolveMatches.next ()
at Function.from ()
at runMicrotasks ()
Import trace for requested module:
./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[3].oneOf[9].use[2]!./styles/global.css
./styles/global.css
The tailwind installation was done following this guide from their website: https://tailwindcss.com/docs/guides/nextjs
I have not changed anything after that.
My global.css only contains the three lines needed by tailwind:
#tailwind base;
#tailwind components;
#tailwind utilities;
package.json:
{
"name": "skillsboardai",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#headlessui/react": "^1.7.8",
"#heroicons/react": "^2.0.14",
"i18next": "^22.4.9",
"i18next-browser-languagedetector": "^7.0.1",
"i18next-http-backend": "^2.1.1",
"next": "^13.1.6",
"next-i18next": "^13.0.3",
"openai": "^3.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^12.1.4"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.4"
}
}
My tailwind.config.js:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx}",
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
}
My postcss.config.js:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
And lastly, my _app.js imports the CSS
import React from 'react'
import '../styles/global.css'
import { appWithTranslation } from 'next-i18next';
function App({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default appWithTranslation(App);
I've seen similar posts, but they are related to other frameworks so I wanted to open this thread in case there is any specific actions to take within Next.js.
I am out of ideas and is frustrating, as it was working before.
I have tried:
Removing tailwind: all works fine, but no tailwind of course
Emptying global.css: all works fine, but no tailwind of course
Removing all tailwind classes in my components: did not work
Deleting .next folder and regenerating it: does not work
Deleting also the node_modules and re installing them: does not work
Even went back to my last known-to work commit: DOES NOT WORK EITHER!
I found the solution!
So in one of my components a div had the className [&:not(:focus-visible)]:focus:outline-none
I have no idea why it had that format, most likely some copied class from the web.
Anyway, remove that class, problem solved. Too bad the error given is so vague.

ASTRO / Svelte / Rxfire: Named export 'collectionData' not found

I try to build my astro application. I have one component using svelte and rxFire, but when i try to build id, i receive this error. Try the suggestion bring me to another error like "default member is not exported". It can be a bug from firebase v9 and the compilation from Vite, but how to fix it ?
Package.json
{
"name": "#example/basics",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"#astrojs/svelte": "^1.0.0",
"astro": "^1.2.1",
"firebase": "^9.9.4",
"rxfire": "^6.0.3",
"rxjs": "^7.5.6",
"svelte": "^3.50.1"
}
}
Component:
<script>
import { collection, query } from "firebase/firestore";
import { firestore } from "../../firebase";
import { collectionData } from "rxfire/firestore";
import { startWith, tap } from "rxjs/operators";
import OpportunityCard from "./OpportunityCard.svelte";
const opportunitiesQuery = query(collection(firestore, "opportunities"));
const opportunities = collectionData(opportunitiesQuery, {idField: "id"}).pipe(
tap(x => console.log(x)),
startWith([])
);
</script>
Error during build:
Apply the suggestion:
Something is rather odd here.
In the first case it is supposed to use the ES module file but uses the CommonJS file. In the second case it is supposed to use the CommonJS file, but it uses the ES module file.
You could try to explicitly specify the ES module file:
import { collectionData } from 'rxfire/firestore/index.esm.js';
// Or
import { collectionData } from 'rxfire/firestore/index.esm';

Can't see the css in the static page generated using the export function [duplicate]

I am using NextJS (https://nextjs.org/) Version 9.0.6.
My next.config.js looks like this:
/* eslint-disable */
const withLess = require("#zeit/next-less");
const lessToJS = require("less-vars-to-js");
const fs = require("fs");
const path = require("path");
// Where your antd-custom.less file lives
const themeVariables = lessToJS(
fs.readFileSync(path.resolve(__dirname, "./assets/antd-custom.less"), "utf8")
);
module.exports = withLess({
lessLoaderOptions: {
javascriptEnabled: true,
modifyVars: themeVariables // make your antd custom effective
},
webpack: (config, {
isServer,
defaultLoaders
}) => {
const originalEntry = config.entry;
config.entry = async() => {
const entries = await originalEntry();
if (
entries["main.js"] &&
!entries["main.js"].includes("./polyfills.js")
) {
entries["main.js"].unshift("./polyfills.js");
}
return entries;
};
config.module.rules.push({
test: /\.scss$/,
use: [
defaultLoaders.babel,
{
loader: require("styled-jsx/webpack").loader,
options: {
type: "scoped",
javascriptEnabled: true
}
},
"sass-loader"
]
});
if (isServer) {
const antStyles = /antd\/.*?\/style.*?/;
const origExternals = [...config.externals];
config.externals = [
(context, request, callback) => {
if (request.match(antStyles)) return callback();
if (typeof origExternals[0] === "function") {
origExternals[0](context, request, callback);
} else {
callback();
}
},
...(typeof origExternals[0] === "function" ? [] : origExternals)
];
config.module.rules.unshift({
test: antStyles,
use: "null-loader"
});
}
return config;
}
});
My package.json looks like this:
{
"name": "test",
"version": "0.0.1beta",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"export": "next export"
},
"dependencies": {
"#material/react-chips": "^0.15.0",
"#zeit/next-less": "^1.0.1",
"antd": "^3.24.3",
"babel-plugin-import": "^1.12.2",
"less": "3.10.3",
"less-vars-to-js": "1.3.0",
"next": "9.0.6",
"null-loader": "3.0.0",
"react": "^16.11.0",
"react-country-flag": "^1.1.0",
"react-device-detect": "^1.9.10",
"react-dom": "^16.11.0",
"react-proptypes": "^1.0.0",
"react-redux": "^7.1.1",
"react-string-replace": "^0.4.4",
"redux": "^4.0.4",
"redux-devtools-extension": "^2.13.8",
"redux-persist": "^6.0.0"
},
"devDependencies": {
"babel-eslint": "^10.0.3",
"eslint": "^6.6.0",
"eslint-config-airbnb": "^18.0.1",
"eslint-plugin-babel": "^5.3.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.16.0",
"node-sass": "^4.13.0",
"prettier": "^1.18.2",
"prettier-eslint": "^9.0.0",
"sass-loader": "8.0.0"
},
"license": "ISC"
}
What I did:
-Deleted the out and the .next folder.
Then:
yarn build
yarn export
The pages will be generated, but they are broken (CSS not loaded, no Javascript).
This worked at the beginning of the project, but no it does not.
Is here someone who has an idea why it could be broken ?
I just came across the same issue and landed on this question.
I think Taha explained the problem correctly, but for me a small adaption in the next.config.js did the trick:
module.exports = {
assetPrefix: './'
}
The topic is also described in the NextJS docs.
I came across this question when I had the same problem, I've figured it out.
Inside your index.html file (in the out directory), find the link tag at the beginning of the file:
<link
rel="preload"
href="/_next/static/css/d849fb1b42015bc13208.css"
as="style"
/>
<link
rel="stylesheet"
href="/_next/static/css/d849fb1b42015bc13208.css"
data-n-g=""
/>
Just add a dot "." at the beginning of href attribute, like this:
<link
rel="preload"
href="./_next/static/css/d849fb1b42015bc13208.css"
as="style"
/>
<link
rel="stylesheet"
href="./_next/static/css/d849fb1b42015bc13208.css"
data-n-g=""
/>
This fixed it for me.
I do not know why the "." is not included by default.
I had the same issue recently while trying to export a static version of my app, and was surprised to see no recent issue about that on Next.js repository.
Actually when run through a web server, the use of absolute path for CSS/Js files works correctly. When run as local files in the browser, you have to change them to relative paths yourself.
As for why Next.js team do not provide an option to export with local path, Tim Neutkens (the lead maintainer) states in this issue that "it would involve a lot of work for very minimal gains".
Apart from #Philipp Schemels answer if anyone is using custom fonts via FontSource with StyledComponents, The built CSS file will not point to the correct font files, You will have to manually change those URLs,
The browser console should print a descriptive error which you can use to identify the CSS files that are causing the issue. Custom fonts are usually put in out/_next/static/media
if you are using VS Code and liveserver the problem is that liveserver is defaulting to the root of the project when it needs to set the root to the out folder or wherever you have the rendered files.
This is a setting which you can set per workspace.
Live Server › Settings: Root
Set Custom root of Live Server.
To change root the the server to sub folder of workspace, use '/' and relative path from workspace.
Example: /subfolder1/subfolder2
Then in the workspace settings.json I have:
{
"liveServer.settings.root": "/out"
}

Chakra UI Setup with Next.js Throwing Error

I'm looking to get Chakra UI set up (latest V1) with a simple Next.js app. Having followed the 'getting started' steps at https://chakra-ui.com/docs/getting-started I'm running into the following error when running dev server:
error - ./node_modules/#chakra-ui/portal/dist/esm/portal.js
Attempted import error: 'useCallbackRef' is not exported from '#chakra-ui/hooks'.
Here's my _app.js file:
import { ChakraProvider } from "#chakra-ui/react";
function MyApp({ Component, pageProps }) {
return (
<ChakraProvider>
<Component {...pageProps} />
</ChakraProvider>
);
}
export default MyApp
package.json:
{
"name": "test",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#chakra-ui/react": "^1.1.3",
"#emotion/react": "^11.1.4",
"#emotion/styled": "^11.0.0",
"framer-motion": "^3.2.0",
"next": "10.0.5",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
I've had a rummage through the prescribed portal.js node module, but there doesn't look to be anything untoward.
Any help would be greatly appreciated, thanks for your time in advance.
Set version to #chakra-ui/react": "1.1.2",
It's a bug and they are working on a fix: https://github.com/chakra-ui/chakra-ui/issues/3006
For now just revert to a lower version until the fix is through.
Same problem here, get a older chakra-ui version.
For example: "#chakra-ui/react": "1.0.4"

Module not found: Can't resolve 'fs' in '/vercel/2d531da8/node_modules/mysql/lib/protocol/sequences' when deploying to Vercel

I'm getting the following error when deploying to Vercel:
Module not found: Can't resolve 'fs' in '/vercel/2d531da8/node_modules/mysql/lib/protocol/sequences'
I don't use the dependency fs, my package.json file looks like:
{
"name": "single",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"mysql": "^2.18.1",
"next": "^9.4.4",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"serverless-mysql": "^1.5.4",
"sql-template-strings": "^2.2.2"
}
}
I'm pretty new to NextJS, so I'm not really sure what's going on. Any ideas?
Edit:
For context, I'm getting data from mySQL in the app, not sure if that has anything to do with the error
export async function getStaticProps() {
const db = require('./lib/db')
const escape = require('sql-template-strings')
const articles = await db.query(escape`
SELECT *
FROM articles
ORDER BY pid
`)
const var1 = JSON.parse(JSON.stringify({ articles }))
return {
props: {
var1,
},
}
}
Solved it by creating a next.config.js file and adding the following to it:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
// Important: return the modified config
// Example using webpack option
//config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
config.node = {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
return config
},
webpackDevMiddleware: config => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config
},
}
I had a similar problem whilst following the next.js tutorial. To resolve this I had to also create a next.config.js file as the above answer. However I have only added the following next configurations
module.exports = {
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js']
}
Once I had added the above next.config.js file with the contents above I was able to successfully build the solution.
source: https://newspatrak.com/javascript/cant-build-react-next-project-found-page-without-a-react-component-as-default-export-context-api-file/
Next.js tutorial link: https://nextjs.org/learn/basics/deploying-nextjs-app/deploy

Resources