Customize Ant design with Next.js - reactjs

I am using ant design in my next.js project. but I want to customize it, for example: " #primary-color: orange; "
I searched the internet and installed all the necessary npm packages, but since I have no webpack knowledge, I got different errors every time I tried. I tried many different codes in next.config.js but I got different errors for all of them. Can someone please explain to me how to do this?
here my folder tree :
and here my next.config.js file :
I would like to state in advance that I do not know anything about webpack.
const withSass = require("#zeit/next-sass");
const withLess = require("#zeit/next-less");
const withCSS = require("#zeit/next-css");
const isProd = process.env.NODE_ENV === "production";
// fix: prevents error when .less files are required by node
if (typeof require !== "undefined") {
require.extensions[".less"] = (file) => {};
}
module.exports = withCSS({
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
localIdentName: "[local]___[hash:base64:5]",
},
...withLess(
withSass({
lessLoaderOptions: {
javascriptEnabled: true,
},
})
),
});
and here my error :
yarn run v1.22.17
warning ../../../package.json: No license field
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled
TypeError: Cannot set properties of undefined (setting 'styles')
at module.exports (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/#zeit/next-css/css-loader-config.js:25:56)
at Object.webpack (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/#zeit/next-css/index.js:15:36)
at Object.getBaseWebpackConfig [as default] (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/build/webpack-config.js:1379:32)
at async Promise.all (index 0)
at async Span.traceAsyncFn (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/trace/trace.js:74:20)
at async Span.traceAsyncFn (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/trace/trace.js:74:20)
at async HotReloader.start (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/server/dev/hot-reloader.js:325:25)
at async DevServer.prepare (/Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/server/dev/next-dev-server.js:290:9)
at async /Users/hashim/Desktop/bakucosy/bakucosy-app/node_modules/next/dist/cli/next-dev.js:128:9
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
➜ bakucosy-app git:(master) ✗

Related

Why is my amplify environment variable appearing for just a moment then disappearing again [duplicate]

So i'm using the Contentful API to get some content from my account and display it in my Next.Js app (i'm using next 9.4.4). Very basic here. Now to protect my credentials, i'd like to use environment variables (i've never used it before and i'm new to all of this so i'm a little bit losted).
I'm using the following to create the Contentful Client in my index.js file :
const client = require('contentful').createClient({
space: 'MYSPACEID',
accessToken: 'MYACCESSTOKEN',
});
MYSPACEID and MYACCESSTOKEN are hardcoded, so i'd like to put them in an .env file to protect it and don't make it public when deploying on Vercel.
I've created a .env file and filled it like this :
CONTENTFUL_SPACE_ID=MYSPACEID
CONTENTFUL_ACCESS_TOKEN=MYACCESSTOKEN
Of course, MYACCESSTOKEN and MYSPACEID contains the right keys.
Then in my index.js file, i do the following :
const client = require('contentful').createClient({
space: `${process.env.CONTENTFUL_SPACE_ID}`,
accessToken: `${process.env.CONTENTFUL_ACCESS_TOKEN}`,
});
But it doesn't work when i use yarn dev, i get the following console error :
{
sys: { type: 'Error', id: 'NotFound' },
message: 'The resource could not be found.',
requestId: 'c7340a45-a1ef-4171-93de-c606672b65c3'
}
Here is my Homepage and how i retrieve the content from Contentful and pass them as props to my components :
const client = require('contentful').createClient({
space: 'MYSPACEID',
accessToken: 'MYACCESSTOKEN',
});
function Home(props) {
return (
<div>
<Head>
<title>My Page</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main id="page-home">
<Modal />
<NavTwo />
<Hero item={props.myEntries[0]} />
<Footer />
</main>
</div>
);
}
Home.getInitialProps = async () => {
const myEntries = await client.getEntries({
content_type: 'mycontenttype',
});
return {
myEntries: myEntries.items
};
};
export default Home;
Where do you think my error comes from?
Researching about my issue, i've also tried to understand how api works in next.js as i've read it could be better to create api requests in pages/api/ but i don't understand how to get the content and then pass the response into my pages components like i did here..
Any help would be much appreciated!
EDIT :
So i've fixed this by adding my env variables to my next.config.js like so :
const withSass = require('#zeit/next-sass');
module.exports = withSass({
webpack(config, options) {
const rules = [
{
test: /\.scss$/,
use: [{ loader: 'sass-loader' }],
},
];
return {
...config,
module: { ...config.module, rules: [...config.module.rules, ...rules] },
};
},
env: {
CONTENTFUL_SPACE_ID: process.env.CONTENTFUL_SPACE_ID,
CONTENTFUL_ACCESS_TOKEN: process.env.CONTENTFUL_ACCESS_TOKEN,
},
});
if you are using latest version of nextJs ( above 9 )
then follow these steps :
Create a .env.local file in the root of the project.
Add the prefix NEXT_PUBLIC_ to all of your environment variables.
eg: NEXT_PUBLIC_SOMETHING=12345
use them in any JS file like with prefix process.env
eg: process.env.NEXT_PUBLIC_SOMETHING
You can't make this kind of request from the client-side without exposing your API credentials. You have to have a backend.
You can use Next.js /pages/api to make a request to Contentful and then pass it to your front-end.
Just create a .env file, add variables and reference it in your API route as following:
process.env.CONTENTFUL_SPACE_ID
Since Next.js 9.4 you don't need next.config.js for that.
By adding the variables to next.config.js you've exposed the secrets to client-side. Anyone can see these secrets.
New Environment Variables Support
Create a Next.js App with Contentful and Deploy It with Vercel
Blog example using Next.js and Contentful
I recomended to update at nextjs 9.4 and up, use this example:
.env.local
NEXT_PUBLIC_SECRET_KEY=i7z7GeS38r10orTRr1i
and in any part of your code you could use:
.js
const SECRET_KEY = process.env.NEXT_PUBLIC_SECRET_KEY
note that it must be the same name of the key "NEXT_PUBLIC_ SECRET_KEY" and not only "SECRET_KEY"
and when you run it make sure that in the log says
$ next dev
Loaded env from E:\awesome-project\client\.env.local
ready - started server on http://localhost:3000
...
To read more about environment variables see this link
Don't put sensitive things in next.config.js however in my case I have some env variables that aren't sensitive at all and I need them Server Side as well as Client side and then you can do:
// .env file:
VARIABLE_X=XYZ
// next.config.js
module.exports = {
env: {
VARIABLE_X: process.env.VARIABLE_X,
},
}
You have to make a simple change in next.config.js
const nextConfig = {
reactStrictMode: true,
env:{
MYACCESSTOKEN : process.env.MYACCESSTOKEN,
MYSPACEID: process.env.MYSPACEID,
}
}
module.exports = nextConfig
change it like this
Refer docs
You need to add a next.config.js file in your project. Define env variables in that file and those will be available inside your app.
npm i --save dotenv-webpack#2.0.0 // version 3.0.0 has a bug
create .env.development.local file in the root. and add your environment variables here:
AUTH0_COOKIE_SECRET=eirhg32urrroeroro9344u9832789327432894###
NODE_ENV=development
AUTH0_NAMESPACE=https:ilmrerino.auth0.com
create next.config.js in the root of your app.
const Dotenv = require("dotenv-webpack");
module.exports = {
webpack: (config) => {
config.resolve.alias["#"] = path.resolve(__dirname);
config.plugins.push(new Dotenv({ silent: true }));
return config;
},
};
However those env variables are gonna be accessed by the server. if you want to use any of the env variables you have to add one more configuration.
module.exports = {
webpack: (config) => {
config.resolve.alias["#"] = path.resolve(__dirname);
config.plugins.push(new Dotenv({ silent: true }));
return config;
},
env: {
AUTH0_NAMESPACE: process.env.AUTH0_NAMESPACE,
},
};
For me, the solution was simply restarting the local server :)
Gave me a headache and then fixed it on accident.
It did not occur to me that env variables are loaded when the server is starting.

Webpack obfuscator not working with craco, maps disabled

today I have a very large problem using react & craco, I can't seem to get my webpack-obfuscator to do anything. I have disabled source maps, but to no avail.
This is my craco config:
const path = require("path");
const WebpackObfuscator = require('webpack-obfuscator');
module.exports = {
webpack: {
configure: (webpackConfig) => {
// Because CEF has issues with loading source maps properly atm,
// lets use the best we can get in line with `eval-source-map`
if (webpackConfig.mode === 'development' && process.env.IN_GAME_DEV) {
webpackConfig.devtool = 'eval-source-map'
webpackConfig.output.path = path.join(__dirname, 'build')
}
return webpackConfig
},
plugins: {
add: [
new WebpackObfuscator ({
rotateStringArray: true
}),
],
},
},
devServer: (devServerConfig) => {
if (process.env.IN_GAME_DEV) {
// Used for in-game dev mode
devServerConfig.writeToDisk = true
}
return devServerConfig
}
}
I get no visible maps files when building, and I've put "GENERATE_SOURCEMAP=false" in my .env file that's located where the package.json is.
Hopefully someone has the answer as to why this is happening.
Kind regards, and thanks for reading.
To upgrade a short config, you can use a construct that, if the condition is met, updates the configuration without using WebpackObfuscator:
module.exports = {
webpack: {
configure: {
...(process.env.IN_GAME_DEV && process.env.NODE_ENV === 'development' && {devtool: 'eval-source-map'})
}
}
}
Also, if you need additional properties for the configuration, in addition to the dvttool, you can add them

When does webpack cli comes into play

How is webpack-cli used in a project?
From what I understand, as soon as I enter npm run start on my bash terminal, webpack starts running the webpack config file where I have written rules to convert jsx to js using babel, scss/less to css (correct me if I'm wrong).
But where does webpack-cli comes into play in all this?
The webpack-dev-server package is responsible to serve the build over an http server that it creates for it. It also re-starts if you make any changes to the source code (when using the hot reload option).
On the other hand, the webpack-cli package is responsible for the build and bundle of the source files. So, webpack-dev-server has to run the webpack-cli.
So you've got to have both of the packages installed.
You can see kind of how it does that in here:
https://github.com/webpack/webpack-dev-server/blob/master/bin/webpack-dev-server.js
/** #type {CliOption} */
const cli = {
name: 'webpack-cli',
package: 'webpack-cli',
binName: 'webpack-cli',
installed: isInstalled('webpack-cli'),
url: 'https://github.com/webpack/webpack-cli',
preprocess() {
process.argv.splice(2, 0, 'serve');
},
};
// ...
const runCli = (cli) => {
if (cli.preprocess) {
cli.preprocess();
}
const path = require('path');
const pkgPath = require.resolve(`${cli.package}/package.json`);
// eslint-disable-next-line import/no-dynamic-require
const pkg = require(pkgPath);
// eslint-disable-next-line import/no-dynamic-require
require(path.resolve(path.dirname(pkgPath), pkg.bin[cli.binName]));
};
// ...
runCommand(packageManager, installOptions.concat(cli.package))
.then(() => {
runCli(cli);
})
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
In webpack v5, that order kind of got reversed since you use webpack server, which is a webpack-cli call, to initiate the serve, that will call the webpack-dev-server package.
I'm not a webpack expert by any means, but I think this will help you to understand it better.

Error with Next Js with Expo when compiling

Im getting this error if I try to use the expo components in my next Js
To be clear im using an expo with next js for the web, and so I wanted both to share the same components which to my knowledge was possible but I'm getting this error.
The error is:
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
(Source code omitted for this binary file)
and this is the next.config.js :
// Learn more: https://github.com/expo/expo/blob/master/docs/pages/versions/unversioned/guides/using-nextjs.md#withexpo
const { withExpo } = require('#expo/next-adapter');
module.exports = withExpo({
projectRoot: __dirname,
});
and this is the babel config:
// Learn more: https://github.com/expo/expo/blob/master/docs/pages/versions/unversioned/guides/using-nextjs.md#shared-steps
module.exports = { presets: ['#expo/next-adapter/babel'] };
please help and hope the info is enough
Try replacing next.config.js with this ( & npm install next-images next-fonts)
const { withExpo } = require('#expo/next-adapter')
const withImages = require('next-images')
const withFonts = require('next-fonts')
module.exports = withExpo(
withImages(
withFonts({
projectRoot: __dirname,
})
)
);

Monaco editor with nextjs

Getting this error when using monaco editor with next js.
Have anyone resolved this?
Failed to compile
./node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.css
Global CSS cannot be imported from within node_modules.
Read more: https://err.sh/next.js/css-npm
Location: node_modules/monaco-editor/esm/vs/base/browser/ui/actionbar/actionbar.js```
Add this webpack config fixed it for me
const withCSS = require('#zeit/next-css');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = withCSS({
webpack(config, options) {
config.plugins.push(new MonacoWebpackPlugin());
return config;
},
cssLoaderOptions: { url: false }
})
#monaco-editor/react third party helper
I'm not sure why it works, I would rather avoid third party stuff, but this is he first thing I got to work, they just package it so nicely, so here it is:
https://www.npmjs.com/package/#monaco-editor/react
https://github.com/suren-atoyan/monaco-react
you can get rid of MonacoWebpackPlugin when using that.
Key dependencies I tested with:
"dependencies": {
"#monaco-editor/react": "4.2.1",
"next": "11.0.1",
"monaco-editor": "0.26.1",
Then usage is as described on README. They expose a Editor component helper, but you can also get a monaco instance if you want.
Related:
https://dev.to/swyx/how-to-add-monaco-editor-to-a-next-js-app-ha3
https://github.com/react-monaco-editor/react-monaco-editor/issues/271
https://github.com/resourcesco/snippets/blob/master/docs/monaco-editor-with-next.md
https://github.com/react-monaco-editor/react-monaco-editor/issues/334
https://github.com/ritz078/transform/issues/282

Resources