├── .github
└── workflows
│ ├── compressed-size.yml
│ └── test.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── package.json
├── packages
├── babel-plugin-htm
│ ├── README.md
│ ├── index.mjs
│ └── package.json
└── babel-plugin-transform-jsx-to-htm
│ ├── README.md
│ ├── index.mjs
│ └── package.json
├── src
├── build.mjs
├── cjs.mjs
├── constants-mini.mjs
├── constants.mjs
├── index.d.ts
├── index.mjs
└── integrations
│ ├── preact
│ ├── index.d.ts
│ ├── index.mjs
│ ├── package.json
│ └── standalone.mjs
│ └── react
│ ├── index.d.ts
│ ├── index.mjs
│ └── package.json
└── test
├── __d8.mjs
├── __perftest.mjs
├── babel-transform-jsx.test.mjs
├── babel.test.mjs
├── fixtures
└── esm
│ ├── index.js
│ └── package.json
├── index.test.mjs
├── perf.test.mjs
├── preact.test.mjs
└── statics-caching.test.mjs
/.github/workflows/compressed-size.yml:
--------------------------------------------------------------------------------
1 | name: Compressed Size
2 |
3 | on: [pull_request]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 |
9 | steps:
10 | - uses: actions/checkout@v2
11 | - uses: preactjs/compressed-size-action@v2
12 | with:
13 | pattern: "./{dist,mini,react,preact}/{index.js,index.mjs,htm.js,htm.mjs,standalone.js,standalone.mjs}"
14 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Unit Tests
2 |
3 | on: [pull_request, push]
4 |
5 | jobs:
6 | build:
7 | runs-on: ubuntu-latest
8 | strategy:
9 | matrix:
10 | # Change the condition for ESM Dist Test below when changing this.
11 | node-version: [12.x, 14.x]
12 | steps:
13 | - name: Checkout
14 | uses: actions/checkout@v2
15 | - name: Use Node.js ${{ matrix.node-version }}
16 | uses: actions/setup-node@v1
17 | with:
18 | node-version: ${{ matrix.node-version }}
19 | - name: Install
20 | run: npm install
21 | - name: Build and Test
22 | run: npm test
23 | - if: matrix.node-version == '14.x'
24 | name: ESM Dist Test
25 | run: npm run test:dist
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | package-lock.json
3 | /preact
4 | /react
5 | dist
6 | mini
7 | yarn.lock
8 | htm.tgz
9 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at jason@developit.ca. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We'd love to accept your patches and contributions to this project. There are
4 | just a few small guidelines you need to follow.
5 |
6 | ## Contributor License Agreement
7 |
8 | Contributions to this project must be accompanied by a Contributor License
9 | Agreement. You (or your employer) retain the copyright to your contribution,
10 | this simply gives us permission to use and redistribute your contributions as
11 | part of the project. Head over to to see
12 | your current agreements on file or to sign a new one.
13 |
14 | You generally only need to submit a CLA once, so if you've already submitted one
15 | (even if it was for a different project), you probably don't need to do it
16 | again.
17 |
18 | ## Code reviews
19 |
20 | All submissions, including submissions by project members, require review. We
21 | use GitHub pull requests for this purpose. Consult
22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23 | information on using pull requests.
24 |
25 | ## Community Guidelines
26 |
27 | This project follows [Google's Open Source Community
28 | Guidelines](https://opensource.google.com/conduct/).
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2018 Google Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | HTM (Hyperscript Tagged Markup)
4 |
5 |
6 |
7 |
8 |
9 |
10 | `htm` is **JSX-like syntax in plain JavaScript** - no transpiler necessary.
11 |
12 | Develop with React/Preact directly in the browser, then compile `htm` away for production.
13 |
14 | It uses standard JavaScript [Tagged Templates] and works in [all modern browsers].
15 |
16 | ## `htm` by the numbers:
17 |
18 | 🐣 **< 600 bytes** when used directly in the browser
19 |
20 | ⚛️ **< 500 bytes** when used with Preact _(thanks gzip 🌈)_
21 |
22 | 🥚 **< 450 byte** `htm/mini` version
23 |
24 | 🏅 **0 bytes** if compiled using [babel-plugin-htm]
25 |
26 |
27 | ## Syntax: like JSX but also lit
28 |
29 | The syntax you write when using HTM is as close as possible to JSX:
30 |
31 | - Spread props: `
` instead of `
`
32 | - Self-closing tags: ``
33 | - Components: `<${Foo}>` instead of `` _(where `Foo` is a component reference)_
34 | - Boolean attributes: ``
35 |
36 |
37 | ## Improvements over JSX
38 |
39 | `htm` actually takes the JSX-style syntax a couple steps further!
40 |
41 | Here's some ergonomic features you get for free that aren't present in JSX:
42 |
43 | - **No transpiler necessary**
44 | - HTML's optional quotes: `
`
45 | - Component end-tags: `<${Footer}>footer content/>`
46 | - Syntax highlighting and language support via the [lit-html VSCode extension] and [vim-jsx-pretty plugin].
47 | - Multiple root element (fragments): ``
48 | - Support for HTML-style comments: ``
49 |
50 | ## Installation
51 |
52 | `htm` is published to npm, and accessible via the unpkg.com CDN:
53 |
54 | **via npm:**
55 |
56 | ```js
57 | npm i htm
58 | ```
59 |
60 | **hotlinking from unpkg:** _(no build tool needed!)_
61 |
62 | ```js
63 | import htm from 'https://unpkg.com/htm?module'
64 | const html = htm.bind(React.createElement);
65 | ```
66 |
67 | ```js
68 | // just want htm + preact in a single file? there's a highly-optimized version of that:
69 | import { html, render } from 'https://unpkg.com/htm/preact/standalone.module.js'
70 | ```
71 |
72 | ## Usage
73 |
74 | If you're using Preact or React, we've included off-the-shelf bindings to make your life easier.
75 | They also have the added benefit of sharing a template cache across all modules.
76 |
77 | ```js
78 | import { render } from 'preact';
79 | import { html } from 'htm/preact';
80 | render(html`Hello!`, document.body);
81 | ```
82 |
83 | Similarly, for React:
84 |
85 | ```js
86 | import ReactDOM from 'react-dom';
87 | import { html } from 'htm/react';
88 | ReactDOM.render(html`Hello!`, document.body);
89 | ```
90 |
91 | ### Advanced Usage
92 |
93 | Since `htm` is a generic library, we need to tell it what to "compile" our templates to.
94 | You can bind `htm` to any function of the form `h(type, props, ...children)` _([hyperscript])_.
95 | This function can return anything - `htm` never looks at the return value.
96 |
97 | Here's an example `h()` function that returns tree nodes:
98 |
99 | ```js
100 | function h(type, props, ...children) {
101 | return { type, props, children };
102 | }
103 | ```
104 |
105 | To use our custom `h()` function, we need to create our own `html` tag function by binding `htm` to our `h()` function:
106 |
107 | ```js
108 | import htm from 'htm';
109 |
110 | const html = htm.bind(h);
111 | ```
112 |
113 | Now we have an `html()` template tag that can be used to produce objects in the format we created above.
114 |
115 | Here's the whole thing for clarity:
116 |
117 | ```js
118 | import htm from 'htm';
119 |
120 | function h(type, props, ...children) {
121 | return { type, props, children };
122 | }
123 |
124 | const html = htm.bind(h);
125 |
126 | console.log( html`
Hello world!
` );
127 | // {
128 | // type: 'h1',
129 | // props: { id: 'hello' },
130 | // children: ['Hello world!']
131 | // }
132 | ```
133 |
134 | If the template has multiple element at the root level
135 | the output is an array of `h` results:
136 |
137 | ```js
138 | console.log(html`
139 |
Hello
140 |
World!
141 | `);
142 | // [
143 | // {
144 | // type: 'h1',
145 | // props: { id: 'hello' },
146 | // children: ['Hello']
147 | // },
148 | // {
149 | // type: 'div',
150 | // props: { class: 'world' },
151 | // children: ['world!']
152 | // }
153 | // ]
154 | ```
155 |
156 | ### Caching
157 |
158 | The default build of `htm` caches template strings, which means that it can return the same Javascript object at multiple points in the tree. If you don't want this behaviour, you have three options:
159 |
160 | * Change your `h` function to copy nodes when needed.
161 | * Add the code `this[0] = 3;` at the beginning of your `h` function, which disables caching of created elements.
162 | * Use `htm/mini`, which disables caching by default.
163 |
164 | ## Example
165 |
166 | Curious to see what it all looks like? Here's a working app!
167 |
168 | It's a single HTML file, and there's no build or tooling. You can edit it with nano.
169 |
170 | ```html
171 |
172 |
173 | htm Demo
174 |
204 |
205 | ```
206 |
207 | [⚡️ **See live version** ▶](https://htm-demo-preact.glitch.me/)
208 |
209 | [⚡️ **Try this on CodeSandbox** ▶](https://codesandbox.io/s/x7pmq32j6q)
210 |
211 | How nifty is that?
212 |
213 | Notice there's only one import - here we're using the prebuilt Preact integration since it's easier to import and a bit smaller.
214 |
215 | The same example works fine without the prebuilt version, just using two imports:
216 |
217 | ```js
218 | import { h, Component, render } from 'preact';
219 | import htm from 'htm';
220 |
221 | const html = htm.bind(h);
222 |
223 | render(html`<${App} page="All" />`, document.body);
224 | ```
225 |
226 | ## Other Uses
227 |
228 | Since `htm` is designed to meet the same need as JSX, you can use it anywhere you'd use JSX.
229 |
230 | **Generate HTML using [vhtml]:**
231 |
232 | ```js
233 | import htm from 'htm';
234 | import vhtml from 'vhtml';
235 |
236 | const html = htm.bind(vhtml);
237 |
238 | console.log( html`
Hello world!
` );
239 | // '
Hello world!
'
240 | ```
241 |
242 | **Webpack configuration via [jsxobj]:** ([details here](https://webpack.js.org/configuration/configuration-languages/#babel-and-jsx)) _(never do this)_
243 |
244 | ```js
245 | import htm from 'htm';
246 | import jsxobj from 'jsxobj';
247 |
248 | const html = htm.bind(jsxobj);
249 |
250 | console.log(html`
251 |
252 |
253 |
254 | `);
255 | // {
256 | // watch: true,
257 | // mode: 'production',
258 | // entry: {
259 | // path: 'src/index.js'
260 | // }
261 | // }
262 | ```
263 |
264 | ## Demos & Examples
265 |
266 | - [Canadian Holidays](https://github.com/pcraig3/hols): A full app using HTM and Server-Side Rendering
267 | - [HTM SSR Example](https://github.com/timarney/htm-ssr-demo): Shows how to do SSR with HTM
268 | - [HTM + Preact SSR Demo](https://gist.github.com/developit/699c8d8f180a1e4eed58167f9c6711be)
269 | - [HTM + vhtml SSR Demo](https://gist.github.com/developit/ff925c3995b4a129b6b977bf7cd12ebd)
270 |
271 | ## Project Status
272 |
273 | The original goal for `htm` was to create a wrapper around Preact that felt natural for use untranspiled in the browser. I wanted to use Virtual DOM, but I wanted to eschew build tooling and use ES Modules directly.
274 |
275 | This meant giving up JSX, and the closest alternative was [Tagged Templates]. So, I wrote this library to patch up the differences between the two as much as possible. The technique turns out to be framework-agnostic, so it should work great with any library or renderer that works with JSX.
276 |
277 | `htm` is stable, fast, well-tested and ready for production use.
278 |
279 | [Tagged Templates]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates
280 | [lit-html]: https://github.com/Polymer/lit-html
281 | [babel-plugin-htm]: https://github.com/developit/htm/tree/master/packages/babel-plugin-htm
282 | [lit-html VSCode extension]: https://marketplace.visualstudio.com/items?itemName=bierner.lit-html
283 | [vim-jsx-pretty plugin]: https://github.com/MaxMEllon/vim-jsx-pretty
284 | [vhtml]: https://github.com/developit/vhtml
285 | [jsxobj]: https://github.com/developit/jsxobj
286 | [hyperscript]: https://github.com/hyperhype/hyperscript
287 | [all modern browsers]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Browser_compatibility
288 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: [
3 | [
4 | '@babel/preset-env',
5 | {
6 | targets: {
7 | node: 'current'
8 | }
9 | }
10 | ]
11 | ]
12 | };
13 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "htm",
3 | "version": "3.1.1",
4 | "description": "The Tagged Template syntax for Virtual DOM. Only browser-compatible syntax.",
5 | "main": "dist/htm.js",
6 | "umd:main": "dist/htm.umd.js",
7 | "module": "dist/htm.module.js",
8 | "types": "dist/htm.d.ts",
9 | "exports": {
10 | ".": {
11 | "types": "./dist/htm.d.ts",
12 | "browser": "./dist/htm.module.js",
13 | "umd": "./dist/htm.umd.js",
14 | "import": "./dist/htm.mjs",
15 | "require": "./dist/htm.js"
16 | },
17 | "./": "./",
18 | "./preact": {
19 | "types": "./preact/index.d.ts",
20 | "browser": "./preact/index.module.js",
21 | "umd": "./preact/index.umd.js",
22 | "import": "./preact/index.mjs",
23 | "require": "./preact/index.js"
24 | },
25 | "./preact/standalone": {
26 | "types": "./preact/index.d.ts",
27 | "browser": "./preact/standalone.module.js",
28 | "umd": "./preact/standalone.umd.js",
29 | "import": "./preact/standalone.mjs",
30 | "require": "./preact/standalone.js"
31 | },
32 | "./react": {
33 | "types": "./react/index.d.ts",
34 | "browser": "./react/index.module.js",
35 | "umd": "./react/index.umd.js",
36 | "import": "./react/index.mjs",
37 | "require": "./react/index.js"
38 | },
39 | "./mini": {
40 | "types": "./mini/index.d.ts",
41 | "browser": "./mini/index.module.js",
42 | "umd": "./mini/index.umd.js",
43 | "import": "./mini/index.mjs",
44 | "require": "./mini/index.js"
45 | }
46 | },
47 | "scripts": {
48 | "build": "npm run -s build:main && npm run -s build:mini && npm run -s build:preact && npm run -s build:react && npm run -s build:babel && npm run -s build:babel-transform-jsx && npm run -s build:mjsalias",
49 | "build:main": "microbundle src/index.mjs -f es,umd --no-sourcemap --target web && microbundle src/cjs.mjs -f iife --no-sourcemap --target web && cp src/index.d.ts dist/htm.d.ts",
50 | "build:mini": "microbundle src/index.mjs -o ./mini/index.js -f es,umd --no-sourcemap --target web --alias ./constants.mjs=./constants-mini.mjs && microbundle src/cjs.mjs -o ./mini/index.js -f iife --no-sourcemap --target web --alias ./constants.mjs=./constants-mini.mjs && cp src/index.d.ts mini",
51 | "build:preact": "cd src/integrations/preact && npm run build",
52 | "build:react": "cd src/integrations/react && npm run build",
53 | "build:babel": "cd packages/babel-plugin-htm && npm run build",
54 | "build:babel-transform-jsx": "cd packages/babel-plugin-transform-jsx-to-htm && npm run build",
55 | "build:mjsalias": "cp dist/htm.module.js dist/htm.mjs && cp mini/index.module.js mini/index.mjs && cp preact/index.module.js preact/index.mjs && cp preact/standalone.module.js preact/standalone.mjs && cp react/index.module.js react/index.mjs",
56 | "test": "eslint src/**/*.mjs test/**/*.mjs --ignore-path .gitignore && npm run build && jest test",
57 | "test:perf": "v8 test/__perftest.mjs",
58 | "test:dist": "npm pack && mv htm*.tgz test/fixtures/esm/htm.tgz && cd test/fixtures/esm && npm install && node index.js",
59 | "release": "npm t && git commit -am \"$npm_package_version\" && git tag $npm_package_version && git push && git push --tags && npm publish"
60 | },
61 | "files": [
62 | "dist",
63 | "mini",
64 | "preact",
65 | "react",
66 | "src"
67 | ],
68 | "eslintConfig": {
69 | "extends": "developit",
70 | "rules": {
71 | "prefer-const": 0,
72 | "prefer-spread": 0,
73 | "prefer-rest-params": 0,
74 | "func-style": 0
75 | }
76 | },
77 | "jest": {
78 | "testURL": "http://localhost",
79 | "testMatch": [
80 | "**/__tests__/**/*.?(m)js?(x)",
81 | "**/?(*.)(spec|test).?(m)js?(x)"
82 | ],
83 | "transform": {
84 | "\\.m?js$": "babel-jest"
85 | },
86 | "moduleFileExtensions": [
87 | "mjs",
88 | "js"
89 | ],
90 | "moduleNameMapper": {
91 | "^babel-plugin-transform-jsx-to-htm$": "/packages/babel-plugin-transform-jsx-to-htm/index.mjs",
92 | "^babel-plugin-htm$": "/packages/babel-plugin-htm/index.mjs",
93 | "^htm$": "/src/index.mjs",
94 | "^htm/preact$": "/src/integrations/preact/index.mjs"
95 | }
96 | },
97 | "repository": "developit/htm",
98 | "keywords": [
99 | "Hyperscript Tagged Markup",
100 | "tagged template",
101 | "template literals",
102 | "html",
103 | "htm",
104 | "jsx",
105 | "virtual dom",
106 | "hyperscript"
107 | ],
108 | "author": "Jason Miller ",
109 | "license": "Apache-2.0",
110 | "homepage": "https://github.com/developit/htm",
111 | "devDependencies": {
112 | "@babel/core": "^7.2.2",
113 | "@babel/preset-env": "^7.1.6",
114 | "@types/jest": "^26.0.24",
115 | "babel-jest": "^24.1.0",
116 | "babel-preset-env": "^1.7.0",
117 | "eslint": "^5.2.0",
118 | "eslint-config-developit": "^1.1.1",
119 | "jest": "^24.1.0",
120 | "microbundle": "^0.10.1",
121 | "preact": "^10.2.0",
122 | "react": "^16.8.3"
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/packages/babel-plugin-htm/README.md:
--------------------------------------------------------------------------------
1 | # `babel-plugin-htm`
2 |
3 | A Babel plugin that compiles [htm] syntax to hyperscript, React.createElement, or just plain objects.
4 |
5 | ## Usage
6 |
7 | In your Babel configuration (`.babelrc`, `babel.config.js`, `"babel"` field in package.json, etc), add the plugin:
8 |
9 | ```js
10 | {
11 | "plugins": [
12 | ["htm", {
13 | "pragma": "React.createElement"
14 | }]
15 | ]
16 | }
17 | ```
18 |
19 | ```js
20 | // input:
21 | html`
hello ${you}
`
22 |
23 | // output:
24 | React.createElement("div", { id: "foo" }, "hello ", you)
25 | ```
26 |
27 | ## options
28 |
29 | ### `pragma`
30 |
31 | The target "hyperscript" function to compile elements to (see [Babel docs]).
32 | Defaults to: `"h"`.
33 |
34 | ### `tag=html`
35 |
36 | By default, `babel-plugin-htm` will process all Tagged Templates with a tag function named `html`. To use a different name, use the `tag` option in your Babel configuration:
37 |
38 | ```js
39 | {"plugins":[
40 | ["babel-plugin-htm", {
41 | "tag": "myCustomHtmlFunction"
42 | }]
43 | ]}
44 | ```
45 |
46 | ### `import=false` _(experimental)_
47 |
48 | Auto-import the pragma function, off by default.
49 |
50 | #### `false` (default)
51 |
52 | Don't auto-import anything.
53 |
54 | #### `String`
55 |
56 | Import the `pragma` like `import {} from ''`.
57 |
58 | With Babel config:
59 | ```js
60 | "plugins": [
61 | ["babel-plugin-htm", {
62 | "tag": "$$html",
63 | "import": "htm/preact"
64 | }]
65 | ]
66 | ```
67 |
68 | ```js
69 | import { html as $$html } from 'htm/preact';
70 |
71 | export default $$html`
hello ${you}
`
72 | ```
73 |
74 | The above will produce files that look like:
75 |
76 | ```js
77 | import { h } from 'preact';
78 | import { html as $$html } from 'htm/preact';
79 |
80 | export default h("div", { id: "foo" }, "hello ", you)
81 | ```
82 |
83 | #### `{module: String, export: String}`
84 |
85 | Import the `pragma` like `import { as } from ''`.
86 |
87 | With Babel config:
88 | ```js
89 | "plugins": [
90 | ["babel-plugin-htm", {
91 | "pragma": "React.createElement",
92 | "tag": "$$html",
93 | "import": {
94 | // the module to import:
95 | "module": "react",
96 | // a named export to use from that module:
97 | "export": "default"
98 | }
99 | }]
100 | ]
101 | ```
102 |
103 | ```js
104 | import { html as $$html } from 'htm/react';
105 |
106 | export default $$html`
64 | `;
65 | }
66 | let now = performance.now();
67 | const start = now;
68 | while ((now = performance.now()) < start+1000) {
69 | count++;
70 | if (results.push(String(go(count)))===10) results.length = 0;
71 | }
72 | const elapsed = now - start;
73 | const hz = count / elapsed * 1000;
74 | // eslint-disable-next-line no-console
75 | console.log(`Usage: ${(hz|0).toLocaleString()}/s, average: ${elapsed/count*1000|0}µs`);
76 | expect(elapsed).toBeGreaterThan(999);
77 | expect(hz).toBeGreaterThan(100000);
78 | });
79 | });
80 |
--------------------------------------------------------------------------------
/test/preact.test.mjs:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2018 Google Inc. All Rights Reserved.
3 | * Licensed under the Apache License, Version 2.0 (the "License");
4 | * you may not use this file except in compliance with the License.
5 | * You may obtain a copy of the License at
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | * Unless required by applicable law or agreed to in writing, software
8 | * distributed under the License is distributed on an "AS IS" BASIS,
9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 | * See the License for the specific language governing permissions and
11 | * limitations under the License.
12 | */
13 |
14 | import { html, Component, render } from 'htm/preact';
15 |
16 | const sleep = ms => new Promise(r => setTimeout(r, ms));
17 |
18 | describe('htm/preact', () => {
19 | const scratch = document.createElement('div');
20 | document.body.appendChild(scratch);
21 |
22 | class Foo extends Component {
23 | render({ name }, { count = 0 }) {
24 | return html`
25 |
26 |
Name: ${name}
27 |
Hello world!
28 |
29 |
Count: ${count}
30 | xml-style end tags:
31 | <${Bar} hello />
32 | explicit end tags:
33 | <${Bar} hello>some children (count=${count})${Bar}>
34 | implicit end tags: (${'/>'})
35 | <${Bar} hello>some children (count=${count})/>
36 | some text at the end
37 |