Gatsbyjs build error when using jarallax javascript library - reactjs

using Gatsby v2.
I want to use jarallax javascript library (https://free.nkdev.info/jarallax/) in order to put some parallax effect on my index page. It is not a react component, so in order to avoid any incompatibility I just wrap it in a component like:
import React from "react"
import { jarallax } from "jarallax"
class Jarallax extends React.Component {
componentDidMount() {
jarallax(document.querySelectorAll(".jarallax"), { speed: 0.2 })
}
componentWillUnmount() {
jarallax(document.querySelectorAll(".jarallax"), "destroy")
}
render() {
return null
}
}
export default Jarallax
And then in the IndexPage when I want to use it, I just import the component and simply use it like <Jarallax /> and It works on develop
I do also have this gatsby-node.js file following the Gatsby documentation:
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /flickity/,
use: loaders.null(),
},
{
test: /jarallax/, // <--
use: loaders.null(),
},
],
},
})
}
}
Now, if I try to run gatsby build I'm facing this error (https://pastebin.com/CXVaQA5f), but as I'm pretty new to react and to gatsby, not really sure what is the next step now.

I solved this replacing <Jarallax /> for {typeof document !== "undefined" && <Jarallax />} in my IndexPage
this helped me: https://github.com/gatsbyjs/gatsby/issues/9038#issuecomment-432548071

Related

gatsby react-spring-3d issue

Does anyone know how to fix this issue Gatsby with react-spring-3d-carousel:
import Carousel from "react-spring-3d-carousel"
and
<Carousel slides={slides} goToSlide={selectedSlide} />.
I looked in the docs but still appears error: window is not defined
gatsby-node.js
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /react-spring-3d-carousel/,
use: loaders.null(),
},
],
},
})
}
}
Any help would be greatly appreciated
For others that may be facing similar issues, not only related to react-spring-3d-carousel: if adding a null loader to the SSR transpilation doesn't work, the other possible workaround is adding a loadable component, which in fact, what is doing is to perform a code-splitting in the server-side.
import loadable from "#loadable/component";
const Carousel = loadable(() => import("react-spring-3d-carousel"))

React Storybook SVG Failed to execute 'createElement' on 'Document'

I'm trying to add Storybook to an existing React app but getting errors with imported svg files. The svg is imported and used like:
import Border from './images/border.inline.svg'
...
<Border className="card__border" />
This works when the app is run and built, but I get an error in Storybook. How come?
Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
Error: Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
The default webpack.config.js has:
...
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
},
...
Also, the existing code uses webpack 3, and I'm using Storybook V4.
This is happening because Storybook's default webpack config has its own svg config:
{
test: /\.(svg|ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/,
loader: 'file-loader',
query: { name: 'static/media/[name].[hash:8].[ext]' }
},
I'm pretty sure this is the cause, because you can see the path outlined in error message: query: { name: 'static/media/[name].[hash:8].[ext]' } -> static/media/border.inline.258eb86a.svg
The solution can be to find the existing loader & change / or add an exclude rule to it. Here's an example of a custom .storybook/webpack.config.js:
// storybook 4
module.exports = (_, _, config) => {
// storybook 5
module.exports = ({ config }) => {
const rules = config.module.rules;
// modify storybook's file-loader rule to avoid conflicts with your inline svg
const fileLoaderRule = rules.find(rule => rule.test.test('.svg'));
fileLoaderRule.exclude = /\.inline.svg$/;
rules.push({
test: /\.inline.svg$/,
...
}],
});
return config;
};
It appears that Storybook V6 they have changed the default Webpack config. I found that the above answers didn't work for me.
They no longer have an SVG rule, therefore testing for SVG will either error or return back undefined.
There is a oneOf rule on the module.rules which contains a loader without a test as the last rule:
{
loader: '/Users/alexwiley/Work/OneUp/resources/client/node_modules/react-scripts/node_modules/file-loader/dist/cjs.js',
exclude: [Array],
options: [Object]
}
This is the culprit, you need to make sure that the file load is excluding all inline SVG file otherwise it will error.
Add the following to your .storybook/main.js file:
webpackFinal: async(config, { configType }) => {
config.module.rules.forEach((rule) => {
if (rule.oneOf) {
// Iterate over the oneOf array and look for the file loader
rule.oneOf.forEach((oneOfRule) => {
if (oneOfRule.loader && oneOfRule.loader.test('file-loader')) {
// Exclude the inline SVGs from the file loader
oneOfRule.exclude.push(/\.inline\.svg$/);
}
});
// Push your SVG loader onto the end of the oneOf array
rule.oneOf.push({
test: /\.inline\.svg$/,
exclude: /node_modules/,
loader: 'svg-react-loader', // use whatever SVG loader you need
});
}
});
return config;
}
In Storybook 6, You have to import it like this:
import { ReactComponent as Border } from './images/border.inline.svg'
Try that if it also works for your version since this question is from a year ago.
This is another way that fixed the issue for me
import Border from './images/border.inline.svg'
And then in your code
<img src={Border} alt="Border" className="w-25"/>
I got it working with
...
module.exports = {
module: {
rules: [
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
}
]
}
}
For me it was happening as I was using wrong tag name:
import React from 'react';
import RMDBLogo from '../../images/react-movie-logo.svg';
import TMDBLogo from '../../images/tmdb_logo.svg';
import { Wrapper, Content,LogoImg,TMDBLogoImg } from './Header.styles';
const Header = () => (
<Wrapper>
<Content>
<LogoImg src={RMDBLogo} alt='RMDBLogo' />
<TMDBLogo src={TMDBLogo} alt='TMDBLogo'/>
</Content>
</Wrapper>
);
export default Header;
I had imported TMDBLogoImg component while I'm using TMDBLogo tag inside Content tag.

Warning: Prop `className` did not match. when using styled components with semantic-ui-react

I use this code to margin my Button from top:
const makeTopMargin = (elem) => {
return styled(elem)`
&& {
margin-top: 1em !important;
}
`;
}
const MarginButton = makeTopMargin(Button);
and whenever i use MarginButton node, I get this error: Warning: PropclassNamedid not match. Server: "ui icon left labeled button sc-bwzfXH MjXOI" Client: "ui icon left labeled button sc-bdVaJa fKCkqX"
You can see this produced here.
What should I do?
This warning was fixed for me by adding an .babelrc file in the project main folder, with the following content:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
See following link for an example:
https://github.com/nblthree/nextjs-with-material-ui-and-styled-components/blob/master/.babelrc
Or you could just add this to your next.config.js. This also makes it so next-swc (speedy web compiler) works to reduce build times. See more here.
// next.config.js
module.exports = {
compiler: {
// Enables the styled-components SWC transform
styledComponents: true
}
}
You should install the babel plugin for styled-components and enable the plugin in your .babelrc
npm install --save-dev babel-plugin-styled-components
.babelrc
{
"plugins": [
[
"babel-plugin-styled-components"
]
]
}
The main reason I am posting this answer to help people understand the tradeoff. When we're using .babelrc in next project it's going to opt of SWC compiler which is based on Rust (Learn More).
It's going to show message something like this when you opt for custom bable config.
info - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc"
I did more digging on this to only find out following! Ref
Next.js now uses Rust-based compiler SWC to compile
JavaScript/TypeScript. This new compiler is up to 17x faster than
Babel when compiling individual files and up to 5x faster Fast
Refresh.
So tradeoff was really huge, we can lose significant amout of performance. So I found a better solution which can solve this issue and keep SWC as default compiler.
You can add this experimental flag in your next.config.js to prevent this issue. Ref
// next.config.js
module.exports = {
compiler: {
// ssr and displayName are configured by default
styledComponents: true,
},
}
If you have already added babel plugins, delete the .next build folder & restart the server again
credit: Parth909 https://github.com/vercel/next.js/issues/7322#issuecomment-912415294
I was having the exact same issue and it was resolved by doing:
npm i babel-preset-next
npm install --save -D babel-plugin-styled-components
and adding this to .babelrc file:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
Styled components server side rendering
Server Side Rendering styled-components supports concurrent server
side rendering, with stylesheet rehydration. The basic idea is that
everytime you render your app on the server, you can create a
ServerStyleSheet and add a provider to your React tree, that accepts
styles via a context API.
This doesn't interfere with global styles, such as keyframes or
createGlobalStyle and allows you to use styled-components with React
DOM's various SSR APIs.
import { renderToString } from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
const sheet = new ServerStyleSheet()
try {
const html = renderToString(sheet.collectStyles(<YourApp />))
const styleTags = sheet.getStyleTags() // or sheet.getStyleElement();
} catch (error) {
// handle error
console.error(error)
} finally {
sheet.seal()
}
import { renderToString } from 'react-dom/server'
import { ServerStyleSheet, StyleSheetManager } from 'styled-components'
const sheet = new ServerStyleSheet()
try {
const html = renderToString(
<StyleSheetManager sheet={sheet.instance}>
<YourApp />
</StyleSheetManager>
)
const styleTags = sheet.getStyleTags() // or sheet.getStyleElement();
} catch (error) {
// handle error
console.error(error)
} finally {
sheet.seal()
}
In my case as im using nextjs
import Document, { Head, Main, NextScript } from "next/document";
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet();
const page = renderPage(App => props =>
sheet.collectStyles(<App {...props} />)
);
const styleTags = sheet.getStyleElement();
return { ...page, styleTags };
}
render() {
return (
<html>
<Head>{this.props.styleTags}</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
I have solved this issue following these steps.
Create a file named .babelrc in the root directory and configure the .babelrc file.
delete the .next build folder(It stores some caches).
Restart the server.
Hot reload the browser.
.babelrc configuration file
{
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
PropType errors are runtime errors that will let you know that the data expected being passed to a prop is not what is expected. It looks like the className prop that is being set on your component is not the same when the component is rendered on the server and when it is then rendered in the client's DOM.
Since it looks like you are using server side rendering, you need to make sure that your class names are deterministic. That error is showing you the class that is being created by your styled-components library on the server and how it is different from the DOM. For libraries that do not normally have deterministic class names, you need to look at advanced configurations. Take a look at the styled-components documentation regarding specificity as it pertains to SSR.
//1. I got an error when using material-ui with Next.js
/********************************************* */
//2. The code I imported was like this :
const useStyles = makeStyles({
root: { // root must change
width: 100 ,
}
});
const Footer = () => {
const classes = useStyles();
return (
<div className={classes.root} > { /* root must change */}
<p> footer copyright #2021 </p>
</div>
)
}
export default Footer;
/********************************************* */
//3. I changed the code like this :
const useStyles = makeStyles({
footer: { // changed here to footer
width: "100%",
backgroundColor: "blue !important"
}
});
const Footer = () => {
const classes = useStyles();
return (
<div className={classes.footer} > { /* changed here to footer */}
<p> footer copyright #2021 </p>
</div>
)
}
export default Footer;
// I hope it works
For Old versions form Nextjs < 12, Go to next.config.js file and add this line inside nextConfig object:
experimental: {
// Enables the styled-components SWC transform
styledComponents: true
}
for new NextJs above 12:
compiler: {
styledComponents: true
}
if that does not work you need to make an NO SSR component wrapper like this:
// /components/NoSsr.js
import dynamic from 'next/dynamic'
const NoSsr = ({ children }) => <>{children}</>
export default dynamic(() => Promise.resolve(NoSsr), { ssr: false })
Then you need to add warp No SSR with your component like this:
// /pages/index.js
import NoSsr from '../components/NoSsr'
import CircleButton from '../components/buttons/CircleButton'
const HomePage = () => {
return (
<>
<p>Home Page Title</p>
<NoSsr>
{/* Here your styled-component */}
<makeTopMargin ele={...} />
</NoSsr>
</>
)
}
I'm using NextJS 12 and encountered the same issue, well error in the console, code was working ok.
I fixed it by creating a .babelrc file at the root of the project and add:
{
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
Styled Components have full, core, non-experimental support in Next now (2022), but you have to turn them on:
Add the following to your next.config.js:
compiler: {
styledComponents: true,
},
My full, mostly vanilla, next.config.js now looks like this:
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
compiler: {
// Enables the styled-components SWC transform
styledComponents: true,
},
}
module.exports = nextConfig
https://nextjs.org/blog/next-12-1#improved-swc-support
I followed all the other advice, around setting up .babelrc (or .babelrc.js), but noticed this message in the Next.js docs:
When css-in-js libraries are not set up for pre-rendering (SSR/SSG) it will often lead to a hydration mismatch. In general this means the application has to follow the Next.js example for the library. For example if pages/_document is missing and the Babel plugin is not added.
That linked to this file, showing that I needed to add this to pages/_document.tsx to:
// if you're using TypeScript use this snippet:
import React from "react";
import Document, {DocumentContext, DocumentInitialProps} from "next/document";
import {ServerStyleSheet} from "styled-components";
export default class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext,
): Promise<DocumentInitialProps> {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}
A blog post by Raúl Sánchez also mentions this solution, linking to the JavaScript version if you're not using TS (pages/_document.js):
// if you're *not* using TypeScript use this snippet:
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
If you are using create-react-app, you can use thi solution.
File called styled.ts
import styled from 'styled-components/macro';
import { css } from 'styled-components';
export const ListRow = styled.div`
...
...
`
Based on the files name, the prefix will be as following.
`${file_name}__{styled_component_name} ${unique_id}`
Meaning when implemented it will have the following classname
Although it would be nice to specify from where the first prefix would be taken from, meaning instead of file_name, we take folder_name. I currently dont know the solution for it.
To expand on C. Molindijk's answer, this error occurs when server-side class is different from client-side because styled-components generates its own unique class Id's. If your Next app is server-side rendered, then his answer is probably correct. However, Next.Js is by default statically generated, so unless you enabled SSR, configure it like this without ssr set to true:
{
"presets": ["next/babel"],
"plugins": [["styled-components"]]
}
This answer is for those who are using NextJs version > v12.0.1 and SWC compiler. You don't have to add _document.js file nor do babel related stuff anymore since it has been replaced by SWC compiler since v12.0.0. Only that your next.config.js file should look like the following since NextJs supports styled components after v12.1.0 and restart the server and it should work: more here
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
// add the following snippet
compiler: {
styledComponents: true,
},
};
module.exports = nextConfig;

SCSS compilation in an isomorphic React app

I'm writing an isomorphic React app based on :
https://github.com/choonkending/react-webpack-node
Instead of css modules used in the examples I'd like to use scss though. And for some reason I'm having a really hard time getting them to work. My first step was to remove the css webpack loaders from both the server and the client configs replacing them with scss-specific loaders (as well as removing postcss) :
loaders: [
'style-loader',
'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:3]',
'sass-loader?sourceMap',
]
But this throws ReferenceError: window is not defined when building as style-loader is apparently not suitable for server-side rendering. So my next idea was to use isomorphic-style-loader. As far as I understand to get it working I need to decorate my component with their higher order component withStyles:
import React, { PropTypes } from 'react';
import classNames from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from '../assets/scss/common/index.scss';
const App = (props, context) => (
<div className={classNames('app')}>
<h1 className="home_header">Welcome!</h1>
{props.children}
</div>
);
export default withStyles(s)(App);
and then do some trickery in the code rendering page on the server. But the problem is, example from the package docs shows a flux action fired inside Express (https://libraries.io/npm/isomorphic-style-loader#webpack-configuration), and the boilerplate that I'm using uses react-router. So I'm kinda lost as how should I inject this object with insertCss into context. I tried this :
import React from 'react';
import { renderToString } from 'react-dom/server';
import { RouterContext, match, createMemoryHistory } from 'react-router';
import axios from 'axios';
import { Provider } from 'react-redux';
import createRoutes from 'routes.jsx';
import configureStore from 'store/configureStore';
import headconfig from 'components/Meta';
import { fetchComponentDataBeforeRender } from 'api/fetchComponentDataBeforeRender';
const clientConfig = {
host: process.env.HOSTNAME || 'localhost',
port: process.env.PORT || '3001'
};
// configure baseURL for axios requests (for serverside API calls)
axios.defaults.baseURL = `http://${clientConfig.host}:${clientConfig.port}`;
function renderFullPage(renderedContent, initialState, head = {
title: 'cs3',
css: ''
}) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
${head.title}
${head.link}
<style type="text/css">${head.css.join('')}</style>
</head>
<body>
<div id="app">${renderedContent}</div>
<script type="text/javascript">window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};</script>
<script type="text/javascript" charset="utf-8" src="/assets/app.js"></script>
</body>
</html>
`;
}
export default function render(req, res) {
const history = createMemoryHistory();
const store = configureStore({
project: {}
}, history);
const routes = createRoutes(store);
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
const css = [];
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
const context = { insertCss: (styles) => css.push(styles._getCss()) };
const InitialView = (
<Provider context={context} store={store}>
<RouterContext {...renderProps} />
</Provider>
);
fetchComponentDataBeforeRender(store.dispatch, renderProps.components, renderProps.params)
.then(() => {
const componentHTML = renderToString(InitialView);
const initialState = store.getState();
res.status(200).end(renderFullPage(componentHTML, initialState, {
title: 'foo',
css
}));
})
.catch(() => {
res.end(renderFullPage('', {}));
});
} else {
res.status(404).send('Not Found');
}
});
}
but I'm still getting Warning: Failed context type: Required context 'insertCss' was not specified in 'WithStyles(App)'. Any ideas how to tackle this ? And more importantly - is there no easier way to do it ? This seems like a lot of additional work.
There's a few parts to handling scss compilation with webpack when you're doing server-side rendering. First of all, you don't want node trying to import .scss files into your components.
So set a global variable WEBPACK: true in your webpack config:
plugins: [
new webpack.DefinePlugin({
'process.env': {
WEBPACK: JSON.stringify(true),
}
})
],
And in your components, only attempt to import .scss files if the component is being handled by webpack (either during build or development):
if (process.env.WEBPACK) require('../assets/scss/common/index.scss');
If you only have one Sass file per component (you should) then this is always just a one-liner. Any additional Sass files can be imported inside index.scss if you need to.
Then in your config you probably still want the css loader, so it should look like this for your dev server:
{
test: /\.s?css$/,
loaders: ['style', 'css', 'sass']
},
And something like this for you build config:
{
test: /\.s?css$/,
loader: ExtractTextPlugin.extract('style', 'css!sass')
},

Proper way to implement jwplayer in react component using webpack (react-starter-kit)

i am making VideoPlayer react component with jwpalyer and i am using webpack es6 for loading module
webpack support npm module loading & there is no npm for jwplayer
so am trying to include jwplayer.js using es6 import but it giving me error
ReferenceError: window is not defined
so any one can help me to properly setup jwplayer with webpack
import React, { PropTypes, Component } from 'react';
import $ from 'jquery';
import Player from "./lib/jwplayer/jwplayer.js";
import styles from './VideoPayer.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
#withStyles(styles)
class VideoPlayer extends Component {
static propTypes = {
className: PropTypes.string,
};
static defaultProps = {
file: '',
image: ''
};
constructor(props) {
super(props);
this.playerElement = document.getElementById('my-player');
}
componentDidMount() {
if(this.props.file) {
this.setupPlayer();
}
}
componentDidUpdate() {
if(this.props.file) {
this.setupPlayer();
}
}
componentWillUnmount() {
Player().remove(this.playerElement);
}
setupPlayer() {
if(Player(this.playerElement)) {
Player(this.playerElement).remove();
}
Player(this.playerElement).setup({
flashplayer: require('./lib/player/jwplayer.flash.swf'),
file: this.props.file,
image: this.props.image,
width: '100%',
height: '100%',
});
}
render() {
return (
<div>
<div id="my-player" className="video-player"></div>
</div>
)
}
}
export default VideoPlayer;
I think this is what you need to do:
Define window as external to the bundle so that references to it in other libraries are not mangled.
Expose a global variable jwplayer so that you can attach your key
(Optional) Create an alias to your jwplayer library
I've tested it and this configuration works for me, but only on the client and not on the server or isomorphically/universally.
webpack.config.js:
// Declare window as external
externals: {
'window': 'Window'
},
// Create an easy binding so we can just import or require 'jwplayer'
resolve: {
alias: {
'jwplayer':'../path/to/jwplayer.js'
}
},
// Expose jwplayer as a global variable so we can attach the key, etc.
module: {
loaders: [
{ test: /jwplayer.js$/, loader: 'expose?jwplayer' }
]
}
Then you can import jwplayer from 'jwplayer' and require('jwplayer').
Probably an old question but I recently found a relatively stable solution.
I include the jwplayer in a folder called app/thirdparty/jwplayer-7.7.4. Next, add it to the exclude in the babel loader so it is not parsed.
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /(node_modules|thirdparty)/,
}
I then use dynamic import in order to bootstrap my component and load jwplayer.
async function bootstrap(Component: React.Element<*>) {
const target = document.getElementById('root');
const { render } = await import('react-dom');
render(<Component />, target);
}
Promise.all([
import('app/components/Root'),
import('app/thirdparty/jwplayer-7.7.4/jwplayer.js'),
]).then(([ { default: Root } ]) => {
window.jwplayer.key = "<your key>";
bootstrap(Root);
});

Resources