Skip to content

Commit

Permalink
Support PostCSS 8 (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
cl1ck authored and giuseppeg committed Nov 24, 2020
1 parent 231a54b commit 66d07da
Show file tree
Hide file tree
Showing 10 changed files with 821 additions and 438 deletions.
1 change: 1 addition & 0 deletions .prettierignore
@@ -0,0 +1 @@
*.css
54 changes: 30 additions & 24 deletions README.md
Expand Up @@ -32,48 +32,54 @@ With config:
```json
{
"plugins": [
["styled-jsx/babel", {
"plugins": [
[
"styled-jsx-plugin-postcss",
{
"path":
"[PATH_PREFIX]/postcss.config.js"
}
[
"styled-jsx/babel",
{
"plugins": [
[
"styled-jsx-plugin-postcss",
{
"path": "[PATH_PREFIX]/postcss.config.js"
}
]
]
]
}]
}
]
]
}
```

### Example with CRA

Usage with Create React App requires you to either _eject_ or use [react-app-rewired](https://github.com/timarney/react-app-rewired).
Usage with Create React App requires you to either _eject_ or use [react-app-rewired](https://github.com/timarney/react-app-rewired).

Here is an example using `react-app-rewired`:

```javascript
// config-overrides.js
// this file overrides the CRA webpack.config

const { getBabelLoader } = require('react-app-rewired')
const { getBabelLoader } = require("react-app-rewired");

module.exports = function override (config, env) {
const loader = getBabelLoader(config.module.rules)
module.exports = function override(config, env) {
const loader = getBabelLoader(config.module.rules);

// Older versions of webpack have `plugins` on `loader.query` instead of `loader.options`.
const options = loader.options || loader.query
options.plugins = [['styled-jsx/babel', {
'plugins': ['styled-jsx-plugin-postcss']
}]].concat(options.plugins || [])
return config
}
const options = loader.options || loader.query;
options.plugins = [
[
"styled-jsx/babel",
{
plugins: ["styled-jsx-plugin-postcss"],
},
],
].concat(options.plugins || []);
return config;
};
```

_Note: Please follow their instructions on how to set up build & test scripts, and make sure you have a correctly formatted `postcss.config.js` as well_.


#### Notes

`styled-jsx-plugin-postcss` uses `styled-jsx`'s plugin system which is supported
Expand All @@ -82,13 +88,13 @@ from version 2. Read more on their repository for further info.
## Plugins

`styled-jsx-plugin-postcss` uses
[`postcss-load-plugins`](https://www.npmjs.com/package/postcss-load-plugins)
[`postcss-load-config`](https://www.npmjs.com/package/postcss-load-config)
therefore you may want to refer to their docs to learn more about
[adding plugins](https://www.npmjs.com/package/postcss-load-plugins#packagejson).
[adding plugins](https://www.npmjs.com/package/postcss-load-config#packagejson).

## Contributions

**PRs and contributions are welcome!**
**PRs and contributions are welcome!**

We aim to drive development of this plugin through community contributions.

Expand Down
4 changes: 2 additions & 2 deletions fixture-invalid-config/postcss.config.js
@@ -1,3 +1,3 @@
module.exports = {
plugins: ['mock-plugin']
}
plugins: ["mock-plugin"],
};
17 changes: 11 additions & 6 deletions fixture-postcss-plugin.js
@@ -1,7 +1,12 @@
const postcss = require('postcss')
const postcss = require("postcss");

module.exports = postcss.plugin('postcss-fixture', () => (root) => {
console.warn('warn')
console.error('error')
return root
})
module.exports = (options = {}) => ({
postcssPlugin: "postcss-csso",
Once(root, { result, postcss }) {
console.warn("warn");
console.error("error");
return root;
},
});

module.exports.postcss = true;
45 changes: 27 additions & 18 deletions index.js
@@ -1,30 +1,39 @@
const { spawnSync } = require('child_process')
const path = require('path')
const { spawnSync } = require("child_process");
const path = require("path");

module.exports = (css, settings) => {
const cssWithPlaceholders = css
.replace(/%%styled-jsx-placeholder-(\d+)%%/g, (_, id) =>
`/*%%styled-jsx-placeholder-${id}%%*/`
)
const cssWithPlaceholders = css.replace(
/%%styled-jsx-placeholder-(\d+)%%/g,
(_, id) => `/*%%styled-jsx-placeholder-${id}%%*/`
);

const result = spawnSync('node', [path.resolve(__dirname, 'processor.js')], {
const result = spawnSync("node", [path.resolve(__dirname, "processor.js")], {
input: JSON.stringify({
css: cssWithPlaceholders,
settings
settings,
}),
encoding: 'utf8'
})
encoding: "utf8",
});

if (result.status !== 0) {
if (result.stderr.includes('Invalid PostCSS Plugin')) {
console.error('Next.js 9 default postcss support uses a non standard postcss config schema https://err.sh/next.js/postcss-shape, you must use the interoperable object-based format instead https://nextjs.org/docs/advanced-features/customizing-postcss-config')
if (result.stderr.includes("Invalid PostCSS Plugin")) {
let isNext = false;
try {
require.resolve("next");
isNext = true;
} catch (err) {}
if (isNext) {
console.error(
"Next.js 9 default postcss support uses a non standard postcss config schema https://err.sh/next.js/postcss-shape, you must use the interoperable object-based format instead https://nextjs.org/docs/advanced-features/customizing-postcss-config"
);
}
}

throw new Error(`postcss failed with ${result.stderr}`)
throw new Error(`postcss failed with ${result.stderr}`);
}

return result.stdout
.replace(/\/\*%%styled-jsx-placeholder-(\d+)%%\*\//g, (_, id) =>
`%%styled-jsx-placeholder-${id}%%`
)
}
return result.stdout.replace(
/\/\*%%styled-jsx-placeholder-(\d+)%%\*\//g,
(_, id) => `%%styled-jsx-placeholder-${id}%%`
);
};
21 changes: 12 additions & 9 deletions package.json
@@ -1,10 +1,10 @@
{
"name": "styled-jsx-plugin-postcss",
"version": "3.0.2",
"version": "4.0.0",
"description": "Plugin to add PostCSS support to styled-jsx",
"main": "index.js",
"scripts": {
"test": "mocha test.js"
"test": "mocha --timeout 10000 test.js"
},
"repository": {
"type": "git",
Expand All @@ -22,14 +22,17 @@
},
"homepage": "https://github.com/giuseppeg/styled-jsx-plugin-postcss#readme",
"dependencies": {
"postcss": "^7.0.2",
"postcss-load-plugins": "^2.3.0"
"postcss-load-config": "^2.1.2"
},
"devDependencies": {
"mocha": "^5.2.0",
"postcss-easy-import": "^3.0.0",
"postcss-nested": "^4.1.0",
"postcss-preset-env": "^6.0.10",
"postcss-spiffing": "^0.1.0"
"mocha": "^8.2.0",
"postcss": "^8.1.2",
"postcss-calc": "^7.0.5",
"postcss-import": "^13.0.0",
"postcss-nested": "^5.0.1",
"postcss-preset-env": "^6.0.10"
},
"peerDependencies": {
"postcss": "^7.0.2 || ^8.1.0"
}
}
20 changes: 10 additions & 10 deletions postcss.config.js
@@ -1,18 +1,18 @@
const path = require('path')
const path = require("path");

module.exports = {
plugins: {
'postcss-easy-import': {},
'postcss-preset-env': {
browsers: ['last 2 versions', 'ie >= 10'],
"postcss-import": {},
"postcss-preset-env": {
browsers: ["last 2 versions", "ie >= 10"],
features: {
'nesting-rules': true,
'color-mod-function': {
unresolved: 'warn',
"nesting-rules": true,
"color-mod-function": {
unresolved: "warn",
},
},
},
'postcss-spiffing': {},
[path.resolve(__dirname, './fixture-postcss-plugin.js')]: {}
"postcss-calc": {},
[path.resolve(__dirname, "./fixture-postcss-plugin.js")]: {},
},
}
};
55 changes: 28 additions & 27 deletions processor.js
@@ -1,46 +1,47 @@
const postcss = require('postcss')
const loader = require('postcss-load-plugins')
const postcss = require("postcss");
const loader = require("postcss-load-config");

let plugins
let _processor
let plugins;
let _processor;

function processor(src, options) {
options = options || {}
let loaderPromise
options = options || {};
let loaderPromise;
if (!plugins) {
loaderPromise = loader(options.env || process.env, options.path, { argv: false })
.then(pluginsInfo => {
plugins = pluginsInfo.plugins || []
})
loaderPromise = loader(options.env || process.env, options.path, {
argv: false,
}).then((pluginsInfo) => {
plugins = pluginsInfo.plugins || [];
});
} else {
loaderPromise = Promise.resolve()
loaderPromise = Promise.resolve();
}

return loaderPromise
.then(() => {
if (!_processor) {
_processor = postcss(plugins)
_processor = postcss(plugins);
}
return _processor.process(src, { from: false })
return _processor.process(src, { from: false });
})
.then(result => result.css)
.then((result) => result.css);
}

let input = ''
process.stdin.on('data', data => {
input += data.toString()
})
let input = "";
process.stdin.on("data", (data) => {
input += data.toString();
});

process.stdin.on('end', () => {
const inputData = JSON.parse(input)
process.stdin.on("end", () => {
const inputData = JSON.parse(input);
processor(inputData.css, inputData.settings)
.then(result => {
process.stdout.write(result)
.then((result) => {
process.stdout.write(result);
})
.catch(err => {
.catch((err) => {
// NOTE: we console.erorr(err) and then process.exit(1) instead of throwing the error
// to avoid the UnhandledPromiseRejectionWarning message.
console.error(err)
process.exit(1)
})
})
console.error(err);
process.exit(1);
});
});

0 comments on commit 66d07da

Please sign in to comment.