Home > Mobile >  How to split MUI v5 theme into separate files by theme options?
How to split MUI v5 theme into separate files by theme options?

Time:11-17

I have a very big MUI v5 theme with around 800 lines (including TypeScript type augmentation). Something like this:

let myTheme = createTheme({
  palette: {
    primary: {
      // lots of custom props
    },
    secondary: {
      // lots of custom props
    },
  },

  typography: {
    // lots of custom variants
  },
});

I'd like to split this huge file into separate files by theme props. Like this:

  • palette.ts
  • typography.ts
  • ...etc.

Then in theme.ts create a theme based on these files. How can I do that? And how to manage TypeScript type augmentation in this case (where to keep type augmentation).

CodePudding user response:

You don't fully expand the theme code and theme props but I usually build out my themes from a directory called theme and my createTheme is within an index.js file:

primary

primary.ts with it's logic

const primary = {
  // lots of custom props
}

export default primary

secondary

secondary.ts with it's logic

const secondary = {
  // lots of custom props
}

export default secondary

typography

typography.ts with it's logic

const typography = {
  // lots of custom props
}

export default typography

theme

bring in the files and add them:

import primary from './primary.ts'
import secondary from './secondary.ts'
import typography from './typography.ts'

const myTheme = createTheme({
  palette: {
    primary,
    secondary
  },
  typography
});
  • Related