Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[examples] Add example to alias styled-components with Next.js #27087

Closed
2 tasks done
hboylan opened this issue Jul 3, 2021 · 8 comments · Fixed by #27088
Closed
2 tasks done

[examples] Add example to alias styled-components with Next.js #27087

hboylan opened this issue Jul 3, 2021 · 8 comments · Fixed by #27088
Labels
docs Improvements or additions to the documentation

Comments

@hboylan
Copy link
Contributor

hboylan commented Jul 3, 2021

  • The issue is present in the latest release. (next v5)
  • I have searched the issues of this repository and believe that this is not a duplicate.

Current Behavior 😯

Setting the webpack alias to target styled-components does not work for nextjs.

Error: Cannot find module '@emotion/styled'
Full stack
Error: Cannot find module '@emotion/styled'
Require stack:
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/@material-ui/styled-engine/node/index.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/@material-ui/system/index.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/@material-ui/core/node/styles/adaptV4Theme.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/@material-ui/core/node/styles/index.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/.next/server/pages/_document.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/next-server/server/require.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/next-server/server/load-components.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/next-server/server/api-utils.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/next-server/server/next-server.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/server/next.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/server/lib/start-server.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/cli/next-dev.js
- /Users/hugh/Development/node/material-ui/examples/nextjs-with-styled-components-typescript/node_modules/next/dist/bin/next

Expected Behavior 🤔

Webpack alias should replace @material-ui/styled-engine with styled-components version.

// next.config.js
module.exports = {
  webpack: config => {
    config.resolve.alias['@material-ui/styled-engine'] = '@material-ui/styled-engine-sc'
    return config
  },
}

Steps to Reproduce 🕹

Steps:

  1. Add webpack alias for styled-components using above config. ☝🏻
  2. Add tsconfig paths for styled-components:
{
  "compilerOptions": {
    "paths": {
      "@material-ui/styled-engine": ["./node_modules/@material-ui/styled-engine-sc"]
    }
}
  1. Create theme.ts:
import { createTheme } from '@material-ui/core/styles'

export default createTheme()
  1. Update _document.tsx:
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
import theme from 'styles/theme';

// https://material-ui.com/styles/advanced/#next-js
export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          {/* PWA primary color */}
          <meta content={theme.palette.primary.main} name="theme-color" />
          <link
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

MyDocument.getInitialProps = async (ctx) => {
  // Step 1: Create an instance of ServerStyleSheet
  const sheet = new ServerStyleSheet();

  // Step 2: Retrieve styles from components in the page
  const view = ctx.renderPage((App) => (props) => sheet.collectStyles(<App {...props} />));

  // Step 3: Extract the styles as <style> tags
  const styleTags = sheet.getStyleElement();

  // Step 4: Pass styleTags as a prop
  return { ...view, styleTags };
};
  1. Update _app.tsx:
import CssBaseline from '@material-ui/core/CssBaseline';
import { StyledEngineProvider, ThemeProvider } from '@material-ui/core/styles';
import type { AppProps } from 'next/app';
import Head from 'next/head';
import theme from 'styles/theme';

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
        <title>Next App</title>
        <link href="/favicon.ico" rel="icon" />
        <meta content="minimum-scale=1, initial-scale=1, width=device-width" name="viewport" />
      </Head>
      <StyledEngineProvider injectFirst={true}>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <Component {...pageProps} />
        </ThemeProvider>
      </StyledEngineProvider>
    </>
  );
}

Context 🔦

Trying to upgrade NextJS app from MUI v4 to v5 using styled-components instead of emotion.

I'd like to add an example for this solution once I get it working. Something like material-ui/examples/nextjs-with-styled-components-typescript

Your Environment 🌎

`npx @material-ui/envinfo`
Browser:
    Brave: Version 1.25.70 Chromium: 91.0.4472.77 (Official Build) (x86_64)
System:
    OS: macOS 11.4
  Binaries:
    Node: 14.17.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 6.14.13 - /usr/local/bin/npm
  Browsers:
    Chrome: 91.0.4472.114
    Edge: 90.0.818.56
    Firefox: 87.0
    Safari: 14.1.1
  npmPackages:
    @material-ui/core: next => 5.0.0-beta.0 
    @material-ui/private-theming:  5.0.0-beta.0 
    @material-ui/styled-engine:  5.0.0-beta.0 
    @material-ui/styled-engine-sc: next => 5.0.0-beta.0 
    @material-ui/system:  5.0.0-beta.0 
    @material-ui/types:  6.0.1 
    @material-ui/unstyled:  5.0.0-alpha.39 
    @material-ui/utils:  5.0.0-beta.0 
    @types/react: latest => 17.0.13 
    react: latest => 17.0.2 
    react-dom: latest => 17.0.2 
    styled-components: latest => 5.3.0 
    typescript: latest => 4.3.5 
@hboylan hboylan added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Jul 3, 2021
@hboylan
Copy link
Contributor Author

hboylan commented Jul 3, 2021

Created draft PR to demonstrate the issue and hopefully provide a helpful example once it's resolved.
#27088

@oliviertassinari oliviertassinari added docs Improvements or additions to the documentation and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Jul 5, 2021
@oliviertassinari oliviertassinari changed the title Unable to alias styled-components with nextjs [examples] Add example to alias styled-components with Next.js Jul 5, 2021
@oliviertassinari
Copy link
Member

@hboylan Great initiative, we talked about doing this in #6115 (comment).

@hboylan
Copy link
Contributor Author

hboylan commented Jul 5, 2021

Thanks, I'm glad this is on the community's radar. It's also reassuring to see the performance results you mentioned there.

@LucasBassetti
Copy link

I'm still having this issue, even trying the #27088 .

Do someone has a different solution?

@willianantunes
Copy link

@LucasBassetti same here. Hope to fix it soon. What I tried so far can be consulted here.

@willianantunes
Copy link

@LucasBassetti I made some changes (like including this) and now it's working as expected. It has some delays when I navigate between index and about pages (maybe not a true SPA navigation, but a back-end one), but as it's a new project, I'll look at it later. I hope it helps you!

@willianantunes
Copy link

Coming back because I had one issue: actually I had to install '@emotion/react' and '@emotion/styled' packages to make jest run properly. I don't know how to solve it. Apart from that, everything seems fine.

@thomasmery
Copy link

Hi there,

chiming in because I'm facing the same problem and can't seem to solve it

I cannot run the examples/nextjs-with-styled-components-typescript

without installing @emotion/react & @emotion/styled

MODULE_NOT_FOUND errors are thrown server side

I thought just running the example should work

any insight on this?

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Improvements or additions to the documentation
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants