UNPKG

37.1 kBMarkdownView Raw
1# claycli
2A CLI For Clay!
3
4[![CircleCI](https://circleci.com/gh/clay/claycli.svg?style=svg)](https://circleci.com/gh/clay/claycli) [![Coverage Status](https://coveralls.io/repos/github/clay/claycli/badge.svg?branch=master)](https://coveralls.io/github/clay/claycli?branch=master)
5
6# Installation
7
8```
9npm install -g claycli
10```
11
12# Usage
13
14```
15clay <command> [options]
16```
17
18If installed globally, call `clay` from the command line. Much like `git`, `claycli` is configured using a [dotfile](https://medium.com/@webprolific/getting-started-with-dotfiles-43c3602fd789) (`.clayconfig`) in your home folder. In it you may specify references to api keys and urls / site prefixes that you use frequently. For urls and site prefixes, it will assume `http://` and port `80` unless you specify otherwise.
19
20Note that a _site prefix_ is everything before the api route, e.g. `http://domain.com/site1` in `http://domain.com/site1/_components/article`.
21
22```
23[keys]
24 local = ha8yds9a8shdf98asdf
25 qa = 8quwqwer09ewr0w9uer
26 prod = bj34b6345k634jnk63n4
27[urls]
28 local-site1 = https://localhost.site1.com:3001
29 local-site2 = site2.com/site-2 # http and port 80
30```
31
32For smaller Clay installations (or, ironically, for very large teams where devs spend most of their time on individual sites), you may specify a default api key and url / site prefix by using the `CLAYCLI_DEFAULT_KEY` and `CLAYCLI_DEFAULT_URL` environment variables.
33
34# Commands
35
36* [`config`](https://github.com/clay/claycli#config)
37* [`lint`](https://github.com/clay/claycli#lint)
38* [`import`](https://github.com/clay/claycli#import)
39* [`export`](https://github.com/clay/claycli#export)
40* [`compile`](https://github.com/clay/claycli#compile)
41
42## Common Arguments
43
44`claycli` uses some common arguments across many commands.
45
46* `-v, --version` will print the `claycli` version and exit
47* `-h, --help` will print helpful info about `claycli` and exit
48* `-r, --reporter` allows specifying how results should be logged
49* `-c, --concurrency` allows setting the concurrency of api calls (defaults to 10)
50* `-k, --key` allows specifying an api key or alias
51
52### Logging
53
54When running `claycli` programmatically (i.e., `import { someMethod } from 'claycli'`), most commands will return a stream of objects with `{ type, message, details }`. The `type` may be `success` (signalling that an operation succeeded), `error`, `warning`, `info`, or `debug`. As you can see, most of those correspond directly to log levels.
55
56When running `claycli` from the command line, you may specify a `reporter` argument to output logs in different formats. The default is `dots`, which will print out green and red dots showing operation success / failure. There is also `pretty` (which prints more detailed messages on each line), `json` (which prints newline-separated json logs in a format that can be passed to ELK), and `nyan` (which is mostly just for fun).
57
58```bash
59clay lint --reporter pretty domain.com/_components/article
60```
61
62You may also specify which reporter to use by setting the `CLAYCLI_REPORTER` environment variable. If you add a `reporter` argument, it will be used instead of the env variable.
63
64```bash
65export CLAYCLI_REPORTER=json
66```
67
68`claycli` pipes to `stderr`. If you want to pipe the logs to a file, you may use `2>`.
69
70```bash
71`clay lint --reporter json domain.com/_components/article 2> article-log.json`
72```
73
74## Handling Files
75
76### Dispatch
77
78Many `claycli` commands allow you to pipe in the contents of files to `stdin` or pipe data out from `stdout`. The format that `claycli` uses to represent data (similar to a database dump) is called a _dispatch_, and it consists of newline-separated JSON without site prefixes.
79
80```
81{"/_components/article/instances/123":{"title":"My Article","content":[{"_ref":"/_components/paragraph/instances/234","text":"Four score and seven years ago..."}]}}
82{"/_components/meta-title/instances/345":{"title":"My Article","ogTitle":"My Longer Titled Article","twitterTitle":"Article"}}
83```
84
85Each line of a _dispatch_ contains [composed data for a component](https://github.com/clay/amphora/blob/master/lib/routes/readme.md#component-data) (or page, user, list, etc), including any data for its child components. This means that each line is able to be sent as a [cascading PUT](https://github.com/clay/amphora/pull/73) to the Clay server, which is a highly efficient way of importing large amounts of data. Note that a _dispatch_ is not meant to be human-readable, and manually editing it is a very easy way to introduce data errors.
86
87A _dispatch_ may be piped into or out of commands such as `clay import` and `clay export`. Because _dispatches_ are a special format (rather than regular JSON files), the convention is to use the `.clay` extension, but this isn't required.
88
89```bash
90clay export domain.com > article_dump.clay
91clay import domain.com < article_dump.clay
92clay export domain.com | clay import localhost
93```
94
95### Bootstrap
96
97For working with human-readable data, we use a format called a _bootstrap_. These are human-readable [yaml](http://docs.ansible.com/ansible/latest/YAMLSyntax.html) files that divide components (and pages, users, lists, etc) by type. [This is the same format that is used by the `bootstrap.yml` files in your Clay install](http://clay.github.io/amphora/docs/lifecycle/startup/bootstrap.html).
98
99```yaml
100_components:
101 article:
102 instances:
103 123:
104 title: My Article
105 content:
106 - _ref: /_components/paragraph/instances/234
107 paragraph:
108 instances:
109 234:
110 text: Four score and seven years ago...
111 meta-title:
112 instances:
113 345:
114 title: My Article
115 ogTitle: My Longer Titled Article
116 twitterTitle: Article
117```
118
119A _bootstrap_ may be piped into and out of any `claycli` commands that accept _dispatches_. To tell `claycli` that you're dealing with _bootstraps_, please use the `--yaml` argument.
120
121```bash
122clay export --yaml domain.com > article_dump.yml
123clay import --yaml domain.com < article_dump.yml
124```
125
126If you're a backend developer or database architect, it may be helpful to think of _dispatches_ and _bootstraps_ as [denormalized and normalized data](https://medium.com/@katedoesdev/normalized-vs-denormalized-databases-210e1d67927d). You'll notice that the two examples above contain the same data. The denormalized _dispatches_ allow a single API call per line and use less memory because they're streamable, while the normalized _bootstraps_ are better for hand-coding data because components are not duplicated if referenced multiple times. Generally speaking, use _dispatches_ for transporting and storing data and _bootstraps_ for hand-coding.
127
128## Config
129
130```bash
131clay config --key <alias> [value]
132clay config --url <alias> [value]
133```
134
135Show or set configuration options. These are saved to `~/.clayconfig`. As specified above, sites will assume `http` and port `80` if you do not write the protocol and port.
136
137### Arguments
138
139* `-k, --key` allows viewing or saving an api key
140* `-u, --url` allows viewing or saving a url / site prefix
141* `-r, --reporter` allows specifying how results should be logged (note: all reporters except `json` report `clay config` the same)
142
143### Examples
144
145```bash
146# view all configuration options
147clay config
148
149# view 'local' api key
150clay config --key local
151
152# set 'local' api key
153clay config --key local ab27s9d
154
155# view 'qa' site prefix
156clay config --url qa
157
158# set 'qa' site prefix
159clay config --url qa https://qa.domain.com:3001
160
161# set a specific url
162clay config --url my-cool-article domain.com/_components/article/instances/123
163```
164
165## Lint
166
167```bash
168clay lint [--concurrency <number>] [url]
169```
170
171Verify Clay data against standardized conventions and make sure all child components exist.
172
173Linting a page, component, or user url will verify that the data for that url exists, and (for pages and components) will (recursively) verify that all references to child components exist. The url must be a raw url, an alias specified via `clay config`, or omitted in favor of `CLAYCLI_DEFAULT_URL`. Linting a public url (or a page/component url that has a `.html` extension) will attempt to render that url with the extension and, if that fails, try to figure out which component isn't rendering correctly. You may lint other renderers by providing their extensions, e.g. `.amp` or `.rss`.
174
175Instead of linting a url, you may pipe in a component's `schema.yml` to lint. It will go through the schema and verify that it conforms to [Kiln's schema rules](https://claycms.gitbooks.io/kiln/editing-components.html).
176
177### Arguments
178
179* `-r, --reporter` allows specifying how results should be logged
180* `-c, --concurrency` allows setting the concurrency of api calls
181
182### Examples
183
184```bash
185# lint all components on a page
186clay lint domain.com/_pages/123
187
188# lint a page via public url
189clay lint domain.com/2018/02/some-slug.html
190
191# lint a component and its html
192clay lint domain.com/_components/article/instances/abc.html
193
194# lint a component specified via config alias
195clay lint my-cool-article
196
197# lint single schema
198clay lint < components/article/schema.yml
199```
200
201## Import
202
203```bash
204clay import [--key <api key>] [--concurrency <number>] [--publish] [--yaml] [site prefix]
205```
206
207Imports data into Clay from `stdin`. Data may be in _dispatch_ or _bootstrap_ format. Site prefix must be a raw url, an alias specified via `clay config`, or omitted in favor of `CLAYCLI_DEFAULT_URL`. Key must be an alias specified via `clay config`, or omitted in favor of `CLAYCLI_DEFAULT_KEY`.
208
209The `publish` argument will trigger a publish of the pages and / or components you're importing. Note that the generated url of an imported page might be different than its original url, depending on your Clay url generation / publishing logic.
210
211### Arguments
212
213* `-k, --key` allows specifying an api key or alias
214* `-r, --reporter` allows specifying how results should be logged
215* `-c, --concurrency` allows setting the concurrency of api calls
216* `-p, --publish` triggers publishing of imported pages
217* `-y, --yaml` specifies that input is _bootstrap_ format
218
219### Examples
220
221```bash
222# import a dispatch
223clay import --key local localhost:3001 < db_dump.clay
224
225# import and publish pages in a bootstrap
226clay import --key qa --publish --yaml < bootstrap.yml
227
228# pipe from 3rd party exporter
229wordpress-export domain.com/blog | clay import --key local localhost.domain.com
230
231# pipe from clay exporter
232clay export --key prod domain.com/_components/article/instances/123 | clay import --key local localhost.domain.com
233
234# import multiple dispatches
235cat *.clay | clay import --key local localhost:3001
236
237# import multiple bootstraps
238tail -n +1 *.yml | clay import --key local --yaml localhost:3001
239
240# recursively import multiple bootstraps
241find . -name '*.yml' -exec cat "{}" \; | clay import --key local --yaml localhost:3001
242
243# recursively import multiple bootstraps (bash v4+ & zsh)
244cat **/*.yml | clay import --key local --yaml localhost:3001
245```
246
247## Export
248
249```bash
250clay export [--key <api key>] [--concurrency <number>] [--size <number>] [--layout] [--yaml] [url]
251```
252
253Exports data from Clay to `stdout`. Data may be in _dispatch_ or _bootstrap_ format. The url must be a raw url, an alias specified via `clay config`, or omitted in favor of `CLAYCLI_DEFAULT_URL`.
254
255If the url points to a site prefix (i.e. it does not point to a specific type of data (a specific page, public url, component, user, list, etc)), `claycli` will query the built-in `pages` index to pull the latest 10 pages from the site. When querying the `pages` index, you must specify a `key` or have the `CLAYCLI_DEFAULT_KEY` set. The api key is only required when exporting multiple pages (by querying the `pages` index or by running custom queries, below).
256
257Instead of fetching the latest pages, you may pipe in a yaml-formatted [elasticsearch query](https://www.elastic.co/guide/en/elasticsearch/reference/current/_introducing_the_query_language.html). Use this to set custom offsets (for batching and chunking exports), export non-page content from other indices, or filter exported data via certain properties. Note that if you pipe in a query that includes `size`, it will take precedence over the CLI `size` argument.
258
259```yaml
260index: pages
261size: 100
262body:
263 sort:
264 updateTime:
265 order: desc # sort by latest updated
266 query:
267 bool:
268 must:
269 -
270 terms:
271 siteSlug:
272 - intelligencer # show only pages for a specific site
273 -
274 match:
275 published: true # show only published pages
276
277```
278
279You may also query other elastic indices, but please make sure that each document returned has a clay uri (e.g. `domain.com/_components/foo/instances/bar` or `domain.com/_pages/foo`) as its `_id`.
280
281```yaml
282index: published-products
283size: 5
284from: 10
285sort:
286 - price
287body:
288 query:
289 match_all: {}
290```
291
292By default, layouts are not exported when exporting pages. This allows you to easily copy individual pages between sites and environments. To trigger layout exporting, please use the `layout` argument.
293
294### Arguments
295
296* `-k, --key` allows specifying an api key or alias
297* `-r, --reporter` allows specifying how results should be logged
298* `-c, --concurrency` allows setting the concurrency of api calls
299* `-s, --size` specifies the number of pages to export (defaults to 10)
300* `-l, --layout` triggers exporting of layouts
301* `-y, --yaml` specifies that output is _bootstrap_ format
302
303### Examples
304
305```bash
306# export individual component
307clay export domain.com/_components/article/instances/123 > article_dump.clay
308
309# export individual page
310clay export --yaml domain.com/_pages/123 > page_bootstrap.yml
311
312# export page with layout
313clay export --layout --yaml domain.com/_pages/123 > page_bootstrap.yml
314
315# copy page to local environment
316clay export domain.com/_pages/123 | clay import --key local local.domain.com
317
318# export latest updated page
319clay export --key prod --size 1 domain.com > recent_page.clay
320
321# export custom query to dispatch
322cat query.yml | clay export --key prod domain.com > db_dump.clay
323
324# export custom query to bootstrap
325clay export --yaml --key prod domain.com/sub-site < query.yml > pages.yml
326
327# note that 'cat query.yml | clay export' and 'clay export < query.yml' are equivalent ways
328# to pipe from a file into claycli in most operating systems
329
330#
331# other things you may export
332#
333
334# export single user
335clay export domain.com/_users/abs8a7s8d --yaml > my_user.yml
336
337# export all users
338clay export domain.com/_users --yaml > users.yml
339
340# export single list
341clay export domain.com/_lists/tags > tags.clay
342
343# export all lists
344clay export domain.com/_lists > lists.clay
345
346# export published page via public url
347clay export domain.com/2017/02/some-slug.html
348
349# export built-in 'New Page Templates' list (page uris will be unprefixed)
350clay export domnain.com/_lists/new-pages
351```
352
353## Compile
354
355```bash
356clay compile [--watch] [--minify] [--inlined] [--linked] [--plugins <space-separated list of postcss plugins>] [--globs <space-separated glob strings>] [--reporter <reporter>]
357```
358
359Compile assets based on standardized Clay conventions. Assets are compiled to a `public` folder at the root of your Clay install (the directory where you run the `clay compile` command), with scripts (including templates), styles (including fonts), and media output to the `js`, `css`, and `media` folders. You may run `clay compile` to compile _all_ assets, or run any of its subcommands (`media`, `fonts`, `styles`, `templates`, `scripts`) to compile a specific type of asset.
360
361Specifying `--watch` on `claycli compile` or any of its subcommands will compile assets once, then watch source files (and their dependencies) for changes. Specifying `--minify` (or setting `CLAYCLI_COMPILE_MINIFIED`) will run assets through minification and bundling if applicable. The `CLAYCLI_COMPILE_ASSET_HOST` and `CLAYCLI_COMPILE_ASSET_PATH` variables are used by the `styles` and `fonts` subcommands to generate links to media and font files in the compiled CSS.
362
363A project specific clay config file is also supported, [read more here](https://github.com/clay/claycli#project-specific-config-file).
364
365#### Arguments
366
367* `-w, --watch` enables watching of source files after compilation
368* `-m, --minify` enables minification and bundling of source files
369* `-i, --inlined` enables the generation of base64 inlined font CSS
370* `-l, --linked` enables the generation of linked font CSS
371* `-p, --plugins` allows running additional postcss plugins when compiling styles
372* `-g, --globs` allows compiling additional JavaScript to `public/js/_global.js`
373* `-r, --reporter` allows specifying how results should be logged
374
375#### Examples
376
377```bash
378# compile all assets once
379clay compile
380
381# compile and watch all assets
382clay compile --watch
383
384# compile all assets once for production environments
385clay compile --minify
386
387# compile all assets, creating both inlined and linked font CSS
388clay compile --inlined --linked
389```
390
391### Media
392
393```bash
394clay compile media [--watch] [--reporter <reporter>]
395```
396
397Copy component, layout, styleguide, and site-specific media files from their source folders to the `public` directory. Media files are images (`jpg`, `jpeg`, `png`, `gif`), `svgs`, and favicons (`ico`).
398
399* `components/<name>/media/` are referenced by component templates and get copied to `public/media/components/<name>/`
400* `layouts/<name>/media/` are referenced by layout templates and get copied to `public/media/layouts/<name>/`
401* `styleguides/<name>/media/` are referenced by that styleguide's CSS and get copied to `public/media/stylesguides/<name>/`
402* `sites/<name>/media/` are favicons and other site-specific icons that are referenced by particular components in the `<head>` of pages. They get copied to `public/media/sites/<name>/`
403
404#### Arguments
405
406* `-w, --watch` enables watching of source files after compilation
407* `-r, --reporter` allows specifying how results should be logged
408
409#### Examples
410
411```bash
412# compile media files once
413clay compile media
414
415# compile and watch media files
416clay compile media --watch
417```
418
419### Fonts
420
421```bash
422clay compile fonts [--watch] [--minify] [--inlined] [--linked] [--reporter <reporter>]
423```
424
425Compile fonts from `styleguides/<name>/fonts/` to the `public` directory. By default (and if `--linked` is specified or `CLAYCLI_COMPILE_LINKED_FONTS` is set), this will generate a `public/css/_linked-fonts.<name>.css` file with `@font-face` declarations and copy the original font file to `public/fonts/`. Note that naming collisions are possible when using fonts of the same filename across different styleguides. If `--inlined` is specified (or `CLAYCLI_COMPILE_INLINED_FONTS` is set), this will generate a `public/css/_inlined-fonts.<name>.css` file with `@font-face` declarations that include a base64-encoded copy of the font.
426
427`@font-face` declarations are generated based on the filename of the original font file, with a simple convention to support various weights and styles.
428
429* `<name>.<ext>` font with normal weight and style
430* `<name>-<weight>.<ext>` or `<name>-<style>.<ext>` specify a font weight _or_ style
431* `<name>-<weight>-<style>.<ext>` specify a font weight _and_ style
432
433All named and numbered font weights are supported, as well as the `italic` and `oblique` font styles. When referencing fonts in your CSS, use the (case-insensitive) `<name>` for your `font-family` rule so the `font-weight` and `font-style` rules will work as expected. Supported font extensions are `woff`, `woff2`, `otf`, and `ttf`.
434
435Specifying `--minify` (or using `CLAYCLI_COMPILE_MINIFIED` or more specifically `CLAYCLI_COMPILE_MINIFIED_FONTS`) will run the generated font CSS through [`clean-css`](https://github.com/jakubpawlowicz/clean-css).
436
437#### Arguments
438
439* `-w, --watch` enables watching of source files after compilation
440* `-m, --minify` enables minification of font CSS
441* `-i, --inlined` enables the generation of base64 inlined font CSS
442* `-l, --linked` enables the generation of linked font CSS
443* `-r, --reporter` allows specifying how results should be logged
444
445#### Examples
446
447```bash
448# compile linked fonts
449clay compile fonts
450
451# compile inlined fonts
452clay compile fonts --inlined
453
454# compile linked and inline fonts
455clay compile fonts --inline --linked
456
457# compile fonts once for production environments
458clay compile fonts --minify
459```
460
461### Styles
462
463```bash
464clay compile styles [--watch] [--minify] [--plugins <space-separated list of postcss plugins>] [--reporter <reporter>]
465```
466
467Compile styleguide CSS files with PostCSS. Source files from `styleguides/<styleguide name>/components/<component name>.css` (and `styleguides/<styleguide name>/layouts/<layout name>.css`) will be compiled to `public/css/<component or layout name>.<styleguide name>.css`.
468
469By default, styles will be compiled using the [`import`](https://github.com/postcss/postcss-import), [`autoprefixer`](https://github.com/postcss/autoprefixer), [`mixins`](https://github.com/postcss/postcss-mixins), [`nested`](https://github.com/postcss/postcss-nested), and [`simple-vars`](https://github.com/postcss/postcss-simple-vars) PostCSS plugins, but you may specify additional plugins (that you have installed with `npm`) into the `--plugins` argument.
470
471Setting `CLAYCLI_COMPILE_ASSET_HOST` and `CLAYCLI_COMPILE_ASSET_PATH` will set the `$asset-host` and `$asset-path` variables, which allows linking to media hosted on other static file servers.
472
473```scss
474/* styleguides/example/components/example-component.css */
475.some-twitter-icon {
476 background-image: url('$asset-host/media/styleguides/example/twitter.svg');
477 background-size: 22px 18px;
478}
479```
480
481Specifying `--minify` (or using `CLAYCLI_COMPILE_MINIFIED` or more specifically `CLAYCLI_COMPILE_MINIFIED_STYLES`) will run the compiled CSS through [`clean-css`](https://github.com/jakubpawlowicz/clean-css).
482
483#### Arguments
484
485* `-w, --watch` enables watching of source files and their dependencies after compilation
486* `-m, --minify` enables minification of CSS
487* `-p, --plugins` allows running additional postcss plugins
488* `-r, --reporter` allows specifying how results should be logged
489
490#### Examples
491
492```bash
493# compile css
494clay compile styles
495
496# compile and watch css and any @import'ed css files
497clay compile styles --watch
498
499# compile css with additional postcss plugins
500clay compile styles --plugins postcss-preset-env stylelint
501
502# compile styles once for production environments
503clay compile styles --minify
504```
505
506### Templates
507
508```bash
509clay compile templates [--watch] [--minify] [--reporter <reporter>]
510```
511
512Precompile handlebars templates so they can be used by Kiln to re-render components (and layouts) on the client side. Note that it is strongly encouraged to enable minification even in dev environments, as specifying `--minify` (or using `CLAYCLI_COMPILE_MINIFIED` or more specifically `CLAYCLI_COMPILE_MINIFIED_TEMPLATES`) will minify the compiled templates with [UglifyJS](https://github.com/mishoo/UglifyJS) and bundle the them into six files based on the component/layout name. Minifying the templates provides the best balance between file size and the number of files Kiln has to fetch on page load.
513
514* `public/js/_templates-a-d.js`
515* `public/js/_templates-e-h.js`
516* `public/js/_templates-i-l.js`
517* `public/js/_templates-m-p.js`
518* `public/js/_templates-q-t.js`
519* `public/js/_templates-u-z.js`
520
521Templates will also be compiled to `public/js/<name>.template.js`.
522
523#### Arguments
524
525* `-w, --watch` enables watching of source files after compilation
526* `-m, --minify` enables bundling of precompiled templates
527* `-r, --reporter` allows specifying how results should be logged
528
529#### Examples
530
531```bash
532# precompile handlebars templates
533clay compile templates
534
535# precompile and bundle templates
536clay compile templates --minify
537
538# precompile, bundle, and watch templates
539clay compile templates --minify --watch
540```
541
542### Scripts
543
544```bash
545clay compile scripts [--watch] [--minify] [--globs <space-separated glob strings>] [--reporter <reporter>]
546```
547
548Compile component `client.js` and `model.js` files, kiln plugins, and legacy global JavaScript, while intelligently calculating and deduplicating dependencies. This generates a number of different types of files:
549
550* `public/js/<name>.client.js` from compiled `client.js`
551* `public/js/<name>.model.js` from compiled `model.js`
552* `public/js/_models-<letter>-<letter>.js` from compiled and _bundled_ `model.js`
553* `public/js/_kiln-plugins.js` from compiled kiln plugins in `services/kiln/`
554* `public/css/_kiln-plugins.css` from compiled kiln plugin styles in their `.vue` components
555* `public/js/_global.js` from compiled legacy scripts specified by the `--globs` argument
556* `public/js/<number>.js` from compiled dependencies of `client.js`, `model.js`, kiln plugin, or global scripts
557* `public/js/_deps-<letter>-<letter>.js` from compiled and bundled dependencies
558
559This also creates a number of files that are used for instantiating component controllers, serving scripts, and speeding up incremental builds:
560
561* `public/js/_client-init.js` script that instantiates `client.js` [component controllers which export a default function](https://claycms.gitbook.io/kiln/kiln-fundamentals/components#model-and-controller)
562* `public/js/_prelude.js` dynamic bundler initialization script
563* `public/js/_postlude.js` dynamic bundler access script, adds `window.require()` which enables loading of bundled dependencies
564* `public/js/_ids.json` cache of module IDs, used when serving bundles
565* `public/js/_registry.json` cache of module dependencies, used when serving bundles
566* `client-env.json` environment variables in `model.js` and dependencies, must be added to `.gitignore` (values for these variables are [passed to Amphora via `env`](https://claycms.gitbook.io/amphora/startup/instantiation#instantiation-arguments) on server start)
567* `browserify-cache.json` local cache for fast incremental builds, must be added to `.gitignore`
568
569Specifying `--minify` (or using `CLAYCLI_COMPILE_MINIFIED` or more specifically `CLAYCLI_COMPILE_MINIFIED_SCRIPTS`) will run all compiled scripts through [`terser`](https://github.com/fabiosantoscode/terser).
570
571This will also copy `clay-kiln-edit.js` and `clay-kiln-view.js` to `public/js` if you have Kiln installed. When you specify `--watch`, Kiln scripts will also be watched for changes.
572
573#### Dependency Management
574
575Any files you `require()` or `import` in your `client.js`, `model.js`, kiln plugins, or legacy global JavaScript are compiled to `<number>.js` and `_deps-<letter>-<letter>.js`, based on their name (for example, `lodash` might be compiled to `283.js` and `_deps-i-l.js`). When resolving media, call `claycli.compile.scripts.getDependencies()` in your Clay install's `resolveMedia` function to dynamically load necessary dependencies for view (`client.js` and legacy `_global.js`) and edit (`model.js` and kiln plugins) modes.
576
577```js
578// in your resolve-media service
579const getDependencies = require('claycli').compile.scripts.getDependencies;
580
581/**
582 * figure out what scripts and styles should be loaded on each page
583 * @param {object} media
584 * @param {array} media.scripts array of filenames from amphora
585 * @param {array} media.styles array of filenames from amphora
586 * @param {object} locals site info, edit mode info, etc from amphora
587 */
588function resolveMedia(media, locals) {
589 const assetPath = locals.site.assetPath; // from site config
590
591 // note: for this example, we're only dealing with scripts.
592 // your own media resolution must also take into account styles, fonts, and templates
593 if (locals.edit) {
594 // edit mode, get script dependencies for linking (so, bundled / minified files)
595 media.scripts = getDependencies(media.scripts, assetPath, { edit: true, minify: true });
596 } else {
597 // view mode, get script dependencies for inlining (so, individual dependency files)
598 media.scripts = getDependencies(media.scripts, assetPath);
599 }
600}
601```
602
603By convention, internal services are specified in a `services/` directory at the root of your Clay install. Services that work in both the client and server live in `services/universal/` (or `services/isomorphic/` if you prefer). If you have `services/client/` and `services/server/` directories, `claycli` will automatically substitute server-side dependencies with their client-side equivalents when compiling. This is useful for database / API calls and wrappers around 3rd party libraries that have wildly different Node.js vs browser implementations.
604
605#### Kiln Plugins
606
607This will look for kiln plugins in `services/kiln/index.js`. You may specify vuex plugins, custom inputs, toolbar buttons, and pre-publish validators, [among other things](https://claycms.gitbook.io/kiln/api-documentation/api). For example, you might have one validator, one input, and one vuex plugin:
608
609```js
610// services/kiln/index.js
611module.exports = () => {
612 // add globals if they don't already exist
613 window.kiln = window.kiln || {};
614 window.kiln.validators = window.kiln.validators || {};
615 window.kiln.inputs = window.kiln.inputs || {};
616 window.kiln.plugins = window.kiln.plugins || {};
617 // add your plugins into the globals
618 window.kiln.validators['unique-url'] = require('./validate-unique-url');
619 window.kiln.inputs['content-picker-button'] = require('./content-picker-button.vue');
620 window.kiln.plugins['kiln-error-tracking'] = require('./kiln-tracking-plugin');
621};
622```
623
624Any styles (denoted with `<style lang="postcss">` sections in your `.vue` components) will be extracted and bundled into `public/css/_kiln-plugins.css`, so please make sure to include it in your `resolveMedia` function in edit mode.
625
626#### Legacy Global Scripts
627
628If you have any legacy scripts that are not `require()`'d or `import`'d by your `client.js` or their dependencies, you may specify `--globs` to include them. They will be compiled and have their dependencies dynamically deduplicated in the same way as your other scripts, but will be served in view mode on _every page_.
629
630#### Arguments
631
632* `-w, --watch` enables watching of scripts and their dependencies after compilation
633* `-m, --minify` enables minification of scripts
634* `-g, --globs` allows compiling additional JavaScript
635* `-r, --reporter` allows specifying how results should be logged
636
637#### Examples
638
639```bash
640# compile scripts once
641clay compile scripts
642
643# compile and watch scripts and dependencies
644clay compile scripts --watch
645
646# compile scripts once for production environments
647clay compile scripts --minify
648
649# compile scripts, including legacy js
650# note: this glob will match all '.js' files in 'global/js/' unless they end in '.test.js',
651# which is a common unit testing convention
652clay compile scripts --globs 'global/js/!(*.test).js'
653```
654
655### Project Specific Config File
656
657Not all projects are the same, and for project specific compilation changes you can add a `claycli.config.js` file to your project's root. This file must simply export an Object whose contains key/value pairs are read during compilation. Good use cases for this file include:
658
659* Adding PostCSS plugins to [`styles`](https://github.com/clay/claycli#styles) compilation
660* Updating options passed into Autoprefixer
661* Changing Babel browser target to meet your env support requirements
662
663#### Arguments
664
665The `claycli.config.js` file currently supports the following arguments:
666
667* `plugins` (_Array_): list of PostCSS plugins that will be concatenated to the end of the list already supported by the `styles` compilation command
668* `babelTargets` (_Object_): the value of this property is passed to the [Babel `targets` option](https://babeljs.io/docs/en/babel-preset-env#targets) to describe the environments your compiled scripts support
669* `autoprefixerOptions` (_Object_): an Object which is [passed directly to `autoprefixer`](https://www.npmjs.com/package/autoprefixer#options) for style and Kiln plugin compilation
670* `customTasks` (_Array_): an Array of Gulp tasks to execute with the `clay compile custom-tasks` command.
671
672#### Example
673
674```js
675'use strict';
676
677module.exports = {
678 plugins: [
679 require('postcss-functions')({
680 functions: {
681 em: function (pixels, browserContext) {
682 var browserContext = parseInt(browserContext, 10) || 16,
683 pixels = parseFloat(pixels);
684
685 return pixels / browserContext + 'em';
686 }
687 }
688 })
689 ],
690 babelTargets: { browsers: ['> 2%'] },
691 autoprefixerOptions: { browsers: ['last 2 versions', 'ie >= 9', 'ios >= 7', 'android >= 4.4.2'] },
692 customTasks: [{
693 name: 'foobar',
694 fn: (cb) => {
695 // A gulp task to execute
696 cb();
697 }
698 }]
699};
700```
701
702### Custom Gulp Tasks
703
704Because not every implementation of Clay is the same, not all complilation will be the same. By adding custom Gulp tasks to your `claycli.config.js` file you can execute additional compilation/processing steps with claycli. Declare a `customTasks` array in your config file with each taks being an object with two properties: `name` and `fn`. The `name` property will be the name of the step to execute and the `fn` property is the actual step to execute.
705
706#### Example
707
708For example, given the following `claycli.config.js` file:
709
710```js
711'use strict';
712
713var { gulp } = require('claycli'),
714 concat = require('gulp-concat'),
715 uglify = require('gulp-uglify'),
716 gutil = require('gulp-util'),
717 argv = require('yargs').argv,
718 gulpif = require('gulp-if');
719
720module.exports = {
721 customTasks: [
722 {
723 name: 'polyfill',
724 fn: () => {
725 return gulp.src([
726 'global/polyfills.js',
727 'global/modernizr.js'
728 ])
729 .pipe(concat('polyfills.js'))
730 .pipe(gulpif(!argv.debug, uglify())).on('error', gutil.log)
731 .pipe(gulp.dest('public/js'));
732 }
733 }
734 ]
735};
736```
737**Important Notes:**
738
7391. Claycli exposes the instance of `gulp` that it users to make sure their is consistency between internal tasks and external ones
7402. This example of a custom task is all done inline, but the objects can be organizes and managed in different files
7413. When executing commands you have access to `argv` and can test options inside your custom functions.
7424. Each task is executed in isolation. This is not a replacement for a complete Gulp pipeline, rather it is meant to patch small tasks that fall outside normal Clay compilation.
743
744Executing `clay compile custom-tasks` will execute this task to produce a `polyfills.js` file.
745
746# Programmatic API
747
748The core `claycli` functionality is exposed as an api, allowing you to use it in Node.js. All main commands are properties of the exported `claycli` object.
749
750```js
751const { config, lint, import, export, compile } = require('claycli');
752```
753
754## Config
755
756Get `key` or `url` from config
757
758```js
759config.get(type, alias);
760```
761
762Set `key` or `url` in config
763
764```js
765config.set(type, alias, value);
766```
767
768Get full configuration object
769
770```js
771config.getAll();
772```
773
774## Lint
775
776Lint a url
777
778```js
779lint.lintUrl(url, { concurrency });
780```
781
782Lint a schema (passed in as a string of yaml)
783
784```js
785lint.lintSchema(yaml);
786```
787
788## Import
789
790Import a string of dispatches or bootstraps to the specified (site prefix) url
791
792```js
793import(string, url, { key, concurrency, publish, yaml });
794```
795
796Parse a string of bootstrap data into a stream of prefixed dispatches. _Note: does NOT do http calls_
797
798```js
799import.parseBootstrap(string, url);
800```
801
802Parse an object of bootstrap data into a stream of prefixes dispatches. This method is good if you want to handle converting Yaml to JSON in your own application where you might need memoization. _Note: does NOT do http calls_
803
804```js
805import.parseBootstrapObject(obj, url);
806```
807
808Parse a string of dispatches into a stream of prefixed dispatches. _Note: does NOT do http calls_
809
810```js
811import.parseDispatch(string, url);
812```
813
814## Export
815
816Export a single url, e.g. `domain.com/_components/foo` or `domain.com/_pages`
817
818```js
819export.fromURL(url, { concurrency, layout, yaml });
820```
821
822Export the results of a query (passed in as a string of yaml)
823
824```js
825export.fromQuery(url, query, { key, concurrency, layout, yaml, size });
826```
827
828Clear the layouts cache. when exporting pages with layouts, they'll be cached so they don't need to be exported for every page
829
830```js
831export.clearLayouts();
832```
833
834## Compile
835
836_Note:_ There is currently no single `require('claycli').compile` method that will compile all assets. Please use the individual `media`, `fonts`, `styles`, `templates`, and `scripts` methods as needed.
837
838Compile media files
839
840```js
841compile.media({ watch });
842```
843
844Compile fonts
845
846```js
847compile.fonts({ minify, watch, inlined, linked });
848```
849
850Compile styles
851
852```js
853compile.styles({ minify, watch, plugins });
854```
855
856Compile templates
857
858```js
859compile.templates({ minify, watch });
860```
861
862Compile scripts
863
864```js
865compile.scripts({ minify, watch, globs });
866```
867
868Calculate script dependencies. _Note:_ when calling this from `resolveMedia`, the first argument is `media.scripts`
869
870```js
871compile.scripts.getDependencies(scripts, assetPath, { edit, minify });
872```
873
874# Contributing
875
876Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/clay/claycli/issues/new).
877
878This project is released under the [MIT license](https://github.com/clay/claycli/blob/master/LICENSE).