Code Monkey home page Code Monkey logo

media-query-splitting-plugin's Introduction

media-query-splitting-plugin

Webpack 4 plugin for styles splitting by media query. Demo

Npm Version Month Downloads Npm Licence

This plugin is addition to mini-css-extract-plugin. It splits styles from style chunks by media query and creates separate CSS files for mobile, tablet and desktop.

Instalation

npm install --save-dev media-query-splitting-plugin

Chunk before applying

0.04a9302b77ca5a27bfee.css - chunk includes all styles and media queries

Chunk after applying

0.04a9302b77ca5a27bfee.css - common chunk includes the styles without media query conditions
0.desktop.04a9302b77ca5a27bfee.css - styles for desktop media query, by default it's (min-width: 1025px)
0.tabletLandscape.04a9302b77ca5a27bfee.css - (min-width: 769px) and (max-width: 1024px)
0.tabletPortrait.04a9302b77ca5a27bfee.css - (min-width: 569px) and (max-width: 768px)
0.tablet.04a9302b77ca5a27bfee.css - styles for both tabletLandscape and tabletPortrait
0.mobile.04a9302b77ca5a27bfee.css - (max-width: 568px)

Also it handles loading of this files depending of the client's screen width, it happens on loading new chunk or on window resize.

Options

This is default options, it can be omitted.

{
  media: {
    mobileEnd: 568,
    tabletPortraitEnd: 768,
    tabletLandscapeEnd: 1024,
  },
  splitTablet: true,
}

You can define your own media breakpoints in the media option. The plugin will create regular expression to check is media query fit input media query rule. Also if you define splitTablet: false on the client side won't be used tabletPortrait or tabletLandscape styles. Instead will be used tablet style which includes both landscape and portrait.

Pay attention that on server side we can't define by user-agent which tablet version the client used - landscape or portrait, that's why we send tablet version in the response. After user receives that response, the next chunk loading happens on client side (for example when user go to another page of our app), so than we can match browser media and load suitable tablet version.

Install

npm install --save-dev media-query-splitting-plugin

Usage

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const MediaQuerySplittingPlugin = require('media-query-splitting-plugin')

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css',
      chunkFilename: '[id].[contenthash].css',
    }),
    new MediaQuerySplittingPlugin({
      // This is default config (optional)
      media: {
        mobileEnd: 568,
        tabletPortraitEnd: 768,
        tabletLandscapeEnd: 1024,
      },
      splitTablet: true,
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ]
      }
    ]
  }
}

Server side rendering

The plugin splits each css asset to common chunk (which should be always included to the response) and media chunk (for desktop, tabletPortrait / tabletLandscape / tablet (includes portrait and landscape) or mobile, which should be included depending on client's device).

How to use it with SSR.

All you need is to define client device type (mobile, tablet or desktop) and add style chunk for this device in addition to the common chunk. For example if you use express.js you can define device type depending on req.headers['user-agent'] (use express-device middleware to handle it).

Example:

  const { getBundles } = require('react-loadable/webpack')
  const assets = require('assets.json') // webpack-assets-manifest

  const bundles  = getBundles(loadableAssets, loadableModules).filter(({ file }) => !/map$/.test(file))

  const styles   = (
    bundles
      .filter((bundle) => bundle.file.endsWith('.css'))
      .concat({ publicPath: assets.client.css })
      .map(({ publicPath }) => {
        const { isMobile, isTablet } = req

        let mediaType     = 'desktop'

        if (isMobile) {
          mediaType       = 'mobile'
        }
        else if (isTablet) {
          mediaType       = 'tablet'
        }

        const chunkId     = publicPath.replace(/.*\//,'').replace(/\..*/, '')
        const mediaPath   = publicPath.replace(chunkId, `${chunkId}.${mediaType}`)

        return `
          <link rel="stylesheet" href="${publicPath}" /> // Common chunk (0.04a9302b77ca5a27bfee.css)
          <link rel="stylesheet" href="${mediaPath}" />  // Media chunk  (0.${mediaType}.04a9302b77ca5a27bfee.css)
        `
      })
  )

media-query-splitting-plugin's People

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.