Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/babel-plugin-htm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,17 @@ html`<div id="foo">hello ${you}</div>`
] }
```

### `noNullProps` _(experimental)_

Setting `noNullProps` to `true` passes empty object literals rather than `null` literals when a tag has no props:

```js
// input:
html`<div />`
// output:
h('div', {})
```


[htm]: https://github.com/developit/htm
[Babel docs]: https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#pragma
4 changes: 3 additions & 1 deletion packages/babel-plugin-htm/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ import { build, treeify } from '../../src/build.mjs';
* @param {boolean} [options.useBuiltIns=false] Use the native Object.assign instead of trying to polyfill it.
* @param {boolean} [options.useNativeSpread=false] Use the native { ...a, ...b } syntax for prop spreads.
* @param {boolean} [options.variableArity=true] If `false`, always passes exactly 3 arguments to the pragma function.
* @param {boolean} [options.noNullProps=false] If `true`, passes an empty object instead of null when there are no props.
*/
export default function htmBabelPlugin({ types: t }, options = {}) {
const pragmaString = options.pragma===false ? false : options.pragma || 'h';
const pragma = pragmaString===false ? false : dottedIdentifier(pragmaString);
const useBuiltIns = options.useBuiltIns;
const useNativeSpread = options.useNativeSpread;
const noNullProps = options.noNullProps;
const inlineVNodes = options.monomorphic || pragma===false;
const importDeclaration = pragmaImport(options.import || false);

Expand Down Expand Up @@ -123,7 +125,7 @@ export default function htmBabelPlugin({ types: t }, options = {}) {

function spreadNode(args, state) {
if (args.length === 0) {
return t.nullLiteral();
return noNullProps ? t.objectExpression([]) : t.nullLiteral();
}
if (args.length > 0 && t.isNode(args[0])) {
args.unshift({});
Expand Down
15 changes: 15 additions & 0 deletions test/babel.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,21 @@ describe('htm/babel', () => {
});
});

describe('{noNullProps:true}', () => {
test('should use empty objects instead of null props', () => {
expect(
transform('html`<div />`;', {
...options,
plugins: [
[htmBabelPlugin, {
noNullProps: true
}]
]
}).code
).toBe(`h("div",{});`);
});
});

describe('{import:Object}', () => {
test('should add import', () => {
expect(
Expand Down