1677106920
Bili Makes It Easier to Bundle JavaScript Libraries
CSS
Sass
Stylus
Less
CSS modules
.Author: Egoist
Source Code: https://github.com/egoist/bili
License: MIT license
1676534466
Template project for setting up a TypeScript monorepo
The main focus of this repo is making the
Go to definition
feature in IDEs work without any surprises, meaning it will work after a fresh clone without needing to build the project.
The secondary focus is to remove surprises when publishing packages. The repo is set up so that each package gets a clean build output without any artifacts from other packages.
Everything else is kept to a minimum. Apart from my personal ESLint config to keep the code clean, there are no extra tools included β you're free to customize this to your own needs after cloning. Compilation targets, module systems, tree shaking etc. are left up to you to decide.
This repo uses pnpm, but should work fine with any of the following:
I strongly recommend pnpm
over the other solutions, not only because it's usually faster, but because it avoids dependency problems caused by hoisting (see https://github.com/NiGhTTraX/ts-monorepo/commit/d93139166b25fab15e9538df58a7d06270b846c9 as an example).
# Install pnpm with your preferred method: https://pnpm.io/installation.
npm i -g pnpm
# Install all dependencies.
pnpm i
See the following blog posts:
If you're looking for the project references solution checkout the project-references
branch.
This repo contains two types of workspaces:
packages
: meant to be published to npm and installed,apps
: meant to be executed.A good example to illustrate the difference is create-react-app
: you wouldn't publish an app like this to npm, you would run it, more specifically you would build the JS bundle and then deploy that somewhere.
For packages, you don't want to bundle all the monorepo dependencies, and instead publish them individually. That's why packages have a separate build tsconfig.json
that resolves monorepo dependencies to node_modules
.
Use tsconfig-paths to resolve the path aliases at runtime:
{
"scripts": {
"start": "ts-node -r tsconfig-paths/register src/index.ts"
}
}
See the full example here.
Use babel-plugin-module-resolver to resolve the path aliases:
module.exports = {
presets: [
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-typescript",
],
plugins: [
[
"module-resolver",
{
alias: {
"^@nighttrax/(.+)": "../\\1/src",
},
},
],
],
};
See the full example here.
Use tsconfig-paths-webpack-plugin to resolve the path aliases:
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
module.exports = {
resolve: {
plugins: [new TsconfigPathsPlugin()]
}
};
See the full example here.
If you use Babel
then see this example from the Babel section above.
If you use ts-jest then you can use its pathsToModuleNameMapper
helper:
const { pathsToModuleNameMapper } = require("ts-jest");
const { compilerOptions } = require("../../tsconfig.json");
module.exports = {
preset: "ts-jest",
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
// This has to match the baseUrl defined in tsconfig.json.
prefix: "<rootDir>/../../",
}),
};
See the full example here.
Use craco or react-app-rewired to extend CRA's webpack config and apply the tsconfig-paths-webpack-plugin:
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
module.exports = (config) => {
// Remove the ModuleScopePlugin which throws when we
// try to import something outside of src/.
config.resolve.plugins.pop();
// Resolve the path aliases.
config.resolve.plugins.push(new TsconfigPathsPlugin());
// Let Babel compile outside of src/.
const oneOfRule = config.module.rules.find((rule) => rule.oneOf);
const tsRule = oneOfRule.oneOf.find((rule) =>
rule.test.toString().includes("ts|tsx")
);
tsRule.include = undefined;
tsRule.exclude = /node_modules/;
return config;
};
See the full example here. For tests, see the jest example.
Use vite-tsconfig-paths in the Vite config:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
plugins: [
react(),
tsconfigPaths()
],
});
See full example here.
Extend Next's webpack config to enable compiling packages from the monorepo:
module.exports = {
webpack: (config) => {
// Let Babel compile outside of src/.
const tsRule = config.module.rules.find(
(rule) => rule.test && rule.test.toString().includes("tsx|ts")
);
tsRule.include = undefined;
tsRule.exclude = /node_modules/;
return config;
},
};
See the full example here.
Include the path aliases in both tsconfig.json
and tsconfig.build.json
and tell NestJS where to find the main.js
file:
{
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"entryFile": "apps/nestjs/src/main"
}
See the full example here.
Extend Storybook's webpack config and apply the tsconfig-paths-webpack-plugin:
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
module.exports = {
webpackFinal: async (config) => {
config.resolve.plugins = [
...(config.resolve.plugins || []),
new TsconfigPathsPlugin({
extensions: config.resolve.extensions,
}),
];
return config;
},
};
See the full example here.
Author: NiGhTTraX
Source Code: https://github.com/NiGhTTraX/ts-monorepo
License: MIT license
1674880569
A familiar and performant compile time CSS-in-JS library for React.
import { styled, ClassNames } from '@compiled/react';
// Tie styles to an element
<div css={{ color: 'purple' }} />
// Create a component that ties styles to an element
const StyledButton = styled.button`
color: ${(props) => props.color};
`;
// Use a component where styles are not necessarily tied to an element
<ClassNames>
{({ css }) => children({ className: css({ fontSize: 12 }) })}
</ClassNames>
Turn on extraction and all components styled in your app and sourced through NPM will have their runtime stripped and styles extracted to an atomic style sheet.
-import { CC, CS } from '@compiled/react/runtime';
-
-const _2 = '._syaz1q9v{color: hotpink}';
-const _ = '._1wybfyhu{font-size: 48px}';
-
export const LargeHotPinkText = () => (
- <CC>
- <CS>{[_, _2]}</CS>
<span className="_syaz1q9v _1wybfyhu">Hello world</span>
- </CC>
);
._1wybfyhu {
font-size: 48px;
}
._syaz1q9v {
color: hotpink;
}
See CSS extraction for more information.
Install the React package.
npm install @compiled/react
Then configure your bundler of choice or use Babel directly.
Install the Webpack loader.
npm install @compiled/webpack-loader --save-dev
See installation for more information.
Install the Parcel v2 configuration.
npm install @compiled/parcel-config --save-dev
Extend from the .parcelrc
configuration:
{
"extends": ["...", "@compiled/parcel-config"]
}
See installation for more information.
Install the Babel plugin.
npm install @compiled/babel-plugin --save-dev
See installation for more information.
Contributions are welcomed! Please see CONTRIBUTING.md to get started.
Author: Atlassian-labs
Source Code: https://github.com/atlassian-labs/compiled
License: Apache-2.0 license
1673149380
Postlight's Modern Serverless Starter Kit adds a light layer on top of the Serverless framework, giving you the latest in modern JavaScript (ES6 via Webpack, TypeScript if you want it, testing with Jest, linting with ESLint, and formatting with Prettier), the ease and power of Serverless, and a few handy helpers (like functions for handling warm functions and response helpers).
Once installed, you can create and deploy functions with the latest ES6 features in minutes, with linting and formatting baked in.
Read more about it in this handy introduction.
Note: Currently, this starter kit specifically targets AWS.
# If you don't already have the serverless cli installed, do that
yarn global add serverless
# Use the serverless cli to install this repo
serverless install --url https://github.com/postlight/serverless-typescript-starter --name <your-service-name>
# cd into project and set it up
cd <your-service-name>
# Install dependencies
yarn install
Creating and deploying a new function takes two steps, which you can see in action with this repo's default Hello World function (if you're already familiar with Serverless, you're probably familiar with these steps).
serverless.yml
In the functions section of ./serverless.yml
, you have to add your new function like so:
functions:
hello:
handler: src/hello.default
events:
- http:
path: hello
method: get
Ignoring the scheduling event, you can see here that we're setting up a function named hello
with a handler at src/hello.ts
(the .default
piece is just indicating that the function to run will be the default export from that file). The http
event says that this function will run when an http event is triggered (on AWS, this happens via API Gateway).
This starter kit's Hello World function (which you will of course get rid of) can be found at ./src/hello.ts
. There you can see a basic function that's intended to work in conjunction with API Gateway (i.e., it is web-accessible). Like most Serverless functions, the hello
function is asynchronous and accepts an event & context. (This is all basic Serverless; if you've never used it, be sure to read through their docs.
You can develop and test your lambda functions locally in a few different ways.
To run the hello function with the event data defined in fixtures/event.json
(with live reloading), run:
yarn watch:hello
To spin up a local dev server that will more closely match the API Gateway endpoint/experience:
yarn serve
Jest is installed as the testrunner. To create a test, co-locate your test with the file it's testing as <filename>.test.ts
and then run/watch tests with:
yarn test
When you add a new function to your serverless config, you don't need to also add it as a new entry for Webpack. The serverless-webpack
plugin allows us to follow a simple convention in our serverless.yml
file which is uses to automatically resolve your function handlers to the appropriate file:
functions:
hello:
handler: src/hello.default
As you can see, the path to the file with the function has to explicitly say where the handler file is. (If your function weren't the default export of that file, you'd do something like: src/hello.namedExport
instead.)
Lambda functions will go "cold" if they haven't been invoked for a certain period of time (estimates vary, and AWS doesn't offer a clear answer). From the Serverless blog:
Cold start happens when you execute an inactive (cold) function for the first time. It occurs while your cloud provider provisions your selected runtime container and then runs your function. This process, referred to as cold start, will increase your execution time considerably.
A frequently running function won't have this problem, but you can keep your function running hot by scheduling a regular ping to your lambda function. Here's what that looks like in your serverless.yml
:
custom:
warmup:
enabled: true
events:
- schedule: rate(5 minutes)
prewarm: true
concurrency: 2
The above config would keep all of your deployed lambda functions running warm. The prewarm
flag will ensure your function is warmed immediately after deploys (so you don't have to wait five minutes for the first scheduled event). And by setting the concurrency
to 2
, we're keeping two instances warm for each deployed function.
Under custom.warmup
, you can set project-wide warmup behaviors. On the other hand, if you want to set function-specific behaviours, you should use the warmup
key under the select functions. You can browse all the options here.
Your handler function can then handle this event like so:
const myFunc = (event, context, callback) => {
// Detect the keep-alive ping from CloudWatch and exit early. This keeps our
// lambda function running hot.
if (event.source === 'serverless-plugin-warmup') {
// serverless-plugin-warmup is the source for Scheduled events
return callback(null, 'pinged');
}
// ... the rest of your function
};
export default myFunc;
Copying and pasting the above can be tedious, so we've added a higher order function to wrap your run-warm functions. You still need to config the ping in your serverless.yml
file; then your function should look like this:
import runWarm from './utils';
const myFunc = (event, context, callback) => {
// Your function logic
};
export default runWarm(myFunc);
The Serverless framework doesn't purge previous versions of functions from AWS, so the number of previous versions can grow out of hand and eventually filling up your code storage. This starter kit includes serverless-prune-plugin which automatically prunes old versions from AWS. The config for this plugin can be found in serverless.yml
file. The defaults are:
custom:
prune:
automatic: true
number: 5 # Number of versions to keep
The above config removes all but the last five stale versions automatically after each deployment.
Go here for more on why pruning is useful.
If you have environment variables stored in a .env
file, you can reference them inside your serverless.yml
and inside your functions. Considering you have a NAME
variable:
In a function:
process.env.NAME
In serverless.yml
:
provider:
name: ${env:NAME}
runtime: nodejs12.x
You can check the documentation here.
Assuming you've already set up your default AWS credentials (or have set a different AWS profile via the profile field):
yarn deploy
yarn deploy
will deploy to "dev" environment. You can deploy to stage
or production
with:
yarn deploy:stage
# -- or --
yarn deploy:production
After you've deployed, the output of the deploy script will give you the API endpoint for your deployed function(s), so you should be able to test the deployed API via that URL.
π¬ A Labs project from your friends at Postlight. Happy coding!
Author: Postlight
Source Code: https://github.com/postlight/serverless-typescript-starter
1672502880
Language grammar for all versions of JavaScript including ES2016 and ESNext, JSX syntax as used by Facebook React, Atom's etch and others, as well as optional typed JavaScript using Facebook flow. This package also supports highlighting of GraphQL language constructs when inside certain JavaScript template strings. For .graphql
and .gql
file support please see language-graphql . The colour of syntax is determined by the theme in use.
The package also provides
By default the language-babel package will detect file types .js
,.babel
,.jsx
, .es
, .es6
, .mjs
and .flow
. Use the standard ATOM interface to enable it for other file types. This provides a grammar that scopes the file in order to colour the text in a meaningful way. If other JavaScript grammars are enabled these may take precedence over language-babel. Look at the bottom right status bar indicator to determine the language grammar of a file being edited. language-babel will be shown as either Babel
or Babel ES6 JavaScript
. Clicking the name will allow the grammar for a file to be changed.
language-babel provides Babel V6 & V5 transpiler support. If you only require grammar/syntax highlighting ensure that the package settings Transpile On Save
and Allow Local Override
are both off.
Install via ATOM or by using apm install language-babel
. If you only need to use the provided grammar read no further!
JSX tag closures are provided as auto-complete options. In addition, common HTML elements and their associated properties are displayed as auto-complete lists. Those supported by language-babel are described here
JSX elements cannot be commented out by using standard //
or /* */
commenting. Normally {/* */}
is used instead. language-babel changes the Atom toggle comments behaviour when inside a JSX block to support this behaviour. Nested elements within JSX that require a // form of commenting will be detected automatically.
When a newline is inserted between a matched open/close pair of JSX tags, language-babel inserts an additional line and positions the cursor. If Auto Indent is also turned on then the cursor is correctly indented.
The package setting Auto Indent JSX
if enabled will auto-indent any JSX code typed or moved across using suitable Atom defaults. There are also three commands - language-babel:toggle-auto-indent-jsx
, language-babel:auto-indent-jsx-on
and language-babel:auto-indent-jsx-off
that override the default behaviour. These can be mapped to keyboard shortcuts if needed.
Auto-Indenting will also attempt to read the .eslintrc
file associated with an edited file's project for the presence of four properties whose defaults are shown below. These rules, which are part of the ESLint-plugin-React EsLint plugin, are then used to determine the alignment and tab/spaces spacing of JSX elements. For more information on the options for these rules see Closing bracket, Indent and Indent Props.
Please note that no attempt is currently made to read eslint settings in any other file. e.g. package.json
, eslint.js
, extends...
, etc.
{
"rules": {
"indent": 1,
"react/jsx-closing-bracket-location": 1,
"react/jsx-indent-props": 1,
"react/jsx-indent": 1
}
}
When moving around a JSX block language-babel reformats the preceding JSX lines automatically. Lines following the cursor are not indented. This is to protect the source code following incomplete JSX from being processed. The user should correctly position the first JSX element as auto-indenting will not do this.
You may also turn off automatic indenting for all files by setting the package option Auto Indent JSX
language-babel fully supports the Babel JavaScript transpiler versions 5, 6 and 7.
Options in the language-babel package settings and/or in .languagebabel
project based JSON files allow for Babel validations to be carried out on a file saves using .babelrc
options. A file tree context menu - Language-Babel
- is also provided that allows whole directories to be transpiled obeying any .babelrc
and .languagebabel
settings. Even if using a workflow such as gulp, webpack, etc, this can be very useful. Additional options allow the output from Babel (transpiled code and maps ) to be output to other directories.
It is also possible to preview any source file as Babel would output it.
Babel code can be previewed as shown below. Source mapping keeps the ES201x file's cursor in step with the transpiled code's cursor. This feature requires the Atom package source-preview in which language-babel
becomes a provider of transpiled output which source-preview
consumes.
Please note that the following two packages should be disabled or uninstalled to stop multiple packages contending for the same transpile - source-preview-babel and source-preview-react.
source-preview
provides a keyboard toggle to view the current file. As with transpiling described below, a project must have the relevant .babelrc
, package.json
and node_modules
This package works by using the concept of a project folder which we assume contains a project or even nested projects any of which may contain a Babel project. In a Babel project, we expect to see one or more .babelrc
files, node_modules
folders at the root's of the project containing an optional @babel/core
babel-core
and other babel plugins/presets as determined by the project's package.json
file. In addition, we may expect to see one or more .languagebabel
files in the project. Projects are either implicit (an Atom project folder) or explicit (denoted by a .languagebabel
property of "projectRoot": true
). If no @babel/core
or babel-core
is found in the project then a check is made to determine if this is part of a Yarn workspace and if so a further check is made in the workspace node_modules for @babel/core
or babel-core
. If none are found then a version will be provided by language-babel
but this will be a Babel Version 6 instance. Plugins and presets will not be provided by the package.
A trivial example project that shows examples of using .languagebabel
and .babelrc
files may be found here.
Multiple projects may be open at any time inside Atom and language-babel
must allow the use of differing babel-core
versions and associated plugins when transpiling. It does this by using background tasks - one per Babel project. When a language-babel
grammar enabled file is saved the package settings and optionally any .languagebabel
configuration files are read to determine if the file should be transpiled and what to do with the output. These settings and .languagebabel
options are described below.
It is very easy to ensure that language-babel does not transpile files that are not needed. Just turn off the global package setting Transpile On Save
and turn on Allow Local Override
. Apart from grammar highlighting only projects having a .languagebabel
in the file path will then be affected by this package. Further granularity is easy too.
If .babelrc
and/or package.json
files contain Babel properties that are environment specific these environments should be created before Atom is started. In particular, Babel assumes a development
environment by default, whereas Atom assumes a production
environment by default.
e.g.
Windows
set NODE_ENV="development"
atom
OSX/Unix
NODE_ENV="development"
atom
For most projects, it is better to configure language-babel
via project-based .languagebabel
file properties which will override the package settings below. See ".langeuagebabel Configuration" for more information on this behaviour.
If set this allows .languagebabel
file properties to override the global package settings.
On any file save of a language-babel
grammar enabled file the Babel transpiler is called. No actual transpiled file is saved but any Babel errors and/or successful indicators are notified by an ATOM pop-up. Not all files are candidates for transpilation as other settings can affect this. For example see Disable When No Babelrc File In Path
and Babel Source Path
below.
{"transpileOnSave": true} or
{"transpileOnSave": false}
If enabled together with Transpile On Save
this will output JavaScript code to a .js
file with the same prefix as the original. By using the Babel Transpile Path
options it is possible to transpile to a different target directory. Not all files are candidates for transpilation as other settings can affect this.
{"createTranspiledCode": true} or
{"createTranspiledCode": false}
Disables transpiler if no .babelrc
files are found in the source file path.
{"disableWhenNoBabelrcFileInPath": true} or
{"disableWhenNoBabelrcFileInPath": false}
Suppress all successful save messages. Errors are still notified.
{"suppressTranspileOnSaveMessages": true} or
{"suppressTranspileOnSaveMessages": false}
This is set by default so that when a file is saved that is outside the Babel Source Path
directory no message is generated. This is particularly useful when you have mixed ES2015 and ES3-5 environment. ES2015 files can be placed inside a Babel Source Path
where they will be transpiled and other files will not pop up annoying messages when being saved.
{"suppressSourcePathMessages": true} or
{"suppressSourcePathMessages": false}
If transpiled output is being saved a separate source map can be also be saved. The source file name will be used with a new suffix of .js.map
and sent to a directory specified in Babel Maps Path
.
If .babelrc
files use the sourceMaps: inline
or sourceMaps both
option, turn this createMap
option off as the map data is stored as part of the source file.
{"createMap": true} or
{"createMap": false}
If a source map is created using the Create Map
option above then this appends a Url reference //# sourceURL=sourcefile.js.map
to the transpiled JavaScript file.
{"babelMapsAddUrl": true} or
{"babelMapsAddUrl": false}
.languagebabel
files)A .languagebabel
property that defines this directory is a project root. A project root would contain a node_modules
folder with an optional babel-core
as well as any plugins required.
{"projectRoot": true} or
{"projectRoot": false}
These a directories based on the project root. A project root is either implicit ( based on an Atom folders root directory) or explicit ( based upon the root defined in the nearest .languagebabel
file with a property "projectRoot": true
)
Only files found under the project/babelsourcepath
will be candidates for transpilation. If multiple project root folders exist then babelsourcepath
may exist in any or all folders.
The Transpile and Maps paths allow different target directories to be specified. If multiple project root folders exist then they may exist in any or all folders.
e.g. Two project root folders exist /proj1
and /proj2
. If Source Path is set to babelSource
the Transpile Path is set to babelTranspile
and the Maps Path is set to babelMaps
then:-
/proj1/babelSource/foo.es6
->/proj1/babelTranspile/foo.js
,/proj1/babelMaps/foo.js.map
{
"projectRoot": true,
"babelSourcePath": "babelSource",
"babelTranspilePath": "babelTranspile",
"babelMapsPath": "babelMaps"
}
/proj2/babelSource/dirBar/foo.es6
-> /proj2/lib/foo.js
,/proj2/lib/foo.js.map
{
"projectRoot": true,
"babelSourcePath": "babelSource/dirBar",
"babelTranspilePath": "lib",
"babelMapsPath": "lib"
}
When enabled any target directories that do not exist will be created prior to a transpilation.
{"createTargetDirectories": true} or
{"createTargetDirectories": false}
Keeps the source filename extension as the target filename extension
Enables automatic indenting of JSX.
This package setting allows language-babel to include third party grammars to highlight code inside template literal strings. These may be tagged template literals, described here, or where no appropriate function tag exists, another form of tag marking that signifies the templates nature. e.g. A comment string.
For example you may wish to highlight templates prefixed with /* @html */`<div></div>`
as HTML, and maybe sql`select * from table foo`
as SQL. The latter assumes a tagged function named sql exists in the code.
In order to do this, you need to find a language package that supports the highlighting of the template code. This language package should then be installed into Atom. You then need to find the scope name for that grammar. This can be done in a number of ways, but if you view the grammars JSON/CSON file and look for the scopeName
property field, this indicates the scope name for that grammar.
If we use the Atom provided languages language-css, language-html and language-sql in our example above to highlight the template code, then this field would look like.
"(?:css\.(?:[a-z])+)":source.css, /* @html */:text.html.basic, sql:source.sql
In other words, the package settings for this field is an array of strings, with each string in the form of template-prefix:grammar-scopename#optional-include
.
where:
template-prefix
is a literal string or an Oniguruma regular expression ( Oniguruma is the regular expression engine for TextMate grammars used by Atom) that comes before the opening back-tick of a template. A literal string may contain any characters except a comma but including colons. A regular expression is denoted by being enclosed by double quote marks "RegExp Here"
. Most importantly, a regular expression should create no capturing groups.:
The last colon in the string signifies the start of the embedded grammars scopeName.grammar-scopename
is the scopeName of the grammar used to highlight the template.#optional-include
if present, will use that include block in the grammars repository.This flag if set will enable Emmet snippets to be used inside CSS templates. If a valid emmet abbreviation is entered then the expanded snippet will appear at the top of a auto-complete list. Pressing the appropriate auto-complete key (normally tab) will expand the snippet.
.languagebabel
JSON configuration files can exist in any directory of the path that contains a source file to be compiled. The properties in this file override the global package settings above. If .languagebabel
files are present, they read and merged starting in the source files directory up to the project root directory. Properties defined closest the source file take precedence.
To use this option please enable the Allow Local Override
package setting.
A .languagebabel
file may contain one or more of the following properties.
{
"babelMapsPath": "relPath",
"babelMapsAddUrl": true|false,
"babelSourcePath": "relPath",
"babelTranspilePath": "relPath",
"createMap": true|false,
"createTargetDirectories": true|false,
"createTranspiledCode": true|false,
"disableWhenNoBabelrcFileInPath": true|false,
"keepFileExtension": true|false,
"projectRoot": true|false,
"suppressSourcePathMessages": true|false,
"suppressTranspileOnSaveMessages": true|false,
"transpileOnSave": true|false
}
language-babel supports highlighting of GraphQL code within JavaScript files. For highlighting .graphql
and .gql
files see its sister grammar - language-graphql.
Inside JavaScript, GraphQL enclosed in back-ticks, a.k.a. Quasi or template strings are highlighted. Other GraphQL structures, notably types, are supported by the Flow component of this package.
Strings that have one of three prefixes/tags are parsed by the grammar to highlight the code enclosed.
Relay.QL`This is how Relay uses template strings`
graphql`This is how Relay will use template strings`
gql`This is how Apollo for GraphQL uses template strings`
/* GraphQL */`For cases where no template tag function is available`
An example of using the third method for highlighting code using /* GraphQL */
var { graphql, buildSchema } = require('graphql');
var schema = buildSchema(/* GraphQL */`
type Query {
hello: String
}
`);
Author: Gandm
Source Code: https://github.com/gandm/language-babel
License: MIT license
1662373500
A tool that tries to automatically update most dependencies, config files, and JavaScript files that require Babel packages directly to Babel 7 (and more in the future).
Requires nodejs 8 or newer
Run at the root of your git repo:
If using npm < v5.2.0, install npx globally.
# npx lets you run babel-upgrade without installing it locally
npx babel-upgrade --write
# or install globally and run
npm install babel-upgrade -g
babel-upgrade --write
Without the --write
(or -w
) flag, babel-upgrade
will print a diff without writing any changes.
Optionally, add --install
(or -i
) as well to run yarn
or npm
after writing the upgrade.
npx babel-upgrade --write --install
Ideas from http://new.babeljs.io/docs/en/next/v7-migration.html (or modify that file if it's missing)
--install
) (#18)package.json
: dependencies
and devDependencies
to the "latest supported" version.{
"devDependencies": {
+ "@babel/core": "^7.0.0",
+ "@babel/plugin-proposal-object-rest-spread": "^7.0.0",
+ "@babel/preset-env": "^7.0.0",
+ "babel-loader": "v8.0.0-beta.0"
- "babel-loader": "6.0.0",
- "babel-plugin-transform-object-rest-spread": "6.0.0",
- "babel-preset-env": "^1.0.0",
},
}
@babel/register
(e81cf7){
"name": "mocha-scripts-test",
"scripts": {
- "test": "mocha --compilers js:babel-register --require babel-polyfill test/*Test.js",
+ "test": "mocha --compilers js:@babel/register --require @babel/polyfill test/*Test.js",
}
}
"babel-core": "^7.0.0-bridge-0"
if jest or jest-cli is a dependency (#14)"devDependencies": {
"@babel/core": "^7.0.0",
+ "babel-core": "7.0.0-bridge.0",
"jest": "^22.0.0"
},
"scripts": {
"test": "jest"
}
@babel/node
package if babel-node
is used (#14)"devDependencies": {
"@babel/cli": "^7.0.0",
+ "@babel/node": "^7.0.0"
},
"scripts": {
"start": "babel-node a.js"
}
.babelrc
(#14)- src/
- example/
- .babelrc // now modifies these too
- test/
- .babelrc // now modifies these too
- `.babelrc`
{
"presets": [
+ "@babel/preset-env"
- "env"
]
}
package.json babel key
(d123ad){
"babel": {
"presets": [
+ "@babel/preset-env"
- "env"
]
}
}
env
(e9fc42){
"babel": {
"presets": [
"@babel/preset-env"
]
},
"env": {
"development": {
"plugins": [
- "transform-react-jsx-source",
- "babel-plugin-transform-react-jsx-self"
+ "@babel/plugin-transform-react-jsx-source",
+ "@babel/plugin-transform-react-jsx-self",
]
}
}
}
mocha.opts
(e81cf7)---require babel-register
+--require @babel/register
{
- "presets": "env, react",
+ "presets": ["@babel/preset-env", "@babel/preset-react"],
.flowconfig
and add it? (#21){
"@babel/preset-react": "^7.0.0",
+ "@babel/preset-flow": "^7.0.0"
}
{
- "presets": ["@babel/preset-stage-3"],
+ "presets": [],
+ "plugins": [
+ "@babel/plugin-syntax-dynamic-import",
+ "@babel/plugin-syntax-import-meta",
+ "@babel/plugin-proposal-class-properties",
+ "@babel/plugin-proposal-json-strings"
+ ]
}
{
- "@babel/preset-stage-3": "^7.0.0"
+ "@babel/plugin-proposal-class-properties": "^7.0.0",
+ "@babel/plugin-proposal-json-strings": "^7.0.0",
+ "@babel/plugin-syntax-dynamic-import": "^7.0.0",
+ "@babel/plugin-syntax-import-meta": "^7.0.0"
}
.babelrc.js
and other js files with a config like presets, webpack.config.js
only
/ignore
if necessarytypeof-symbol
if using @babel/preset-env
+ loosebabel-types
-> @babel/types
, babel-core
)babel-register
with @babel/register
)? Could be in a Makefile or somewhere else, but it's just find replace.@babel/cli
?npx/globally
npm install
npm start
Author: Babel
Source Code: https://github.com/babel/babel-upgrade
1662052500
faster.js is a Babel plugin that compiles idiomatic Javascript to faster, micro-optimized Javascript.
Setup Babel for your project if you haven't already. Then install faster.js:
npm install --save-dev faster.js
.babelrc
{
"plugins": ["faster.js"]
}
Babel CLI
babel-cli --plugins faster.js script.js
webpack.config.js (Webpack 4)
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
plugins: [require('faster.js')]
}
}
}]
}
faster.js rewrites common Array
method calls to faster code that does the same thing (usually - see When NOT to use faster.js). This results in performance boosts (especially on code that relies heavily on Array
methods) while maintaining code readability, but comes at the cost of a slightly larger bundle size. If having a small Javascript bundle size is much more important for you than performance is, you should not use faster.js.
Array
methodsfaster.js will rewrite the following Array
methods when possible:
.every()
.filter()
.forEach()
.map()
.reduce()
.reduceRight()
.some()
Try it yourself: https://fasterjs-demo.victorzhou.com
Demo Github repo: https://github.com/vzhou842/faster.js-demo
faster.js makes two critical assumptions that MUST be true about your codebase:
Code compiled with faster.js may produce incorrect results when run on sparse arrays.
faster.js assumes any restricted method call is done on a native Javascript array. Any new classes you write should not include methods with restricted names.
Restricted method names are the names of methods that faster.js will attempt to rewrite - see Supported Array
methods.
// OK
const a = [1, 2, 3].map(e => 2 * e);
// BAD
class Foo {
constructor(map) {
this._map = map;
}
map() {
return this._map;
}
}
const f = new Foo({});
const map = f.map(); // .map() is a restricted method
faster.js exploits the fact that native Javascript Array
methods are slowed down by having to support seldom-used edge cases like sparse arrays. Assuming no sparse arrays, there are often simple ways to rewrite common Array
methods to improve performance.
// Original code
const arr = [1, 2, 3];
const results = arr.map(e => 2 * e);
roughly compiles to
// Compiled with faster.js
const arr = [1, 2, 3];
const results = new Array(arr.length);
const _f = (e => 2 * e);
for (let _i = 0; _i < arr.length; _i++) {
results[_i] = _f(arr[_i], _i, arr);
}
$ npm run bench
array-every large
β native x 2,255,548 ops/sec Β±0.46% (57 runs sampled)
β faster.js x 10,786,892 ops/sec Β±1.25% (56 runs sampled)
faster.js is 378.2% faster (0.351ΞΌs) than native
array-filter large
β native x 169,237 ops/sec Β±1.42% (55 runs sampled)
β faster.js x 1,110,629 ops/sec Β±1.10% (59 runs sampled)
faster.js is 556.3% faster (5.008ΞΌs) than native
array-forEach large
β native x 61,097 ops/sec Β±3.66% (43 runs sampled)
β faster.js x 200,459 ops/sec Β±0.52% (55 runs sampled)
faster.js is 228.1% faster (11.379ΞΌs) than native
array-map large
β native x 179,800 ops/sec Β±1.00% (58 runs sampled)
β faster.js x 1,706,593 ops/sec Β±0.25% (56 runs sampled)
faster.js is 849.2% faster (4.976ΞΌs) than native
array-reduce large
β native x 200,425 ops/sec Β±1.01% (55 runs sampled)
β faster.js x 1,694,350 ops/sec Β±1.52% (55 runs sampled)
faster.js is 745.4% faster (4.399ΞΌs) than native
array-reduceRight large
β native x 49,784 ops/sec Β±0.38% (58 runs sampled)
β faster.js x 1,756,352 ops/sec Β±0.99% (59 runs sampled)
faster.js is 3428.0% faster (19.517ΞΌs) than native
array-some large
β native x 2,968,367 ops/sec Β±0.56% (56 runs sampled)
β faster.js x 11,591,773 ops/sec Β±1.29% (54 runs sampled)
faster.js is 290.5% faster (0.251ΞΌs) than native
The benchmark example above was run on Node 8. Later versions of Node include improvements / optimizations that may make some features in faster.js obsolete. View full benchmark examples here: Node 8, Node 10, Node 12.
Sparse arrays are arrays that contain holes or empty slots.
const sparse1 = [0, , 1]; // a sparse array literal
console.log(sparse1.length); // 3
const sparse2 = [];
sparse2[5] = 0; // sparse2 is now a sparse array
console.log(sparse2.length); // 6
It is generally recommended to avoid using sparse arrays.
Read the blog post on faster.js!
Author: vzhou842
Source Code: https://github.com/vzhou842/faster.js
License: MIT license
1661951341
A Babel plugin to add a new resolver for your modules when compiling your code using Babel. This plugin allows you to add new "root" directories that contain your modules. It also allows you to setup a custom alias for directories, specific files, or even other npm modules.
This plugin can simplify the require/import paths in your project. For example, instead of using complex relative paths like ../../../../utils/my-utils
, you can write utils/my-utils
. It will allow you to work faster since you won't need to calculate how many levels of directory you have to go up before accessing the file.
// Use this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of that:
import MyUtilFn from '../../../../utils/MyUtilFn';
// And it also work with require calls
// Use this:
const MyUtilFn = require('utils/MyUtilFn');
// Instead of that:
const MyUtilFn = require('../../../../utils/MyUtilFn');
Install the plugin
npm install --save-dev babel-plugin-module-resolver
or
yarn add --dev babel-plugin-module-resolver
Specify the plugin in your .babelrc
with the custom root or alias. Here's an example:
{
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"test": "./test",
"underscore": "lodash"
}
}]
]
}
.babelrc.js version Specify the plugin in your .babelrc.js
file with the custom root or alias. Here's an example:
const plugins = [
[
require.resolve('babel-plugin-module-resolver'),
{
root: ["./src/"],
alias: {
"test": "./test"
}
}
]
];
Good example: // https://gist.github.com/nodkz/41e189ff22325a27fe6a5ca81df2cb91
babel-plugin-module-resolver can be configured and controlled easily, check the documentation for more details
Are you a plugin author (e.g. IDE integration)? We have documented the exposed functions for use in your plugins!
If you're using ESLint, you should use eslint-plugin-import, and eslint-import-resolver-babel-module to remove falsy unresolved modules. If you want to have warnings when aliased modules are being imported by their relative paths, you can use eslint-plugin-module-resolver.
babel-plugin-module-resolver
option.jsconfig.json
(tsconfig.json
for TypeScript), e.g.:{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"test/*": ["test/*"],
"underscore": ["lodash"]
}
}
}
../../../utils/MyUtilFn
you can mark ../../../utils
as "resources root". This has the problem that your alias also has to be named utils
. The second option is to add a webpack.config.js
to your project and use it under File->Settings->Languages&Frameworks->JavaScript->Webpack. This will trick webstorm into resolving the paths and you can use any alias you want e.g.:var path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.json', '.vue'],
alias: {
utils: path.resolve(__dirname, '../../../utils/MyUtilFn'),
},
},
};
Are you also using it? Send a PR!
Author: Tleunen
Source Code: https://github.com/tleunen/babel-plugin-module-resolver
License: MIT license
1661871540
A simple transform to cherry-pick Lodash modules so you donβt have to.
Combine with lodash-webpack-plugin for even smaller cherry-picked builds!
$ npm i --save lodash
$ npm i --save-dev babel-plugin-lodash @babel/cli @babel/preset-env
Transforms
import _ from 'lodash'
import { add } from 'lodash/fp'
const addOne = add(1)
_.map([1, 2, 3], addOne)
roughly to
import _add from 'lodash/fp/add'
import _map from 'lodash/map'
const addOne = _add(1)
_map([1, 2, 3], addOne)
.babelrc
{
"plugins": ["lodash"],
"presets": [["@babel/env", { "targets": { "node": 6 } }]]
}
Set plugin options using an array of [pluginName, optionsObject]
.
{
"plugins": [["lodash", { "id": "lodash-compat", "cwd": "some/path" }]],
"presets": [["@babel/env", { "targets": { "node": 6 } }]]
}
The options.id
can be an array of ids.
{
"plugins": [["lodash", { "id": ["async", "lodash-bound"] }]],
"presets": [["@babel/env", { "targets": { "node": 6 } }]]
}
Babel CLI
$ babel --plugins lodash --presets @babel/es2015 script.js
Babel API
require('babel-core').transform('code', {
'plugins': ['lodash'],
'presets': [['@babel/env', { 'targets': { 'node': 6 } }]]
})
webpack.config.js
'module': {
'loaders': [{
'loader': 'babel-loader',
'test': /\.js$/,
'exclude': /node_modules/,
'query': {
'plugins': ['lodash'],
'presets': [['@babel/env', { 'targets': { 'node': 6 } }]]
}
}]
}
Can this plugin produce ES2015 imports rather than CommonJS imports?
This plugin produces ES2015 imports by default. The @babel/plugin-transform-modules-commonjs
plugin, which is included in the @babel/preset-es2015
preset, transforms ES2015 import
statements to CommonJS. Omit it from your preset to preserve ES2015 style imports.
Author: lodash
Source Code: https://github.com/lodash/babel-plugin-lodash
License: View license
1659777900
Paste or drop code into the editor and inspect the generated AST on https://astexplorer.net/
The AST explorer provides following code parsers:
Depending on the parser settings, it not only supports ES5/CSS3 but also
Since future syntax is supported, the AST explorer is a useful tool for developers who want to create AST transforms. In fact, following transformers are included so you can prototype your own plugins:
$node
in the console to refer to the last opened/toggled AST node.I'm happy about any feedback, feature request or PR to make this tool as useful as possible!
website/
.yarn add theParser
(or npm install -S theParser
)src/parsers/{language}
.loadParser
).parse
.nodeToRange
method (this is for highlighting).getNodeName
method (this is for quick look through the tree).opensByDefault
method for auto-expansion of specific properties._ignoredProperties
set or implement forEachProperty
generator method for filtering.renderSettings
method if applicable.website/
.src/parsers/{language}/transformers
.defaultParserID
.loadTransformer
).transform
.codeExample.txt
.website/
.yarn install
(you can run npm install
as well).Run yarn run build
for the final minimized version. Run yarn run watch
for incremental builds.
Run yarn start
to start a simple static webserver.
Author: fkling
Source Code: https://github.com/fkling/astexplorer
License: MIT license
1658569140
Babel preset with all plugins for Electron.
$ npm install --save-dev babel-preset-electron@37.8
.babelrc
(Recommended).babelrc
{
"presets": ["electron"]
}
$ babel script.js --preset electron
require("babel-core").transform("code", {
presets: ["electron"]
});
Author: Emorikawa
Source Code: https://github.com/emorikawa/babel-preset-electron
License: MIT license
1658197680
SWC (stands for Speedy Web Compiler
) is a super-fast TypeScript / JavaScript compiler written in Rust. It's a library for Rust and JavaScript at the same time. If you are using SWC from Rust, see rustdoc and for most users, your entry point for using the library will be parser.
Also, SWC tries to ensure that
If you select the latest version of each crates, it will work
for rust users. Without such guarantee, using SWC would be too hard as SWC is a large, modular project and typically you have to use many modules.
Getting Started
The easiest way to try SWC is using the Playground.
Otherwise, run the following to download pre-built binaries:
npm i -D @swc/cli @swc/core
Then, you can transpile your first file and emit to stdout
:
npx swc ./file.js
SWC can be downloaded and used as a pre-built binary, or built from source. Currently, the following binaries are provided:
@swc/core-linux-musl
)Check out the documentation in the website.
Features
Please see comparison with babel.
Performance
Please see benchmark results on the website.
If you are using SWC from JavaScript, please refer to docs on the website.
SWC is a community-driven project, and is maintained by a group of volunteers. If you'd like to help support the future of the project, please consider:
See CONTRIBUTING.md. You may also find the architecture documentation useful (ARCHITECTURE.md).
Author: swc-project
Source Code: https://github.com/swc-project/swc
License: Apache-2.0 license
1657107060
Serverless plugin for zero-config Typescript support
export
, import
, async
, await
, Promise
, ...)sls package
, sls deploy
and sls deploy function
sls invoke local
+ --watch
modeserverless-offline
yarn add --dev serverless-plugin-typescript typescript
# or
npm install -D serverless-plugin-typescript typescript
Add the following plugin to your serverless.yml
:
plugins:
- serverless-plugin-typescript
See example folder for a minimal example.
tsconfig.json
The default tsconfig.json
file used by the plugin looks like this:
{
"compilerOptions": {
"preserveConstEnums": true,
"strictNullChecks": true,
"sourceMap": true,
"allowJs": true,
"target": "es5",
"outDir": ".build",
"moduleResolution": "node",
"lib": ["es2015"],
"rootDir": "./"
}
}
Note 1: The
outDir
androotDir
options cannot be overwritten.
Note 2: Don't confuse the
tsconfig.json
in this repository with the one mentioned above.
All files from package/include
will be included in the final build file. See Exclude/Include
Override what tsconfig.json to use with the following snippet in your severless.yaml
custom:
serverlessPluginTypescript:
tsConfigFileLocation: './tsconfig.build.json'
When using with Google Cloud Functions via the serverless-google-cloudfunctions plugin, you simply have to provide a main
field in your package.json
:
{
// ...
"main": "handler.js",
// ..
}
And this plugin will automatically compile your typescript correctly. Note that the field must refer to the compiled file name, namely, ending with a .js
extension.
If a main
field was not found, then this plugin will use index.js
. Before compilation begins, it will check to see that the file indicated exists with a .ts
extension before actually trying to compile it.
The normal Serverless deploy procedure will automatically compile with Typescript:
serverless create -t aws-nodejs
serverless deploy
The plugin integrates very well with serverless-offline to simulate AWS Lambda and AWS API Gateway locally.
Add the plugins to your serverless.yml
file and make sure that serverless-plugin-typescript
precedes serverless-offline
as the order is important:
plugins:
...
- serverless-plugin-typescript
...
- serverless-offline
...
Run serverless offline
or serverless offline start
to start the Lambda/API simulation.
In comparison to serverless offline
, the start
command will fire an init
and a end
lifecycle hook which is needed for serverless-offline
and e.g. serverless-dynamodb-local
to switch off resources (see below)
Configure your service the same as mentioned above, but additionally add the serverless-dynamodb-local
plugin as follows:
plugins:
- serverless-plugin-typescript
- serverless-dynamodb-local
- serverless-offline
Run serverless offline start
.
You can reduce the clutter generated by serverless-offline
with --dontPrintOutput
and disable timeouts with --noTimeout
.
To run your compiled functions locally you can:
$ serverless invoke local --function <function-name>
Options are:
--function
or -f
(required) is the name of the function to run--watch
- recompile and run a function locally on source changes--path
or -p
(optional) path to JSON or YAML file holding input data--data
or -d
(optional) input dataYou can easily enable support for source-maps (making stacktraces easier to read) by installing and using the following plugin:
yarn add --dev source-map-support
// inside of your function
import 'source-map-support/register'
If you are using webpack (most likely). Add devtool: 'source-map'
to webpack.config.js
:
module.exports = {
.... snip ....
devtool: 'source-map',
.... snip ....
}
Originally developed by Prisma Labs, now maintained in scope of Serverless, Inc
Author: Serverless
Source Code: https://github.com/serverless/serverless-plugin-typescript
License: MIT license
1653910680
babel-jest-assertions
πβοΈ
Adds expect.assertions(n) and expect.hasAssertions to all tests automatically
Ever wondered if your tests are actually running their assertions, especially in asynchronous tests? Jest has two features built in to help with this: expect.assertions(number)
and expect.hasAssertions()
. These can be useful when doing something like:
it('resolves to one', () => {
Promise.reject(1).then(value => expect(value).toBe(1));
});
The issue here is the catch
case is not dealt with in this test, which is fine as we are testing the happy path, but this test will currently pass even though the Promise
rejects and the assertion is never ran.
One solution is to manually adjust the above test to include expect.assertions(number)
and expect.hasAssertions()
this is quite verbose and prone to human error.
An alternative is a babel plugin to automate adding these additional properties, and this is such plugin π
With npm:
npm install --save-dev babel-jest-assertions
With yarn:
yarn add -D babel-jest-assertions
{
"plugins": ["babel-jest-assertions"]
}
babel --plugins babel-jest-assertions script.js
require('babel-core').transform('code', {
plugins: ['babel-jest-assertions'],
})
Simply write your tests as you would normally and this plugin will add the verification of assertions in the background.
One assertion
it('resolves to one', () => {
Promise.reject(1).then(value => expect(value).toBe(1));
});
β β β β β β
it('resolves to one', () => {
expect.hasAssertions();
expect.assertions(1);
Promise.reject(1).then(value => expect(value).toBe(1));
});
Note: this test will now fail π
Multiple assertions
it('counts multiple assertions too', () => {
expect(1 + 0).toBe(1);
expect(0 + 1).toBe(1);
});
β β β β β β
it('counts multiple assertions too', () => {
expect.hasAssertions();
expect.assertions(2);
expect(1 + 0).toBe(1);
expect(0 + 1).toBe(1);
});
Asynchronous assertions
it('counts multiple assertions too', async () => {
const res = await fetch('www.example.com');
expect(res.json).toBeTruthy();
const json = await res.json();
expect(json).toEqual({ whatever: 'trevor' });
});
β β β β β β
it('counts multiple assertions too', async () => {
expect.hasAssertions();
expect.assertions(2);
const res = await fetch('www.example.com');
expect(res.json).toBeTruthy();
const json = await res.json();
expect(json).toEqual({ whatever: 'trevor' });
});
beforeEach and afterEach blocks
If you have expectations inside either of beforeEach
or afterEach
blocks for your test then these expects will be included in the count - even if you have nested describe blocks each with their own beforeEach
/afterEach
the count will accumulate.
beforeEach(() => {
expect(true).toBe(true);
});
afterEach(() => {
expect(true).toBe(true);
});
describe('.add', () => {
beforeEach(() => {
expect(true).toBe(true);
});
afterEach(() => {
expect(true).toBe(true);
});
it('returns 1 when given 0 and 1', () => {
expect(add(1, 0)).toEqual(1);
});
describe('.add2', () => {
beforeEach(() => {
expect(true).toBe(true);
});
afterEach(() => {
expect(true).toBe(true);
});
it('returns 1 when given 0 and 1', () => {
expect(add2(1, 0)).toEqual(1);
});
});
});
β β β β β β
beforeEach(() => {
expect(true).toBe(true);
});
afterEach(() => {
expect(true).toBe(true);
});
describe('.add', () => {
beforeEach(() => {
expect(true).toBe(true);
});
afterEach(() => {
expect(true).toBe(true);
});
it('returns 1 when given 0 and 1', () => {
expect.assertions(5);
expect.hasAssertions();
expect(add2(1, 0)).toEqual(1);
});
describe('.add2', () => {
beforeEach(() => {
expect(true).toBe(true);
});
afterEach(() => {
expect(true).toBe(true);
});
it('returns 1 when given 0 and 1', () => {
expect.assertions(7);
expect.hasAssertions();
expect(add2(1, 0)).toEqual(1);
});
});
});
Comments are ignored
it('ignores commented-out assertions', async () => {
const res = await fetch('www.example.com');
// expect(res.json).toBeTruthy();
const json = await res.json();
/*
expect(json).toEqual({ whatever: 'trevor1' });
*/
expect(json).toEqual({ whatever: 'trevor' });
/* expect(json).toEqual({ whatever: 'trevor2' }); */
});
β β β β β β
it('counts multiple assertions too', async () => {
expect.hasAssertions();
expect.assertions(1);
const res = await fetch('www.example.com');
// expect(res.json).toBeTruthy();
const json = await res.json();
/*
expect(json).toEqual({ whatever: 'trevor1' });
*/
expect(json).toEqual({ whatever: 'trevor' });
/* expect(json).toEqual({ whatever: 'trevor2' }); */
});
If you add either expect.assertions(number)
or expect.hasAssertions()
then your defaults will be favoured and the plugin will skip the test.
it('will leave test as override supplied', () => {
expect.hasAssertions();
expect.assertions(1);
if (true) {
expect(true).toBe(true);
}
if (false) {
expect(false).toBe(false);
}
});
β β β β β β
it('will leave test as override supplied', () => {
expect.hasAssertions();
expect.assertions(1);
if (true) {
expect(true).toBe(true);
}
if (false) {
expect(false).toBe(false);
}
});
Author: Mattphillips
Source Code: https://github.com/mattphillips/babel-jest-assertions
License: MIT license
1653699660
Voice Activated Lamp with Johnny-Five
An example of HTML5 Speech Recognition used to control a lamp using Socket.io and Johnny-Five.
This was merely a small experiment of making a small lamp with Johnny-Five but also using speech recognition for control. With this, we can have a web app using Speech Recognition for commands that are then sent to our server, which will then check and change the robot's state, the robot being our lamp.
It's also worth noting this is just a prototype project. It's nothing production ready and was made for fun, but also for practicing JS stacks and organisation.
Don't worry β you can find instructions and a circuit here for making the circuit for the lamp. Included in the file are a list of components and also a detailed guide for first-timers.
Clone this repository and then use npm
or yarn
to install the project's dependencies. In this README, I will be using Yarn (as it's super powerful) but any commands here can be used with npm
as well. Your choice.
yarn install
To run the project as is, then simply run the build
command and then run start
to get the project going.
yarn build
yarn start
If you wish to use this for development purposes and even extend it, it's best to use dev-start
and dev-server
. dev-start
is to run Nodemon to watch our files and update on the fly while running a web server. dev-start
initiates a Webpack Server to watch for changes on the client files and update them.
yarn dev-start
yarn dev-server
dev-start
: Starts the Express Server and uses Nodemon to watch for changesdev-server
: Begins a Webpack Development Server to rebundle your scripts.build
: Compile all the code for production.start
: Start the production copy of the server.test
: Check and test the code.Author: IainIsCreative
Source Code: https://github.com/IainIsCreative/johnny-five-speech-recognition-lamp
License: