Skip to content

Commit

Permalink
reintroduce namedExports
Browse files Browse the repository at this point in the history
  • Loading branch information
egoist committed Jan 10, 2018
1 parent f4e67b8 commit 3381db8
Show file tree
Hide file tree
Showing 9 changed files with 142 additions and 4 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,40 @@ Default: `false`

Extract CSS into its own file.

### modules

Type: `boolean` `object`<br>
Default: `false`

Enable CSS modules or set options for `postcss-modules`.

### namedExports

Type: `boolean`<br>
Default: `false`

Use named exports alongside default export.

When importing specific classNames, the following will happen:

- dashed class names will be transformed by replacing all the dashes to `$` sign wrapped underlines, eg. `--` => `$__$`
- js protected names used as your style class names, will be transformed by wrapping the names between `$` signs, eg. `switch` => `$switch$`

All transformed names will be logged in your terminal like:

```bash
Exported "new" as "$new$" in test/fixtures/named-exports/style.css
```

The original will not be removed, it's still available on `default` export:

```js
import style, { class$_$name, class$__$name, $switch$ } from './style.css';
console.log(style['class-name'] === class$_$name) // true
console.log(style['class--name'] === class$__$name) // true
console.log(style['switch'] === $switch$) // true
```

### minimize

Type: `boolean` `object`<br>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"postcss-load-config": "^1.2.0",
"postcss-modules": "^1.1.0",
"promise.series": "^0.2.0",
"reserved-words": "^0.1.2",
"rollup-pluginutils": "^2.0.1",
"style-inject": "^0.2.0"
},
Expand Down
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export default (options = {}) => {
extract: typeof options.extract === 'undefined' ? false : options.extract,
/** CSS modules */
modules: inferOption(options.modules, false),
namedExports: options.namedExports,
/** Options for cssnano */
minimize: inferOption(options.minimize, false),
/** Postcss config file */
Expand Down
41 changes: 37 additions & 4 deletions src/postcss-loader.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'path'
import postcss from 'postcss'
import findPostcssConfig from 'postcss-load-config'
import reserved from 'reserved-words'
import { localRequire } from './utils'

function loadConfig(id, { ctx: configOptions, path: configPath }) {
Expand All @@ -22,8 +23,21 @@ function loadConfig(id, { ctx: configOptions, path: configPath }) {
options: configOptions || {}
}

return findPostcssConfig(ctx, configPath, { argv: false })
.catch(handleError)
return findPostcssConfig(ctx, configPath, { argv: false }).catch(handleError)
}

function escapeClassNameDashes(str) {
return str.replace(/-+/g, match => {
return `$${match.replace(/-/g, '_')}$`
})
}

function ensureClassName(name) {
name = escapeClassNameDashes(name)
if (reserved.check(name)) {
name = `$${name}$`
}
return name
}

export default {
Expand All @@ -36,7 +50,9 @@ export default {
)
}

const config = this.options.config ? await loadConfig(this.id, this.options.config) : {}
const config = this.options.config ?
await loadConfig(this.id, this.options.config) :
{}

const options = this.options
const plugins = [...(options.plugins || []), ...(config.plugins || [])]
Expand Down Expand Up @@ -84,6 +100,21 @@ export default {

let output = ''
let extracted

if (options.namedExports) {
const json = modulesExported[this.id]
// eslint-disable-next-line guard-for-in
for (const name in json) {
const newName = ensureClassName(name)
if (name !== newName) {
console.warn(`Exported "${name}" as "${newName}" in ${path.relative(process.cwd(), this.id)}`)
}
output += `export var ${newName} = ${JSON.stringify(
json[name]
)};\n`
}
}

if (shouldExtract) {
output += `export default ${JSON.stringify(modulesExported[this.id])};`
extracted = {
Expand All @@ -98,7 +129,9 @@ export default {
}
if (!shouldExtract && shouldInject) {
output += `\n__$$styleInject(css${
Object.keys(options.inject).length > 0 ? `,${JSON.stringify(options.inject)}` : ''
Object.keys(options.inject).length > 0 ?
`,${JSON.stringify(options.inject)}` :
''
});`
}

Expand Down
46 changes: 46 additions & 0 deletions test/__snapshots__/index.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,52 @@ console.log(style.foo);
"
`;

exports[`modules:named-exports: js code 1`] = `
"'use strict';
function __$styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css) { return }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var foo = \\"style_foo__23nAE\\";
var $new$ = \\"style_new__155Jg\\";
var css = \\".style_foo__23nAE {\\\\n color: red;\\\\n}\\\\n\\\\n.style_new__155Jg {\\\\n color: blue;\\\\n}\\\\n\\";
var style = {\\"foo\\":\\"style_foo__23nAE\\",\\"new\\":\\"style_new__155Jg\\"};
__$$styleInject(css);
var style$1 = Object.freeze({
foo: foo,
$new$: $new$,
default: style
});
console.log(style$1);
"
`;

exports[`postcss-config: js code 1`] = `
"'use strict';
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/named-exports/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as style from './style.css'

console.log(style)
7 changes: 7 additions & 0 deletions test/fixtures/named-exports/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.foo {
color: red;
}

.new {
color: blue;
}
9 changes: 9 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,15 @@ snapshot({
}
})

snapshot({
title: 'modules:named-exports',
input: 'named-exports/index.js',
options: {
modules: true,
namedExports: true
}
})

snapshot({
title: 'modules:extract',
input: 'css-modules/index.js',
Expand Down
4 changes: 4 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4775,6 +4775,10 @@ require-uncached@^1.0.2:
caller-path "^0.1.0"
resolve-from "^1.0.0"

reserved-words@^0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/reserved-words/-/reserved-words-0.1.2.tgz#00a0940f98cd501aeaaac316411d9adc52b31ab1"

resolve-cwd@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-1.0.0.tgz#4eaeea41ed040d1702457df64a42b2b07d246f9f"
Expand Down

0 comments on commit 3381db8

Please sign in to comment.