diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6fc1fc4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# general +.DS_Store +node_modules + +# prefer npm +yarn.lock + +# exclude unit testing output +test/output \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ab60297 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f4551a --- /dev/null +++ b/README.md @@ -0,0 +1,159 @@ +# Media Query Plugin + +Have you ever thought about extracting your media queries from your CSS so a mobile user doesn't have to load desktop specific CSS? +If so this plugin is what you need! + +When writing CSS with the help of a framework (such as [Bootstrap](https://getbootstrap.com/) or [Foundation](https://foundation.zurb.com/sites.html)) and with a modular design pattern you'll mostly end up with CSS that contains all media queries. Using this plugin lets you easily extract the media queries from your CSS and load it async. + +So instead of forcing the user to load this + +```css +.foo { color: red } +@media print, screen and (min-width: 75em) { + .foo { color: blue } +} +.bar { font-size: 1rem } +``` + +he only has to load this always + +```css +.foo { color: red } +.bar { font-size: 1rem } +``` + +and on desktop viewport size this in addition + +```css +@media print, screen and (min-width: 75em) { + .foo { color: blue } +} +``` + + +## Prerequisites + +You should already have a working webpack configuration before you try to use this plugin. If you haven't used webpack yet please go through the [webpack guide](https://webpack.js.org/guides/) first and start using this awesome tool for your assets mangement! + +## Installation + +Simply install the package with your prefered package manager. + +- npm +```bash +npm install media-query-plugin --save-dev +``` + +- yarn +```bash +yarn add media-query-plugin --dev +``` + +## Let's get started + +### 1. Loader + +The plugin comes together with a loader which takes care of the CSS extraction from the source and provides it for the injection afterwards. You are able to override the plugin options via the loader options. But usually this shouldn't be necessary and can be left empty. + +**Important:** make sure the loader receives plain CSS so place it between the css-loader and the sass-loader/less-loader. + +```javascript +const MediaQueryPlugin = require('media-query-plugin'); + +module.exports = { + module: { + rules: [ + { + test: /\.scss$/, + use: [ + MiniCssExtractPlugin.loader, + 'css-loader', + MediaQueryPlugin.loader, + 'postcss-loader', + 'sass-loader' + ] + } + ] + } +}; +``` + +### 2. Plugin + +Add the plugin to your webpack config. It will inject the extracted CSS of the loader after the compilation. +The two options `include` and `queries` are required for the plugin to work and get explained later. + +```javascript +const MediaQueryPlugin = require('./plugins/media-query-plugin'); + +module.exports = { + plugins: [ + new MediaQueryPlugin({ + include: [ + 'example' + ], + queries: { + 'print, screen and (min-width: 75em)': 'desktop' + } + }) + ] +}; +``` + +### 3. Extracted Files + +If you use dynamic imports, webpack will try to resolve that import and throw an error if the file does not exist. Thus you have to create those empty files manually in the same folder(s) as the source file which generates the CSS. + +**Important:** the names of those files must follow the pattern `[source name]-[query name]` so an example file could be `example-desktop.scss`. If you don't do this the plugin will extract the specified media queries from the source file but not inject them anywhere. + +Afterwards you can simply do this in your JavaScript and webpack will take care of the rest for you + +```javascript +import(/* webpackChunkName: 'example' */ './example.scss'); + +if (window.innerWidth >= 1200) { + import(/* webpackChunkName: 'example-desktop' */ './example-desktop.scss'); +} +``` + +## Options + +As mentioned earlier there are two options required (either via plugin or via loader options) + +### include + +Each chunk (which uses the loader) gets checked if its name matches this option. In case of a match each query specified in the `queries` options gets extracted from the chunk. + +Possible types +- array (e.g. `[example]`) +- regex (e.g. `/example/`) +- boolean (e.g. `true`) + +### queries + +This option tells the plugin which media queries are supposed to get extracted. If a media query doesn't match it'll stay untouched. Otherwise it gets extracted and afterwards injected into the chunk with the name `[source name]-[query name]`. + +**Important:** make sure the keys match 100% the source CSS excl the `@media`. + +**Tip:** you can use the same name for different media queries to concatenate them (e.g. desktop portrait and desktop landscape) + +```javasript +queries: { + 'print, screen and (max-width: 60em) and (orientation: portrait)': 'desktop', + 'print, screen and (max-width: 60em) and (orientation: landscape)': 'desktop' +} +``` + +## Not using webpack? + +This plugin is built for webpack only and can't be used with other module bundlers (such as [FuseBox](https://fuse-box.org/)) or task runners (such as [Gulp](https://gulpjs.com/)). However if you can't or don't want to use webpack but nevertheless want to extract media queries you should check out my [PostCSS plugin](https://github.com/SassNinja/postcss-extract-media-query) which supports much more tools. + +However it also breaks out of the bundler/runner and emits files within the PostCSS plugin which will ignore all other pipes in your task. +So it's highly recommended to use this webpack plugin instead of the PostCSS alternative! + +## Contribution + +This plugin has been built because I wasn't able to find a webpack solution for such a trivial task of loading media queries async. It works for my use cases by I'm pretty sure it can get more improved. So if you miss any feature don't hesitate to create an issue as feature request or to create a PR to do the job. + +**And last but not least, if you like this plugin please give it a star on github and share it!** + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c55e0a7 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,97 @@ +{ + "name": "media-query-plugin", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "big.js": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-3.2.0.tgz", + "integrity": "sha512-+hN/Zh2D08Mx65pZ/4g5bsmNiZUuChDiQfTUQ7qJr4/kuopCr88xZsAXv6mBoZEsUI4OuGHlX59qE94K2mMW8Q==" + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.2.tgz", + "integrity": "sha512-3NUJZdhMhcdPn8vJ9v2UQJoH0qqoGUkYTgFEPZaPjEtwmmKUfNV46zZmgB2M5M4DCEQHMaCfWHCxiBflLm04Tg==", + "requires": { + "color-name": "1.1.1" + } + }, + "color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha1-SxQVMEz1ACjqgWQ2Q72C6gWANok=" + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "json5": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-0.5.1.tgz", + "integrity": "sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=" + }, + "loader-utils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.1.0.tgz", + "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", + "requires": { + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" + } + }, + "postcss": { + "version": "6.0.22", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-6.0.22.tgz", + "integrity": "sha512-Toc9lLoUASwGqxBSJGTVcOQiDqjK+Z2XlWBg+IgYwQMY9vA2f7iMpXVc1GpPcfTSyM5lkxNo0oDwDRO+wm7XHA==", + "requires": { + "chalk": "^2.4.1", + "source-map": "^0.6.1", + "supports-color": "^5.4.0" + } + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==" + }, + "supports-color": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.4.0.tgz", + "integrity": "sha512-zjaXglF5nnWpsq470jSv6P9DwPvgLkuapYmfDm3JWOm0vkNTVF2tI4UrN2r6jH1qM/uc/WtxYY1hYoA2dOKj5w==", + "requires": { + "has-flag": "^3.0.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..17a87bf --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "media-query-plugin", + "version": "0.0.1", + "description": "Webpack plugin for media query extraction.", + "author": "Kai Falkowski", + "license": "MIT", + "main": "src/index.js", + "scripts": { + "test": "mocha" + }, + "keywords": [ + "webpack", + "plugin", + "loader", + "mediaquery", + "extract", + "split", + "css" + ], + "dependencies": { + "loader-utils": "^1.1.0", + "postcss": "^6.0.22" + }, + "devDependencies": {}, + "repository": { + "type": "git", + "url": "https://github.com/SassNinja/media-query-plugin.git" + } +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..7ed728d --- /dev/null +++ b/src/index.js @@ -0,0 +1,9 @@ + +const loader = require('./loader'); +const plugin = require('./plugin'); + +// provide easy access to the loader +plugin.loader = require.resolve('./loader'); + +// export default webpack plugin +module.exports = plugin; \ No newline at end of file diff --git a/src/loader.js b/src/loader.js new file mode 100644 index 0000000..30ea7b4 --- /dev/null +++ b/src/loader.js @@ -0,0 +1,39 @@ + +const { getOptions, interpolateName } = require('loader-utils'); +const postcss = require('postcss'); +const store = require('./store'); +const plugin = require('./postcss'); + +module.exports = function(source) { + + // make loader async + const cb = this.async(); + + // merge loader's options with plugin's options from store + const options = Object.assign(store.options, getOptions(this)); + + // basename gets used later for key in media query store + options.basename = interpolateName(this, '[name]', { content: '' }); + + let isIncluded = false; + + // check if current file should be affected + if (typeof options.include === 'object' && options.include.indexOf(options.basename) > -1) { + isIncluded = true; + } else if (options.include instanceof RegExp && options.basename.match(options.include)) { + isIncluded = true; + } else if (options.include === true) { + isIncluded = true; + } + + // return (either modified or not) source + if (isIncluded === true) { + postcss([ plugin(options) ]) + .process(source, { from: options.basename }) + .then(result => { + cb(null, result.toString()) + }); + } else { + cb(null, source); + } +}; \ No newline at end of file diff --git a/src/plugin.js b/src/plugin.js new file mode 100644 index 0000000..de029ba --- /dev/null +++ b/src/plugin.js @@ -0,0 +1,50 @@ + +const pluginName = 'MediaQueryPlugin'; + +const store = require('./store'); +const escapeUtil = require('./utils/escape'); + +module.exports = class MediaQueryPlugin { + + constructor(options) { + options = Object.assign({ + include: [], + queries: {} + }, options); + + // save in store to provide to loader + store.options = options; + } + + apply(compiler) { + + compiler.hooks.compilation.tap(pluginName, compilation => { + compilation.hooks.finishModules.tap(pluginName, (modules) => { + + for (const module of modules) { + + const basename = module.rawRequest + ? module.rawRequest + .match(/([\w-]+)(\.[\w-]+)+(\?.*)?$/)[0] + .replace(/\..+$/, '') + : undefined; + + // check if store contains extraction for current basename + if (basename && store.hasMedia(basename)) { + + const css = store.getMedia(basename); + + // inject the extracted css + if (module._source._value.match(/exports\.push/)) { + const regex = /exports\.push\(\[module\.id, ".*"/gm; + module._source._value = module._source._value + .replace(regex, `exports.push([module.id, ${ escapeUtil(css) }`); + } + } + } + + }); + }); + + } +}; diff --git a/src/postcss.js b/src/postcss.js new file mode 100644 index 0000000..332a6b6 --- /dev/null +++ b/src/postcss.js @@ -0,0 +1,27 @@ + +const postcss = require('postcss'); +const store = require('./store'); + +module.exports = postcss.plugin('MediaQueryPostCSS', options => { + + function addToStore(name, atRule) { + + const css = postcss.root().append(atRule).toString(); + + store.addMedia(name, css); + } + + return (css, result) => { + + css.walkAtRules('media', atRule => { + + const queryname = options.queries[atRule.params]; + + if (queryname) { + const name = `${options.basename}-${queryname}`; + addToStore(name, atRule); + atRule.remove(); + } + }); + }; +}); \ No newline at end of file diff --git a/src/store.js b/src/store.js new file mode 100644 index 0000000..d391045 --- /dev/null +++ b/src/store.js @@ -0,0 +1,25 @@ + +class MediaQueryStore { + + constructor() { + this.media = {}; + this.options = {}; + } + + addMedia(key, css) { + if (typeof this.media[key] !== 'object') { + this.media[key] = []; + } + this.media[key].push(css); + } + + hasMedia(key) { + return !!this.media[key]; + } + + getMedia(key) { + return this.media[key].join('\n'); + } +}; + +module.exports = new MediaQueryStore(); \ No newline at end of file diff --git a/src/utils/escape.js b/src/utils/escape.js new file mode 100644 index 0000000..43c4d18 --- /dev/null +++ b/src/utils/escape.js @@ -0,0 +1,20 @@ +// Utility to escape a string. +// Taken over from css-loader +// https://github.com/webpack-contrib/css-loader/blob/master/lib/url/escape.js + +module.exports = function escape(url) { + if (typeof url !== 'string') { + return url + } + // If url is already wrapped in quotes, remove them + if (/^['"].*['"]$/.test(url)) { + url = url.slice(1, -1); + } + // Should url be wrapped? + // See https://drafts.csswg.org/css-values-3/#urls + if (/["'() \t\n]/.test(url)) { + return '"' + url.replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"' + } + + return url +} \ No newline at end of file