what is the best way to load global styles and images for Storybook in NextJS?
Below are the following Storybook files (config.js and scs-loader.scss and webpack.config.js)
webpack.config.js
module.exports = ({ config }) => {
config.module.rules.push({
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [require.resolve('babel-preset-react-app')],
},
});
config.resolve.extensions.push('.ts', '.tsx');
config.module.rules.push({
test: /\.(svg|ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/,
loader: require.resolve('file-loader')
});
return config;
};
config.js
import '!file-loader!style-loader!css-loader!sass-loader!./scss-loader.scss';
import { configure } from '#storybook/react';
configure(require.context('../components', true, /\.stories\.(j|t)sx?$/), module);
scss.loader.scss
#import '../styles/global.scss';
Using the above config I can get a successful Storybook build however I do not see any global styles nor do I see any images referenced in global.scss
If i remove the file-loader in config.js as follows
import '!style-loader!css-loader!sass-loader!./scss-loader.scss';
import { configure } from '#storybook/react';
configure(require.context('../components', true, /\.stories\.(j|t)sx?$/), module);
I see this error.
Error: Can't resolve '/images/hero.jpg' in 'D:\dev\personal\nextjs-ts\.storybook'
If I then go and remove all the images from global.scss I can then load Storybook and I can see the global styles however I've lost all the images. I need to try and get images and global styles working in tandem. Thanks.
Here is an example of how the images are referenced in global.scss.
.hero {
width: 100%;
height: 800px;
background: url('/images/hero.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
Related
I added font to react typescript project after that I try to build but its showing error
Error during bundle: Error: Unexpected character '' (Note that you need plugins to import files that are not JavaScript)
Adding font using styled-components and loader using is url-loader
fonts work fine in system and no error while run.
Font extension is ttf. Below is my style file using styled-component
import IBMPlexSansSemiBold from './fonts/IBMPlexSans/IBMPlexSans-SemiBold.ttf';
import IBMPlexSansBold from './fonts/IBMPlexSans/IBMPlexSans-Bold.ttf';
import { font} from './Fonts';
export const FontsIBM = createGlobalStyle`
#font-face {
font-family: ${font.DEFAULT.SEMI_BOLD};
src: local('IBMPlexSans-SemiBold'), local(${font.DEFAULT.SEMI_BOLD}),
url(${IBMPlexSansSemiBold}) format('truetype');
font-weight: 600;
font-style: normal;
}
#font-face {
font-family: ${font.DEFAULT.BOLD};
src: local('IBMPlexSans-Bold'), local(${font.DEFAULT.BOLD}),
url(${IBMPlexSansBold}) format('truetype');
font-weight: 700;
font-style: normal;
}
`;
This is how I config url-loader
const rootMain = require('../../../.storybook/main');
module.exports = {
...rootMain,
core: { ...rootMain.core, builder: 'webpack5' },
stories: [
...rootMain.stories,
'../src/lib/**/*.stories.mdx',
'../src/lib/**/*.stories.#(js|jsx|ts|tsx)',
],
addons: [...rootMain.addons, '#nrwl/react/plugins/storybook'],
staticDirs: ['../../../public'],
webpackFinal: async (config, { configType }) => {
// apply any global webpack configs that might have been specified in .storybook/main.js
if (rootMain.webpackFinal) {
config = await rootMain.webpackFinal(config, { configType });
}
//Font added using url-loader
config.module.rules.push({
test: /\.(ttf|eot|woff|woff2)$/,
loader: require.resolve('url-loader'),
options: {
name: '[name].[hash].[ext]',
},
});
// add your own webpack tweaks if needed
return config;
},
};
This question already has answers here:
Self-hosted fonts using NextJS
(4 answers)
Closed 1 year ago.
I have a problem when I try to add self hosted font in Material UI 5 with Next.js. I got this error:
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)
Even I have added file-loader in next.config.js here:
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader'],
},
],
},
};
And this is my custom theme:
PS: my font name in local is BarcadeBrawl.ttf.
import { createTheme } from "#mui/material";
import { purple, blue } from '#mui/material/colors';
import BarcadeBrawl from '../assets/fonts/BarcadeBrawl.ttf'
export const theme = createTheme({
palette: {
primary: {
main: purple[500],
},
secondary: {
main: blue[500],
},
},
typography: {
fontFamily: 'BarcadeBrawl',
fontSize: 12,
},
components: {
MuiCssBaseline: {
styleOverrides: `
#font-face {
font-family: 'BarcadeBrawl';
font-style: normal;
font-display: swap;
font-weight: 400;
src: local('BarcadeBrawl'), local('BarcadeBrawl'), url(${BarcadeBrawl}) format('ttf');
unicodeRange: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF;
}
`,
},
},
});
Firstly, that's not how Webpack is configured in Next.js. Refer the official documentation on this - Custom Webpack Config. Secondly, file-loader is deprecated for Webpack v5 (the default for newer Next.js versions). Use asset modules instead.
So you probably need to do something like this:
// next.config.js
// https://webpack.js.org/guides/asset-management/#loading-fonts
module.exports = {
// other configs...
// future: { webpack5: true }, // -- not needed since Next.js v11.0.0
webpack(config) {
config.module.rules.push({
test: /\.(woff|woff2|eot|ttf|otf)$/i,
issuer: { and: [/\.(js|ts|md)x?$/] },
type: 'asset/resource',
});
return config;
},
};
Moreover, this is not necessary, you can simply store your fonts directory in public directory and use them. There is no need to import them. They can be directly referenced like /fonts/BarcadeBrawl.ttf. Refer: Static File Serving
It throws DOM EXCEPTION
styles file
import { fontUrls1 } from './Fonts/Amaranth-Bold.ttf';
const GlobalStyle = createGlobalStyle`
#font-face {
font-family: 'Amaranth-Bold';
src: url('${fontUrls1}') format('truetype');
}
body {
font-family: 'Amaranth-Bold';
}
body.fontLoaded {
font-family: 'Amaranth-Bold' ;
}'
My app.js file
const openUberMoveLightObserver = new FontFaceObserver('Amaranth-
Bold',{});
Executing this line throws an error.
openUberMoveLightObserver.load().then(() => {
document.body.classList.add('fontLoaded');
});
Uncaught (in promise) DOMException
You don't need to import fonts to add into styles....
You can do this just passing url to the fonts
like this.....
export const MyFonts = createGlobalStyle`
#font-face {
font-family: 'Metropolis';
src: url(/static/fonts/Metropolis-ExtraLight.ttf);
src: url(/static/fonts/Metropolis-Light.ttf);
src: url(/static/fonts/Metropolis-LightItalic.ttf);
src: url(/static/fonts/Metropolis-Medium.ttf);
src: url(/static/fonts/Metropolis-Regular.ttf);
src: url(/static/fonts/Metropolis-SemiBold.ttf);
}
`;
OR
export const MyFonts = createGlobalStyle`
#import url('/static/fonts/Metropolis-ExtraLight.ttf');
#import url('/static/fonts/Metropolis-Light.ttf');
#import url('/static/fonts/Metropolis-LightItalic.ttf');
#import url('/static/fonts/Metropolis-Medium.ttf');
#import url('/static/fonts/Metropolis-Regular.ttf');
#import url('/static/fonts/Metropolis-SemiBold.ttf');
`;
you can use this font by importing inside your component
import React from 'react';
import MyFonts from './MyFonts';
function Example(){
return (
<div>
<MyFonts />
....
</div>
)
}
export default Example
You need to add a specific loader to load the font. For example if you are using webpack then you can use url-loader as below:
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
exclude: path.resolve(__dirname, "node_modules"),
use: [
{
loader: "url-loader",
options: {
prefix: "font",
limit: 10000,
mimetype: "application/octet-stream"
}
}
] }
I have a SSR React-TypeScript app, built on Webpack 4 and I use SCSS for each React component. I use two Webpack config files, one for the client bundle and one for the server bundle.
I am in a bind as to how to use the MiniCssExtractPlugin to load my SCSS on the client Webpack config. The documentation isn't very helpful. It is evident that this rule is necessary inside modules:
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
But it isn't clear what file should go here:
plugins: [
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
})
],
My SCSS files are spread throughout my application: each React component has its own SCSS file. I don't know how to pass these files to MiniCssExtractPlugin.
For the server Webpack config, I have the following to load my SCSS files and I don't know whether or not it's sufficient:
{
test: /\.scss$/,
use: ["css-loader", "sass-loader"]
}
I would love to see an actual working example of a similar app, if possible.
My css file as generated by MiniCSS:
.home {
text-align: center; }
.home-logo {
animation: home-logo-spin infinite 20s linear;
height: 40vmin;
pointer-events: none; }
.home-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white; }
.home-link {
color: #61dafb; }
#keyframes home-logo-spin {
from {
transform: rotate(0deg); }
to {
transform: rotate(360deg); } }
/*# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9zcmMvY2xpZW50L3ByZXNlbnRhdGlvbmFsLWNvbXBvbmVudHMvaG9tZS9Ib21lLnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQSxxQkFBcUI7O0FBRXJCO0FBQ0E7QUFDQTtBQUNBLHVCQUF1Qjs7QUFFdkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGVBQWU7O0FBRWY7QUFDQSxpQkFBaUI7O0FBRWpCO0FBQ0E7QUFDQSw0QkFBNEI7QUFDNUI7QUFDQSw4QkFBOEIsRUFBRSIsImZpbGUiOiJzdHlsZXMuY3NzIiwic291cmNlc0NvbnRlbnQiOlsiLmhvbWUge1xuICB0ZXh0LWFsaWduOiBjZW50ZXI7IH1cblxuLmhvbWUtbG9nbyB7XG4gIGFuaW1hdGlvbjogaG9tZS1sb2dvLXNwaW4gaW5maW5pdGUgMjBzIGxpbmVhcjtcbiAgaGVpZ2h0OiA0MHZtaW47XG4gIHBvaW50ZXItZXZlbnRzOiBub25lOyB9XG5cbi5ob21lLWhlYWRlciB7XG4gIGJhY2tncm91bmQtY29sb3I6ICMyODJjMzQ7XG4gIG1pbi1oZWlnaHQ6IDEwMHZoO1xuICBkaXNwbGF5OiBmbGV4O1xuICBmbGV4LWRpcmVjdGlvbjogY29sdW1uO1xuICBhbGlnbi1pdGVtczogY2VudGVyO1xuICBqdXN0aWZ5LWNvbnRlbnQ6IGNlbnRlcjtcbiAgZm9udC1zaXplOiBjYWxjKDEwcHggKyAydm1pbik7XG4gIGNvbG9yOiB3aGl0ZTsgfVxuXG4uaG9tZS1saW5rIHtcbiAgY29sb3I6ICM2MWRhZmI7IH1cblxuQGtleWZyYW1lcyBob21lLWxvZ28tc3BpbiB7XG4gIGZyb20ge1xuICAgIHRyYW5zZm9ybTogcm90YXRlKDBkZWcpOyB9XG4gIHRvIHtcbiAgICB0cmFuc2Zvcm06IHJvdGF0ZSgzNjBkZWcpOyB9IH1cbiJdLCJzb3VyY2VSb290IjoiIn0=*/
My Header.tsx is:
import * as React from 'react';
import "./header.css"
export default class Header extends React.Component {
public render() {
return <div id="Header">
</div>;
}
}
and header.css is:
#Header{
height: 100px;
width: 100%;
background-color: white;
}
When I run m project i get this error:
NodeInvocationException: Prerendering failed because of error: Error: Module parse failed: E:\Tools\ClientApp\components\header.css Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
How can I fix it ?
You need to use css-loader for import and use css files in react applications.
First install css-loader:
npm install --save-dev css-loader
Then add css-loader to your webpack config:
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
}