• This repository has been archived on 27/Apr/2021
  • Stars
    star
    199
  • Rank 196,105 (Top 4 %)
  • Language
    JavaScript
  • Created over 9 years ago
  • Updated over 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Feature Tests for JavaScript

ES Feature Tests

Feature Tests for JavaScript. This is the library used by the FeatureTests.io service.

If you're looking for the repository for the site itself, not this library, go here instead.

Why

Load the library, request feature test results for the current browser, use those results to determine what code to deliver for your application!

If all the JavaScript features/syntax your code uses are supported natively by the browser, why would you load up the ugly transpiled code? Why would you load dozens of kb of polyfills/shims if all (or most of) those APIs are already built-in?

Just use the original authored ES6+ code in newest browsers! Only use transpiled code and polyfills/shims for browsers which are missing the features/syntax you need.

Don't rely on stale caniuse data baked into build tools that matches a browser based on brittle UserAgent string parsing. Feature Test! That's the most reliable and sensible approach.

For much more detail about the why motivations and sanity checking the risks/concerns about scalability/reliability, see ES6: Features By Testing.

Documentation

The updated and detailed documentation for how this library works and what test results are available can be found on FeatureTests.io/details.

Hosting vs. Hosted

Hosting this package locally on your server is mostly useful if you want to use the feature tests in your Node/iojs programs (see "Node/iojs" below).

You can install this package locally and web host your own copy of the library files if you prefer. You'll need to modify the URLs ("https://featuretests.io") in several places to get them to load correctly. Hosting the files also means the test results won't be shareable with other sites, which puts more testing burden on users' machines.

Another concern that only applies if you're self-hosting and running your own tests is that all of the syntax-realted tests require using new Function(..) (or, ugh, eval(..)). If your site has a restrictive CSP, you will not be able to run those tests unless you relax it to allow unsafe-eval. By allowing the service to run the tests, that CSP policy is contained to the "featuretests.io" domain instead of polluting your site's domain.

It's probably a much better idea to use the "https://featuretests.io" service's hosted versions of the files for web usage.

Web

Using this library on the web:

<script src="https://featuretests.io/rs.js"></script>
<script>
window["Reflect.supports"]( "all", function(results,timestamp){
	console.log( results );
	// {
	//    ..
	// }
});
</script>

Node/iojs

Using this library in Node/iojs:

npm install es-feature-tests

Then:

var ReflectSupports = require("es-feature-tests");

ReflectSupports( "all", function(results,timestamp){
	console.log( results );
	// {
	//    ..
	// }
});

Testify CLI

This package also includes a testify CLI tool, which scans files for ES6 features and produces the code for a JS function called checkFeatureTests(..). For example:

function checkFeatureTests(testResults){return testResults.letConst&&testResults.templateString}

As shown, checkFeatureTests(..) receives the feature test results (as provided by this es-feature-tests library), and returns true or false indicating if the test results are sufficient or not. This test tells you if your ES6-authored files can be loaded directly into the environment in question, or if you need to load the transpiled version of your code.

In the preceding example, both the letConst test result and the templateString test result must pass for checkFeatureTests(..) to pass.

By letting testify scan your files, you won't need to manually maintain a list of checks for your code base. Just simply run testify during your build process, and include the code it produces (like shown above) into your initial bootstrapped code that will run the feature tests. Use the generated checkFeatureTests(..) with the es-feature-tests library like so:

var supports = window["Reflect.supports"];

// or in Node:
// var supports = require("es-feature-tests");

supports( "all", function(results){
	if (checkFeatureTests(results)) {
		// load ES6 code
	}
	else {
		// load transpiled code instead
	}
});

The testify CLI tool has the following options:

usage: testify [--file|--dir]=path [opt ...]

options:
--help                    show this help

--file=file               scan a single file
--dir=directory           scan all files in a directory
--exclude=pattern         exclude any included paths that match pattern (JS regex)
-C, --input               scan file contents from STDIN

--output=[simple|json|babel|traceur]
                          control output format (see docs)
                          (default: simple)
--enable=test-name        force inclusion of a test by name
--disable=test-name       force exclusion of a test by name

-R, --recursive           directory scan is recursive
                          (default: off)
-M, --ignore-missing      ignore missing dependency files
                          (default: off)
-I, --ignore-invalid      ignore JS parsing issues
                          (default: off)

Specify file(s) to scan by using one or more --file and/or --dir flags, and/or import text contents via STDIN by specifying --input (-C).

If you use --dir, that directory's contents will be examined (non-recursively), and all found JS files will be scanned. Use --recursive (-R) to recursively examine sub-directories. To exclude any files/paths from this processing, use one or more --exclude flags, specifying a JS-style regular expression to match for exclusion (note: to avoid shell escaping issues, surround your regex in ' ' quotes).

The default (--output=simple) output of the testify CLI tool is the code for the checkFeatureTests(..) function, as described above. If you'd prefer to receive a JSON string holding the array of tests needed by name, specify --output=json. If you want to produce a Babel config with tests needed mapped to the whitelist option, use --output=babel. To produce the configuration for Traceur, use --output=traceur.

To force the inclusion of a specific test check, use --enable and specify the name (matching the test result name from this es-feature-tests library). To exclude a specific test check, use --disable and specify the matching name.

Suppress errors for missing scan files with --ignore-missing and for invalid files (failure to parse the JS) with --ignore-invalid.

Testify Library

testify can also be used programmatically in JS:

var testify = require("es-feature-tests/testify"),
	code = testify.scan({ ..options.. });

// (Optional) To use the function inside Node:
var checkFeatureTests = new Function(
	"res",
	code + ";return checkFeatureTests(res)"
);

The options correspond similarly to the CLI parameters described above:

  • files (string, array): specifies file(s) to scan

  • dirs (string, array): specifies director(ies) of file(s) to scan

  • excludes (string, array): specifies exclusion pattern(s)

  • content (string): specifies text to scan as if it was already read from a file

  • output (string: "simple", "json", "babel", "traceur"): controls the output formatting of the list of tests needed

    Note: The CLI --output option defaults to "simple" (the code for checkFeatureTests(..)), but the default value for the library option is "json", which *actually produces the array object itself, since that will likely be more useful when used programmatically.

  • enabled (string, array): specifies test(s) that should always be included

  • disabled (string, array): specifies test(s) that should never be included

  • recursive (boolean, default: false): make directory scans recursive

  • ignore (object, boolean): if true/false, will set all sub-properties accordingly; otherwise, should be an object with one or more of these:

    • ignore.missing (boolean): ignore files or directories not found
    • ignore.invalid (boolean): ignore files where the scan fails

Note: files, dirs, and excludes all have the -s suffix, and enabled and disabled both have the -d suffix. However, the associated CLI parameter names do not have these suffixes.

GitHub

If you install this package from GitHub instead of npm, you won't have the deploy/* files for deployment. Run these commands from the main repo directory to build them:

npm install
npm run build

License

The code and all the documentation are all (c) 2015 Kyle Simpson and released under the MIT license.

http://getify.mit-license.org/

More Repositories

1

You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
178,746
star
2

Functional-Light-JS

Pragmatic, balanced FP in JavaScript. @FLJSBook on twitter.
JavaScript
16,593
star
3

LABjs

Loading And Blocking JavaScript: On-demand parallel loader for JavaScript with execution order dependencies
HTML
2,277
star
4

asynquence

Asynchronous flow control (promises, generators, observables, CSP, etc)
JavaScript
1,743
star
5

CAF

Cancelable Async Flows (CAF)
JavaScript
1,332
star
6

monio

The most powerful IO monad implementation in JS, possibly in any language!
JavaScript
1,049
star
7

TNG-Hooks

Provides React-inspired 'hooks' like useState(..) for stand-alone functions
JavaScript
1,011
star
8

native-promise-only

A polyfill for native ES6 Promises as close as possible (no extensions) to the strict spec definitions.
JavaScript
723
star
9

A-Tale-Of-Three-Lists

Comparing various async patterns for a single demo
JavaScript
651
star
10

fasy

FP iterators that are both eager and asynchronous
JavaScript
546
star
11

FPO

FP library for JavaScript. Supports named-argument style methods.
JavaScript
449
star
12

youperiod.app

YouPeriod.app -- the privacy-first period tracking app
JavaScript
442
star
13

JSON.minify

Simple minifier for JSON to remove comments and whitespace
409
star
14

TypL

The Type Linter for JS
JavaScript
374
star
15

h5ive-DEPRECATED

**DEPRECATED** A collection of thin facade APIs wrapped around HTML5 JavaScript features.
JavaScript
324
star
16

eslint-plugin-proper-arrows

ESLint rules to ensure proper arrow function definitions
JavaScript
305
star
17

foi-lang

Foi: a different kind of functional programming language
JavaScript
303
star
18

grips

Simple-logic templates
JavaScript
287
star
19

moduloze

Convert CommonJS (CJS) modules to UMD and ESM formats
JavaScript
207
star
20

let-er

DEPRECATED: Transpile non-ES6 let-blocks into ES6 (or ES3)
JavaScript
192
star
21

Incomplete-JS

"The Incomplete Guide to JavaScript" (book). @IncompleteJS on twitter.
190
star
22

revocable-queue

Specialized async queue data structure, supports revocation of values
JavaScript
176
star
23

deePool

highly-efficient pool for JavaScript objects
JavaScript
118
star
24

getify.github.io

JavaScript
113
star
25

concrete-syntax-tree

Defining a standard JavaScript CST (concrete syntax tree) to complement ASTs
107
star
26

eslint-plugin-proper-ternary

ESLint rules to ensure proper usage of ternary/conditional expressions
JavaScript
96
star
27

cloud-sweeper

A casual game built for the web.
JavaScript
94
star
28

BikechainJS

JavaScript VM engine (powered by V8); server-side environment modules; server-side synchronous web app controllers
C++
82
star
29

wepuzzleit

Demo PoC game for various advanced HTML5 js APIs
JavaScript
79
star
30

workshop-periodic-table

66
star
31

elasi

EL/ASI: Encrypt Locally, Account Secure Interchange
JavaScript
62
star
32

remote-csp-channel

Remote bridge for CSP channels
JavaScript
55
star
33

ScanTree

Scan a JS file tree to build an ordered and grouped dependency listing
JavaScript
51
star
34

dwordly-game

A game where words dwindle down to the shortest possible
JavaScript
42
star
35

stable-timers

timers with less race conditions
JavaScript
38
star
36

emdash

Simple blogging with node/iojs + GitHub.
36
star
37

domio

DOM and Event helpers for Monio
JavaScript
30
star
38

eslint-plugin-no-optional-call

ESLint plugin to disallow the optional-call operator
JavaScript
30
star
39

eslint-plugin-arrow-require-this

DEPRECATED: ESLint rule to require arrow functions to reference the 'this' keyword
JavaScript
28
star
40

import-remap

Rewrite ES module import specifiers using an import-map.
JavaScript
25
star
41

gum-try-hd

Try to enforce HD (16:9) camera aspect ratio for web-video calls
JavaScript
25
star
42

Mock-DOM-Resources

A mock of (parts of) the DOM API to simulate resource preloading and loading
JavaScript
25
star
43

make-a-game

some project files for a tutorial on making a simple web game
JavaScript
25
star
44

mpAjax

framework plugin for handling multi-part Ajax responses
JavaScript
23
star
45

asyncGate.js

DEPRECATED. asynchronous gate for javascript
JavaScript
21
star
46

tic-tac-toe-workshop

Workshop files for building tic-tac-toe in JS and <canvas>
21
star
47

esre

esre: fully configurable JS code formatting
20
star
48

workshop-chess-diagonals

17
star
49

featuretests.io

JavaScript Feature Tests... as a service
JavaScript
16
star
50

FoilScript

FoilScript: a new dialect of JS that fixes the sucky parts but still looks and feels like JS
16
star
51

literalizer

Specialized heuristic lexer for JS to identify complex literals
JavaScript
16
star
52

normalize-selector

Normalize CSS selectors
JavaScript
14
star
53

DOMEventBridge

Bridge DOM events to a JS event hub (for pubsub)
JavaScript
14
star
54

pong-around-workshop

Workshop files for building a pong-variant game in JS and <canvas>
12
star
55

workshop-wordy-unscrambler

11
star
56

shortie.me

Proof-of-concept demo for server-side JavaScript driven "middle-end" architecture
JavaScript
11
star
57

workshop-knights-dialer

8
star
58

middleend-boilerplate

Boilerplate Starting Point for Middle-end Web Architecture
JavaScript
8
star
59

demo-app-weatheround

JavaScript
7
star
60

the-economy-of-keystrokes-slides

Slides code built for "The Economy of Keystrokes" talk
JavaScript
6
star
61

santa-connect-app

Santa Connect: keeping track of your kids' nice/naughty status
JavaScript
5
star
62

nyc-bug-demo

bug demo for NYC code coverage tool
JavaScript
4
star
63

unnamed

unnamed (for now). nothing to see here. ;-)
JavaScript
2
star
64

my-lifesheets

CSS
1
star
65

breakthewebforward.com

JavaScript
1
star