how can i use styled-component and local font in next js? - next.js

i am using styled-component in my next js app.
and for using it i had to add a babel file with this code:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
i want to use local font and i did it according to the document https://nextjs.org/docs/basic-features/font-optimization.
but problem is here that after using local font the app errors.
it errors that you have to use initial babel.
how can i use both styled-component and local font?

With the release of Next.js 12 you can use styled-components without additional plugins.
Just add styledComponents: true in your next.config.js
const nextConfig = {
...rest of your config,
compiler: {
styledComponents: true,
},
};
module.exports = nextConfig;
A related issue on GitHub

Related

trying to connect the postcss plugin to tailwind

I read instruction PostCSS plugin Guidlines, wrote a simple plugin just for the test.
module.exports = (opts) => {
return {
postcssPlugin: "testplugin",
Once(root) {
console.log("Hello")
},
};
};
module.exports.postcss = true;
But I don't understand how I can connect it to tailwind. I know there is a postcss.config.js file is about the following content
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {}
},
};
but all my attempts to add a plugin there lead to the error
Cannot find module 'testplugin'
i use tailwind 3.1.8 and postcss 8.4.16
my github project
I wrote tailwind plugin but the question remains open
I used an vite - ide development server that provides extensive functionality compared to native ES modules, for example, extremely fast hot module replacement (HMR). it supports PostCSS, for support this feature uses plugin postcss-load-config. in which multiple syntaxes can be supported for objects and arrays. For objects, I still did not understand how to solve the problem, but it turned out with arrays
module.exports = {
plugins: [
require('tailwindcss'),
require('autoprefixer'),
require("./postcss/testplugin")
],
};

How to enable NextJS "next/future/image"?

I'm trying to use Next.js next/future/image experimental component.
I upgraded the Next.js version in package.json to "next": "^12.2.0".
Here's my next.config.js file:
/** #type {import('next').NextConfig} */
const nextConfig = {
strictMode: true,
experimental: {
images: {
allowFutureImage: true,
},
},
images: {
domains: ['firebasestorage.googleapis.com',],
},
};
module.exports = nextConfig;
It doesn't allow me to use this feature. Here's the error message in the browser console:
Error: The "next/future/image" component is experimental and may be subject to breaking changes. To enable this experiment, please include `experimental: { images: { allowFutureImage: true } }` in your next.config.js file.
For Next v13 users:
I believe next/future/image is now the default Image component. So no additional work necessary! Just import and use
import Image from 'next/image'
For Next v12.3 users(like the author of this question)
You don't need to add anything to the config to use future/image. The future image is now stable. Just use it directly by importing
import Image from 'next/future/image'
In fact, adding an images property to the config will cause an error, since the config schema has been updated. So don't do that.
// next.config.js
module.exports = {
experimental: {
images: { // This will cause an error
allowFutureImage: true,
},
},
}
The solution that worked for me was to add the experimental rule and stop the nextjs server and restart it. Then it would start working
module.exports = {
experimental: {
images: {
allowFutureImage: true,
},
},
}
I'm currently working with NextJS version 12.3.1, and if I enable it in the next.config.js then I get an ugly warning on the terminal. So it is best to just import Image from "next/future/image" and not add the config to avoid the Warning. Hope others using 12.3.1 find this useful ( using future/image gets rid of the nasty wrapper divs/spans around the )
Warning I'm seeing with config in place:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn - Invalid next.config.js options detected:
- The value at .experimental has an unexpected property, images, which is not in the list of allowed properties (adjustFontFallbacks, amp, appDir, browsersListForSwc, cpus, craCompat, disableOptimizedLoading, disablePostcssPresetEnv, esmExternals, externalDir, fallbackNodePolyfills, forceSwcTransforms, fullySpecified, gzipSize, incrementalCacheHandlerPath, isrFlushToDisk, isrMemoryCacheSize, largePageDataBytes, legacyBrowsers, manualClientBasePath, modularizeImports, newNextLinkBehavior, nextScriptWorkers, optimizeCss, optimisticClientCache, outputFileTracingRoot, pageEnv, profiling, proxyTimeout, runtime, scrollRestoration, serverComponents, sharedPool, sri, swcFileReading, swcMinify, swcMinifyDebugOptions, swcPlugins, swcTraceProfiling, urlImports, workerThreads).
See more info here: https://nextjs.org/docs/messages/invalid-next-config
warn - You have enabled experimental feature (images) in next.config.js.
warn - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk.

Using vite plugins with Storybook and SvelteKit

I have successfully set up #poppanator/sveltekit-svg with SvelteKit using the following configuration (svelte.config.js):
import preprocess from 'svelte-preprocess';
import svg from '#poppanator/sveltekit-svg';
/** #type {import('#sveltejs/kit').Config} */
const config = {
// Consult https://github.com/sveltejs/svelte-preprocess
// for more information about preprocessors
preprocess: preprocess(),
kit: {
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
vite: {
plugins: [svg()]
}
}
};
export default config;
This works when running the SvelteKit project using npm run dev. However, I cannot get the svg plugin to work inside Storybook.
I have the following Storybook configuration (.storybook/main.cjs):
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx|svelte)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-svelte-csf"
],
"core": {
"builder": "storybook-builder-vite"
},
"svelteOptions": {
preprocess: import("../svelte.config.js").preprocess
}
}
When importing SVG files in Storybook stories (or in components used by the stories), only the file path of the SVG file is returned. When importing SVG files inside a SvelteKit route, a Svelte component is returned as it should be.
I have tried this with Storybook 6.3.10 and 6.4.0-beta.7 with storybook-builder-vite (0.1.0).
How should this go together to make SVG imports work inside Storybook?
While SvelteKit uses Vite, Storybook uses Webpack.
To get svg imports working you'll need to find a loader for webpack that behaves similar to the #poppanator/sveltekit-svg plugin and add that to your storybook configuration.
I'm not sure similar loader exists (yet), depending on your usage, renaming the .svg files to .svelte could be an alternative

Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected

I am trying to import "../../node_modules/react-quill/dist/quill.snow.css"; in my next.js project but I get following error
[ error ] ./node_modules/react-quill/dist/quill.snow.css
Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js.
Read more: https://err.sh/next.js/css-global
Location: components\crud\BlogCreate.js
I managed to make it work with next.config.js. It worked with this configuration
// next.config.js
const withCSS = require('#zeit/next-css');
module.exports = withCSS({
cssLoaderOptions: {
url: false
}
});
But now I am getting a warning,
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://err.sh/next.js/built-in-css-disabled
It seems my solution is not the best way to solve this problem. How could I get rid of this warning?
You may remove the #zeit/next-css plugin because the Next.js 9.3 is very simple. Then Next.js 9.3 is Built-in Sass Support for Global Stylesheets after removing the #zeit/next-css you may install
npm install sass
Then, import the Sass file within pages/_app.js.
Global CSS
Import any global CSS in the /pages/_app.js.
import '../styles.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Importing CSS in components or pages won't work with the built-in CSS support.
Component CSS
Next.js supports CSS Modules using the [name].module.css file naming convention.
components/Button.module.css
/*
You do not need to worry about .error {} colliding with any other `.css` or
`.module.css` files!
*/
.error {
color: white;
background-color: red;
}
components/Button.js
import styles from './Button.module.css'
export function Button() {
return (
<button
type="button"
// Note how the "error" class is accessed as a property on the imported
// `styles` object.
className={styles.error}
>
Destroy
</button>
)
}
CSS Module files can be imported anywhere in your application.
Third-party CSS on Component / Page level
You can use <link> tag in the component.
const Foo = () => (
<div>
<link
href="third.party.css"
rel="stylesheet"
/>
</div>
);
export default Foo;
The loaded stylesheet won't be automatically minified as it doesn't go through build process, so use the minified version.
If none of the options doesn't fit your requirements consider using a custom CSS loader like #zeit/next-css.
In that case you will see a warning which is fine:
Warning: Built-in CSS support is being disabled due to custom CSS configuration being detected.
See here for more info: https://err.sh/next.js/built-in-css-disabled
Suggested reading:
Next.js Built-In CSS Support
Global SASS
CSS Modules
Install sass module by running following command.
npm install sass
You then need to remove all css-loader and sass-loader configuration from next.config.js.
For example, I had to remove the withSass() function (in your case withCSS()) and just return the configuration object.
Had to remove the following lines from next.config.js
{
test: /\.scss$/,
use: {
loader: "sass-loader",
options: {
data: '#import "./scss/_variables.scss"',
sourceMap: true,
},
},
}
Move your options to sassOptions in next config file.
sassOptions: {
data: '#import "./scss/_variables.scss"',
sourceMap: true,
}
Also remove the old #zeit/next-sass and #zeit/next-css from package.json
I had to remove following #zeit dependency from my package.json
"dependencies": {
"#zeit/next-sass": "1.0.1",
This worked for me.
For more details, visit https://nextjs.org/docs/basic-features/built-in-css-support

Angular custom webpack config enable CSS modules

I'm trying to apply CSS modules concept agains my angular app, to order embed it into existing frontend with CSS which unfortunately overlaps. My project uses scss, I want webpack "modulize" my CSS after CSS if formed from scss on last build step I think.
I want to use CSS loader of webpack to achieve this.
But I couldn't make it work.
https://www.npmjs.com/package/#angular-builders/custom-webpack
to order customize my webpack config.
I've tried to apply the next configuration
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
};
and got this error
ERROR in Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError
(1:1) Unknown word
> 1 | exports = module.exports = require("../../../../css-loader/dist/runtime/api.js")(false);
I've tried to find and add css loader into existing
module.exports = (config, options) => {
const rules = config.module.rules || [];
rules.forEach(rule => {
if (String(rule.test) === String(/\.css$/)) {
rule.use.push({ loader: 'css-loader', options: { modules: true }})
}
});
return config;
};
Getting the same error. How to make it work?
Update 1:
I found that angular uses postcss which also provides this functionality as a plugin, postcss-modules. Also still can't make it work.
I was able to implement CSS Modules in Angular with the help of #angular-builders/custom-webpack as you suggested.
However, my solution use postcss-modules and posthtml-css-modules instead of the css-loader to hash the styles.
postcss-modules hash all the styles, then posthtml-css-modules replaces the class names on the html files by the hashed class names.
I documented my solution here:
Live Demo: https://angular-css-modules.herokuapp.com/
Github Repo: https://github.com/gquinteros93/angular-css-modules
Article with the step by step: https://indepth.dev/angular-css-modules/
I hope it will be useful for you.

Resources