1671670800
In this Ethers.js article we will Learn about Simple Ethers.js Usage Example for Beginners. Although outlined code snippets are great when developing, having access to a proper ethers.js tutorial that instructs novice developers and serves as a reminder for experienced ones can take any development project to the next level. Moving forward, we will not only outline code snippets but also provide step-by-step instructions on how to get started with ethers.js, and we’ll do so with the help of a simple ethers.js example. That said, aside from exploring ethers.js examples, you can also use Web3.js as an alternative. However, in the last two years (or so), most dapp (decentralized application) developers have been more inclined toward ethers.js. Why? For example, it’s easier to listen to the blockchain with ethers.js, which we’ll look closer at in this tutorial!
We will first ensure you can answer the “what is ethers.js?” question. This is where you’ll also learn about the core features of this practical JS tool. Then, we’ll examine the main benefits of using ethers.js. With the basics under our belt, we’ll take you through our ethers.js tutorial. By following our lead, you’ll be able to create your ethers.js example script and learn how to use ethers.js.
However, you should keep in mind that there’s an even smoother solution for listening to on-chain events – Moralis’ Streams API. Thus, we’ll redo the same ethers.js example but use the Streams API instead. We’ll also point out some key advantages of this next-level solution. Nonetheless, you’ll even learn how to use a neat UI to go beyond ethers.js examples. As such, create your free Moralis account, which is all you need to start using Moralis Streams.
Just like Web3.js, ethers.js is a Web3 JavaScript library. Since its release in 2016, this tool for blockchain interaction has experienced impressive adoption. Everyone who has ever used this JS library can thank Richard Moore, the man behind ethers.js. It is safe to say that ethers.js is the most popular open-source Ethereum JS library. It features millions of downloads and has surpassed Web3.js in daily downloads by more than 60% in 2022
For more information, read our Web3.js vs ethers.js comparison.
If you know a thing or two about any conventional programming library, you won’t be surprised to hear that ethers.js consists of a collection of prewritten code snippets. The latter can be used to perform many recurring functions and, thus, avoid reinventing the wheel. Of course, ethers.js’ functionalities focus on Web3 via Ethereum (ETH) and other EVM-compatible blockchains. As such, this ETH JS library enables you to communicate easily and interact with decentralized networks. Over time, ethers.js has expanded and become quite a general-purpose library for Web3 development. Furthermore, it’s been successful at fulfilling its goals of being a complete and compact solution for developers looking to interact with the Ethereum chain.
Because this JS library offers many features, this results in countless ethers.j examples. However, when listening to blockchain events, ethers.js’ option to connect to Ethereum nodes using JSON-RPC, Etherscan, MetaMask, Infura, Alchemy, or Cloudflare is the key. However, this also means you have to worry about one of these node providers. We’ll explain how to avoid that later on, but for now, let’s focus on ethers.js features.
Aside from enabling you to connect to Ethereum node providers, ethers.js maintains many other features, which enables you to cover the following aspects:
Ethers.js features a small bundle size, extensive and straightforward documentation, and a user-friendly API structure. Furthermore, it is intuitive and straightforward to use. Also, aside from JavaScript, ethers.js supports TypeScript (TS). All these benefits, combined with the above-listed features, make ethers.js a highly attractive library for many Web3 developers.
Let’s look at a sum of ethers.js’ main benefits:
Aside from these ethers.js-specific benefits, learning how to use ethers.js brings some universal advantages. After all, blockchain is here to stay and poised to radically change how the world operates. Thus, you may use this ethers.js tutorial, knowing that it’s helping you learn to become part of that solution.
Moreover, some of the most common ethers.js examples revolve around creating whale alerts, building automated bots, monitoring NFT collections, Web3 game notifications, etc. Ultimately, when listening to on-chain events either with ethers.js or other reliable tools, your main objective is to execute actions automatically as a response to specific on-chain events occurring. So, your goal must be to choose a tool that will enable you to do that effectively and efficiently.
It’s time we show you how to use ether.js by tackling our ethers.js tutorial. To make things as convenient for you as possible, you can use our ethers.js example script (“index.js”) found below. However, let’s still guide you through the code. So, in the top line, you must first ensure that your NodeJS file uses ethers.js. Then, you must import the application binary interface (ABI), which is specific to every smart contract. That said, the “getTransfer” async function deserves your main attention. After all, the latter takes care of listening to the blockchain.
Using our ethers.js example script, you’ll focus on the USDC contract address. Of course, you could convert it to other ethers.js examples by using other contract addresses. Furthermore, the “getTransfer” function below relies on the ethers.js library’s “WebSocketProvider” endpoint. By using this endpoint, you can define the node provider you want to use. To make that work, you must also obtain that provider’s key, which is an important aspect of how to use ethers.js. The example code below focuses on Alchemy. However, you should use a node provider that supports the chain(s) you want to focus on.
Aside from a contract address and provider, the “getTransfer” function also accepts an ABI. Last but not least, you also need to set up a “transfer” listener. The latter will also console-log the relevant on-chain details.
Below is our example script that is the core of today’s ethers.js tutorial. So, make sure to copy the entire script and test it:
const ethers = require("ethers");
const ABI = require("./abi.json");
require("dotenv").config();
async function getTransfer(){
const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; ///USDC Contract
const provider = new ethers.providers.WebSocketProvider(
`wss://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}`
);
const contract = new ethers.Contract(usdcAddress, ABI, provider);
contract.on("Transfer", (from, to, value, event)=>{
let transferEvent ={
from: from,
to: to,
value: value,
eventData: event,
}
console.log(JSON.stringify(transferEvent, null, 4))
})
}
getTransfer()
Once you have the above lines of code in place, you can run the script using the following command:
node index.js
In response, you should see the results in your terminal:
There are countless ethers.js examples that we could focus on; however, the above ethers.js tutorial provides you with more than enough to get going. Moreover, looking at the results of the above script, you can see that ethers.js provides you with quite a lot of details. Unfortunately, however, these details come in the form of un-parsed data. This is one of the main reasons why instead of learning how to use ethers.js, many devs focus on utilizing Moralis’ Streams API.
Above, you were able to see ethers.js in action, and if you took our example script for a spin, you even saw firsthand that ethers.js obtains real-time events. Consequently, it would be wrong to call this ETH JS library anything less than a very decent open-source solution for listening to the blockchain. Yet, ethers.js comes with some limitations. Trying to overcome these limitations as you go about developing your dapps can be quite costly. Hence, the above ethers.js tutorial wouldn’t be complete without pointing out the main ethers.js’ limitations:
On the other hand, the Moralis Streams API covers all those aspects. This makes it the ultimate solution for streaming blockchain data. That said, you can find a more detailed ethers.js vs Web3 streams comparison on our blog; however, the following image shows the gist of it:
With that said, let’s tackle the above ethers.js tutorial with Moralis Streams.
The goal of this subsection is to obtain the same on-chain data as above – any USDC transfer on Ethereum. However, instead of using ether.js, Moralis’ Streams API will be our tool. If you want to follow our lead, create another “index.js” file and make sure to import Moralis and its utils at the top:
const Moralis = require("moralis").default;
const Chains = require("@moralisweb3/common-evm-utils");
const EvmChain = Chains.EvmChain;
const ABI = require("./abi.json");
require("dotenv").config();
const options = {
chains: [EvmChain.ETHEREUM],
description: "USDC Transfers 100k",
tag: "usdcTransfers100k",
includeContractLogs: true,
abi: ABI,
topic0: ["Transfer(address,address,uint256)"],
webhookUrl: "https://22be-2001-2003-f58b-b400-f167-f427-d7a8-f84e.ngrok.io/webhook",
advancedOptions: [
{
topic0: "Transfer(address,address,uint256)",
filter: {
gt : ["value", "100000"+"".padEnd(6,"0")]
}
}
]
};
Moralis.start({
apiKey: process.env.MORALIS_KEY ,
}).then(async () => {
const stream = await Moralis.Streams.add(options);
const { id } = stream.toJSON();
await Moralis.Streams.addAddress({
id: id,
address: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"]
})
});
Looking at the lines of code above, you can see that the script focuses on the same ABI and the same contract address. The script also covers the options that the Streams API provides. This is also where we used “ETHEREUM” to focus on that chain. However, since Moralis is all about cross-chain interoperability, we could easily target any other chain or multiple chains simultaneously.
Furthermore, the above script also initiates Moralis using your Moralis Web3 API key. Fortunately, anyone with a free Moralis account gets to obtain that key in two steps:
Among the bottom lines of the above code, you can see the “addAddress” endpoint. The latter enables you to add multiple addresses and listen to them simultaneously. To see that option in action, make sure to use the video below. This is also the place to learn how to create and manage streams using a neat UI.
Ultimately, when using Moralis’ Streams API, we receive parsed data. Also, not only do we receive transactions hashes and from and to addresses, but we also receive transfer values:
The video tutorial below also demonstrated how to use the filtering feature of this powerful “ethers.js 2.0” tool.
In today’s article, you had an opportunity to learn all you need to know about ethers.js – the leading ETH JavaScript library. As such, you now know the core features and main benefits of using this library. You also had a chance to follow our ethers.js tutorial to take this JS library for a spin. Also, you learned that despite ethers.js’s great power, it has several limitations. However, you also learned that you could bridge these limitations using Moralis’ Streams API. In fact, you were able to follow our lead and redo the ethers.js tutorial but using Moralis Streams instead. Last but not least, following a detailed video tutorial, you had an opportunity to see how filtering works, how you can listen to multiple addresses, and how to use the Moralis Streams UI.
Following the trends and devs’ preferences, it’s safe to say that the Streams API is the tool of the future. Thus, make sure to learn how to work with it properly by visiting the Streams API documentation page. This is also the place to find quick-start tutorials and many examples. By exploring other pages of the Moralis docs, you can master all of Moralis’ tools. By doing so, you’ll be a confident dapp developer with your legacy skills.
Furthermore, remember to explore other blockchain development topics covered on the Moralis YouTube channel and the Moralis blog. Some of the latest articles explain how to get all tokens owned by a wallet, what ERC 1155 NFTs are, and what the Sepolia testnet is. In addition, if you’d like to understand Web3 storage, make sure to read our articles explaining how Web3 data storage works, what web3.storage is, how to use metadata for NFT storage, using IPFS for NFT metadata, and why developers should opt for the market’s leading Web3 provider when wanting to upload files to IPFS. You can also take a more professional approach to your crypto education – enroll in Moralis Academy and master blockchain and Bitcoin fundamentals.
Original article sourced at: https://moralis.io
#Ethers.js
1677668905
Mocking library for TypeScript inspired by http://mockito.org/
mock
) (also abstract classes) #examplespy
) #examplewhen
) via:verify
)reset
, resetCalls
) #example, #examplecapture
) #example'Expected "convertNumberToString(strictEqual(3))" to be called 2 time(s). But has been called 1 time(s).'
)npm install ts-mockito --save-dev
// Creating mock
let mockedFoo:Foo = mock(Foo);
// Getting instance from mock
let foo:Foo = instance(mockedFoo);
// Using instance in source code
foo.getBar(3);
foo.getBar(5);
// Explicit, readable verification
verify(mockedFoo.getBar(3)).called();
verify(mockedFoo.getBar(anything())).called();
// Creating mock
let mockedFoo:Foo = mock(Foo);
// stub method before execution
when(mockedFoo.getBar(3)).thenReturn('three');
// Getting instance
let foo:Foo = instance(mockedFoo);
// prints three
console.log(foo.getBar(3));
// prints null, because "getBar(999)" was not stubbed
console.log(foo.getBar(999));
// Creating mock
let mockedFoo:Foo = mock(Foo);
// stub getter before execution
when(mockedFoo.sampleGetter).thenReturn('three');
// Getting instance
let foo:Foo = instance(mockedFoo);
// prints three
console.log(foo.sampleGetter);
Syntax is the same as with getter values.
Please note, that stubbing properties that don't have getters only works if Proxy object is available (ES6).
// Creating mock
let mockedFoo:Foo = mock(Foo);
// Getting instance
let foo:Foo = instance(mockedFoo);
// Some calls
foo.getBar(1);
foo.getBar(2);
foo.getBar(2);
foo.getBar(3);
// Call count verification
verify(mockedFoo.getBar(1)).once(); // was called with arg === 1 only once
verify(mockedFoo.getBar(2)).twice(); // was called with arg === 2 exactly two times
verify(mockedFoo.getBar(between(2, 3))).thrice(); // was called with arg between 2-3 exactly three times
verify(mockedFoo.getBar(anyNumber()).times(4); // was called with any number arg exactly four times
verify(mockedFoo.getBar(2)).atLeast(2); // was called with arg === 2 min two times
verify(mockedFoo.getBar(anything())).atMost(4); // was called with any argument max four times
verify(mockedFoo.getBar(4)).never(); // was never called with arg === 4
// Creating mock
let mockedFoo:Foo = mock(Foo);
let mockedBar:Bar = mock(Bar);
// Getting instance
let foo:Foo = instance(mockedFoo);
let bar:Bar = instance(mockedBar);
// Some calls
foo.getBar(1);
bar.getFoo(2);
// Call order verification
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(2)); // foo.getBar(1) has been called before bar.getFoo(2)
verify(mockedBar.getFoo(2)).calledAfter(mockedFoo.getBar(1)); // bar.getFoo(2) has been called before foo.getBar(1)
verify(mockedFoo.getBar(1)).calledBefore(mockedBar.getFoo(999999)); // throws error (mockedBar.getFoo(999999) has never been called)
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(10)).thenThrow(new Error('fatal error'));
let foo:Foo = instance(mockedFoo);
try {
foo.getBar(10);
} catch (error:Error) {
console.log(error.message); // 'fatal error'
}
You can also stub method with your own implementation
let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);
when(mockedFoo.sumTwoNumbers(anyNumber(), anyNumber())).thenCall((arg1:number, arg2:number) => {
return arg1 * arg2;
});
// prints '50' because we've changed sum method implementation to multiply!
console.log(foo.sumTwoNumbers(5, 10));
You can also stub method to resolve / reject promise
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.fetchData("a")).thenResolve({id: "a", value: "Hello world"});
when(mockedFoo.fetchData("b")).thenReject(new Error("b does not exist"));
You can reset just mock call counter
// Creating mock
let mockedFoo:Foo = mock(Foo);
// Getting instance
let foo:Foo = instance(mockedFoo);
// Some calls
foo.getBar(1);
foo.getBar(1);
verify(mockedFoo.getBar(1)).twice(); // getBar with arg "1" has been called twice
// Reset mock
resetCalls(mockedFoo);
// Call count verification
verify(mockedFoo.getBar(1)).never(); // has never been called after reset
You can also reset calls of multiple mocks at once resetCalls(firstMock, secondMock, thirdMock)
Or reset mock call counter with all stubs
// Creating mock
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn("one").
// Getting instance
let foo:Foo = instance(mockedFoo);
// Some calls
console.log(foo.getBar(1)); // "one" - as defined in stub
console.log(foo.getBar(1)); // "one" - as defined in stub
verify(mockedFoo.getBar(1)).twice(); // getBar with arg "1" has been called twice
// Reset mock
reset(mockedFoo);
// Call count verification
verify(mockedFoo.getBar(1)).never(); // has never been called after reset
console.log(foo.getBar(1)); // null - previously added stub has been removed
You can also reset multiple mocks at once reset(firstMock, secondMock, thirdMock)
let mockedFoo:Foo = mock(Foo);
let foo:Foo = instance(mockedFoo);
// Call method
foo.sumTwoNumbers(1, 2);
// Check first arg captor values
const [firstArg, secondArg] = capture(mockedFoo.sumTwoNumbers).last();
console.log(firstArg); // prints 1
console.log(secondArg); // prints 2
You can also get other calls using first()
, second()
, byCallIndex(3)
and more...
You can set multiple returning values for same matching values
const mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(anyNumber())).thenReturn('one').thenReturn('two').thenReturn('three');
const foo:Foo = instance(mockedFoo);
console.log(foo.getBar(1)); // one
console.log(foo.getBar(1)); // two
console.log(foo.getBar(1)); // three
console.log(foo.getBar(1)); // three - last defined behavior will be repeated infinitely
Another example with specific values
let mockedFoo:Foo = mock(Foo);
when(mockedFoo.getBar(1)).thenReturn('one').thenReturn('another one');
when(mockedFoo.getBar(2)).thenReturn('two');
let foo:Foo = instance(mockedFoo);
console.log(foo.getBar(1)); // one
console.log(foo.getBar(2)); // two
console.log(foo.getBar(1)); // another one
console.log(foo.getBar(1)); // another one - this is last defined behavior for arg '1' so it will be repeated
console.log(foo.getBar(2)); // two
console.log(foo.getBar(2)); // two - this is last defined behavior for arg '2' so it will be repeated
Short notation:
const mockedFoo:Foo = mock(Foo);
// You can specify return values as multiple thenReturn args
when(mockedFoo.getBar(anyNumber())).thenReturn('one', 'two', 'three');
const foo:Foo = instance(mockedFoo);
console.log(foo.getBar(1)); // one
console.log(foo.getBar(1)); // two
console.log(foo.getBar(1)); // three
console.log(foo.getBar(1)); // three - last defined behavior will be repeated infinity
Possible errors:
const mockedFoo:Foo = mock(Foo);
// When multiple matchers, matches same result:
when(mockedFoo.getBar(anyNumber())).thenReturn('one');
when(mockedFoo.getBar(3)).thenReturn('one');
const foo:Foo = instance(mockedFoo);
foo.getBar(3); // MultipleMatchersMatchSameStubError will be thrown, two matchers match same method call
You can mock interfaces too, just instead of passing type to mock
function, set mock
function generic type Mocking interfaces requires Proxy
implementation
let mockedFoo:Foo = mock<FooInterface>(); // instead of mock(FooInterface)
const foo: SampleGeneric<FooInterface> = instance(mockedFoo);
You can mock abstract classes
const mockedFoo: SampleAbstractClass = mock(SampleAbstractClass);
const foo: SampleAbstractClass = instance(mockedFoo);
You can also mock generic classes, but note that generic type is just needed by mock type definition
const mockedFoo: SampleGeneric<SampleInterface> = mock(SampleGeneric);
const foo: SampleGeneric<SampleInterface> = instance(mockedFoo);
You can partially mock an existing instance:
const foo: Foo = new Foo();
const spiedFoo = spy(foo);
when(spiedFoo.getBar(3)).thenReturn('one');
console.log(foo.getBar(3)); // 'one'
console.log(foo.getBaz()); // call to a real method
You can spy on plain objects too:
const foo = { bar: () => 42 };
const spiedFoo = spy(foo);
foo.bar();
console.log(capture(spiedFoo.bar).last()); // [42]
Author: NagRock
Source Code: https://github.com/NagRock/ts-mockito
License: MIT license
1632537859
Not babashka. Node.js babashka!?
Ad-hoc CLJS scripting on Node.js.
Experimental. Please report issues here.
Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.
Additional goals and features are:
Nbb requires Node.js v12 or newer.
CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).
Install nbb
from NPM:
$ npm install nbb -g
Omit -g
for a local install.
Try out an expression:
$ nbb -e '(+ 1 2 3)'
6
And then install some other NPM libraries to use in the script. E.g.:
$ npm install csv-parse shelljs zx
Create a script which uses the NPM libraries:
(ns script
(:require ["csv-parse/lib/sync$default" :as csv-parse]
["fs" :as fs]
["path" :as path]
["shelljs$default" :as sh]
["term-size$default" :as term-size]
["zx$default" :as zx]
["zx$fs" :as zxfs]
[nbb.core :refer [*file*]]))
(prn (path/resolve "."))
(prn (term-size))
(println (count (str (fs/readFileSync *file*))))
(prn (sh/ls "."))
(prn (csv-parse "foo,bar"))
(prn (zxfs/existsSync *file*))
(zx/$ #js ["ls"])
Call the script:
$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs
Nbb has first class support for macros: you can define them right inside your .cljs
file, like you are used to from JVM Clojure. Consider the plet
macro to make working with promises more palatable:
(defmacro plet
[bindings & body]
(let [binding-pairs (reverse (partition 2 bindings))
body (cons 'do body)]
(reduce (fn [body [sym expr]]
(let [expr (list '.resolve 'js/Promise expr)]
(list '.then expr (list 'clojure.core/fn (vector sym)
body))))
body
binding-pairs)))
Using this macro we can look async code more like sync code. Consider this puppeteer example:
(-> (.launch puppeteer)
(.then (fn [browser]
(-> (.newPage browser)
(.then (fn [page]
(-> (.goto page "https://clojure.org")
(.then #(.screenshot page #js{:path "screenshot.png"}))
(.catch #(js/console.log %))
(.then #(.close browser)))))))))
Using plet
this becomes:
(plet [browser (.launch puppeteer)
page (.newPage browser)
_ (.goto page "https://clojure.org")
_ (-> (.screenshot page #js{:path "screenshot.png"})
(.catch #(js/console.log %)))]
(.close browser))
See the puppeteer example for the full code.
Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet
macro is similar to promesa.core/let
.
$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)' 0.17s user 0.02s system 109% cpu 0.168 total
The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx
this adds another 300ms or so, so for faster startup, either use a globally installed nbb
or use $(npm bin)/nbb script.cljs
to bypass npx
.
Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.
To load .cljs
files from local paths or dependencies, you can use the --classpath
argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs
relative to your current dir, then you can load it via (:require [foo.bar :as fb])
. Note that nbb
uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar
in the namespace name becomes foo_bar
in the directory name.
To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:
$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"
and then feed it to the --classpath
argument:
$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]
Currently nbb
only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar
files will be added later.
The name of the file that is currently being executed is available via nbb.core/*file*
or on the metadata of vars:
(ns foo
(:require [nbb.core :refer [*file*]]))
(prn *file*) ;; "/private/tmp/foo.cljs"
(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"
Nbb includes reagent.core
which will be lazily loaded when required. You can use this together with ink to create a TUI application:
$ npm install ink
ink-demo.cljs
:
(ns ink-demo
(:require ["ink" :refer [render Text]]
[reagent.core :as r]))
(defonce state (r/atom 0))
(doseq [n (range 1 11)]
(js/setTimeout #(swap! state inc) (* n 500)))
(defn hello []
[:> Text {:color "green"} "Hello, world! " @state])
(render (r/as-element [hello]))
Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core
namespace is included with the let
and do!
macros. An example:
(ns prom
(:require [promesa.core :as p]))
(defn sleep [ms]
(js/Promise.
(fn [resolve _]
(js/setTimeout resolve ms))))
(defn do-stuff
[]
(p/do!
(println "Doing stuff which takes a while")
(sleep 1000)
1))
(p/let [a (do-stuff)
b (inc a)
c (do-stuff)
d (+ b c)]
(prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3
Also see API docs.
Since nbb v0.0.75 applied-science/js-interop is available:
(ns example
(:require [applied-science.js-interop :as j]))
(def o (j/lit {:a 1 :b 2 :c {:d 1}}))
(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1
Most of this library is supported in nbb, except the following:
:syms
.-x
notation. In nbb, you must use keywords.See the example of what is currently supported.
See the examples directory for small examples.
Also check out these projects built with nbb:
See API documentation.
See this gist on how to convert an nbb script or project to shadow-cljs.
Prequisites:
To build:
bb release
Run bb tasks
for more project-related tasks.
Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb
License: EPL-1.0
#node #javascript
1656280800
This package allows users to jump to local IDE code directly from browser React component by just a simple click, which is similar to Chrome inspector but more advanced.
press hotkey (
ctrl⌃ + shift⇧ + commmand⌘ + c
), then click the HTML element you wish to inspect.
screen record gif (8M size):
npm i -D react-dev-inspector
Users need to add React component and apply webpack config before connecting your React project with 'react-dev-inspector'.
Note: You should NOT use this package, and React component, webpack config in production mode
import React from 'react'
import { Inspector, InspectParams } from 'react-dev-inspector'
const InspectorWrapper = process.env.NODE_ENV === 'development'
? Inspector
: React.Fragment
export const Layout = () => {
// ...
return (
{}}
onClickElement={(params: InspectParams) => {}}
>
...
)
}
You should add:
react-dev-inspector/plugins/babel
import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'
to your current project development config.
Such as add babel plugin into your .babelrc
or webpack babel-loader
config,
add api middleware into your webpack-dev-server
config or other server setup.
There are some example ways to set up, please pick the one fit your project best.
In common cases, if you're using webpack, you can see #raw-webpack-config,
If your project happen to use vite / nextjs / create-react-app and so on, you can also try out our integrated plugins / examples with
Example:
// .babelrc.js
module.exports = {
plugins: [
/**
* react-dev-inspector plugin, options docs see:
* https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
*/
'react-dev-inspector/plugins/babel',
],
}
// webpack.config.ts
import type { Configuration } from 'webpack'
import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'
const config: Configuration = {
/**
* [server side] webpack dev server side middleware for launch IDE app
*/
devServer: {
before: (app) => {
app.use(launchEditorMiddleware)
},
},
}
example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/vite2
example vite.config.ts
:
import { defineConfig } from 'vite'
import { inspectorServer } from 'react-dev-inspector/plugins/vite'
export default defineConfig({
plugins: [
inspectorServer(),
],
})
use Next.js Custom Server + Customizing Babel Config
example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/nextjs
in server.js
, example:
...
const {
queryParserMiddleware,
launchEditorMiddleware,
} = require('react-dev-inspector/plugins/webpack')
app.prepare().then(() => {
createServer((req, res) => {
/**
* middlewares, from top to bottom
*/
const middlewares = [
/**
* react-dev-inspector configuration two middlewares for nextjs
*/
queryParserMiddleware,
launchEditorMiddleware,
/** Next.js default app handle */
(req, res) => handle(req, res),
]
const middlewarePipeline = middlewares.reduceRight(
(next, middleware) => (
() => { middleware(req, res, next) }
),
() => {},
)
middlewarePipeline()
}).listen(PORT, (err) => {
if (err) throw err
console.debug(`> Ready on http://localhost:${PORT}`)
})
})
in package.json
, example:
"scripts": {
- "dev": "next dev",
+ "dev": "node server.js",
"build": "next build"
}
in .babelrc.js
, example:
module.exports = {
plugins: [
/**
* react-dev-inspector plugin, options docs see:
* https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
*/
'react-dev-inspector/plugins/babel',
],
}
cra + react-app-rewired + customize-cra example config-overrides.js
:
example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/cra
const { ReactInspectorPlugin } = require('react-dev-inspector/plugins/webpack')
const {
addBabelPlugin,
addWebpackPlugin,
} = require('customize-cra')
module.exports = override(
addBabelPlugin([
'react-dev-inspector/plugins/babel',
// plugin options docs see:
// https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
{
excludes: [
/xxxx-want-to-ignore/,
],
},
]),
addWebpackPlugin(
new ReactInspectorPlugin(),
),
)
example project see: https://github.com/zthxxx/react-dev-inspector/tree/master/examples/umi3
Example .umirc.dev.ts
:
// https://umijs.org/config/
import { defineConfig } from 'umi'
export default defineConfig({
plugins: [
'react-dev-inspector/plugins/umi/react-inspector',
],
inspectorConfig: {
// babel plugin options docs see:
// https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
excludes: [],
},
})
Example .umirc.dev.js
:
import { launchEditorMiddleware } from 'react-dev-inspector/plugins/webpack'
export default {
// ...
extraBabelPlugins: [
// plugin options docs see:
// https://github.com/zthxxx/react-dev-inspector#inspector-babel-plugin-options
'react-dev-inspector/plugins/babel',
],
/**
* And you need to set `false` to `dll` in `umi-plugin-react`,
* becase these is a umi2 bug that `dll` cannot work with `devServer.before`
*
* https://github.com/umijs/umi/issues/2599
* https://github.com/umijs/umi/issues/2161
*/
chainWebpack(config, { webpack }) {
const originBefore = config.toConfig().devServer
config.devServer.before((app, server, compiler) => {
app.use(launchEditorMiddleware)
originBefore?.before?.(app, server, compiler)
})
return config
},
}
Example build.json
:
// https://ice.work/docs/guide/basic/build
{
"plugins": [
"react-dev-inspector/plugins/ice",
]
}
checkout TS definition under react-dev-inspector/es/Inspector.d.ts
.
Property | Description | Type | Default |
---|---|---|---|
keys | inspector hotkeys supported keys see: https://github.com/jaywcjlove/hotkeys#supported-keys | string[] | ['control', 'shift', 'command', 'c'] |
disableLaunchEditor | disable editor launching (launch by default in dev Mode, but not in production mode) | boolean | false |
onHoverElement | triggered when mouse hover in inspector mode | (params: InspectParams) => void | - |
onClickElement | triggered when mouse hover in inspector mode | (params: InspectParams) => void | - |
// import type { InspectParams } from 'react-dev-inspector'
interface InspectParams {
/** hover / click event target dom element */
element: HTMLElement,
/** nearest named react component fiber for dom element */
fiber?: React.Fiber,
/** source file line / column / path info for react component */
codeInfo?: {
lineNumber: string,
columnNumber: string,
/**
* code source file relative path to dev-server cwd(current working directory)
* need use with `react-dev-inspector/plugins/babel`
*/
relativePath?: string,
/**
* code source file absolute path
* just need use with `@babel/plugin-transform-react-jsx-source` which auto set by most framework
*/
absolutePath?: string,
},
/** react component name for dom element */
name?: string,
}
interface InspectorPluginOptions {
/** override process.cwd() */
cwd?: string,
/** patterns to exclude matched files */
excludes?: (string | RegExp)[],
}
// import type { ParserPlugin, ParserOptions } from '@babel/parser'
// import type { InspectorConfig } from 'react-dev-inspector/plugins/webpack'
interface InspectorConfig {
/** patterns to exclude matched files */
excludes?: (string | RegExp)[],
/**
* add extra plugins for babel parser
* default is ['typescript', 'jsx', 'decorators-legacy', 'classProperties']
*/
babelPlugins?: ParserPlugin[],
/** extra babel parser options */
babelOptions?: ParserOptions,
}
This package uses react-dev-utils
to launch your local IDE application, but, which one will be open?
In fact, it uses an environment variable named REACT_EDITOR
to specify an IDE application, but if you do not set this variable, it will try to open a common IDE that you have open or installed once it is certified.
For example, if you want it always open VSCode when inspection clicked, set export REACT_EDITOR=code
in your shell.
install VSCode command line tools, see the official docs
set env to shell, like .bashrc
or .zshrc
export REACT_EDITOR=code
.bashrc
or .zshrc
(only MacOS)export REACT_EDITOR='/Applications/WebStorm.app/Contents/MacOS/webstorm'
OR
install WebStorm command line tools
then set env to shell, like .bashrc
or .zshrc
export REACT_EDITOR=webstorm
Yes! you can also use vim if you want, just set env to shell
export REACT_EDITOR=vim
Stage 1 - Compile Time
Stage 2 - Web React Runtime
[React component] Inspector
Component in react, for listen hotkeys, and request api to dev-server for open IDE.
Specific, when you click a component DOM, the Inspector
will try to obtain its source file info (path/line/column), then request launch-editor api (in stage 3) with absolute file path.
Stage 3 - Dev-server Side
[middleware] setup launchEditorMiddleware
in webpack dev-server (or other dev-server), to open file in IDE according to the request params.
Only need in development mode,and you want to open IDE when click a component element.
Not need in prod mode, or you just want inspect dom without open IDE (set disableLaunchEditor={true}
to Inspector component props)
Author: zthxxx
Source code: https://github.com/zthxxx/react-dev-inspector
License: MIT license
1622719015
Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices.
Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend.
Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently.
The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.
Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers.
The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module.
Alongside prevalence, Node.js additionally acquired the fundamental JS benefits:
In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development).
This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable.
In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based.
There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations).
Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.
Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while.
Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements.
Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility.
Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root.
What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations.
Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation.
In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.
So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development.
I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call.
Good Luck!
#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development
1605177692
In this video, I will be showing you what a templating engine is by showing you 3 different templating engines the ones we will look at it is pug, mustache and ejs.
#node js tutorial #node js templating #node js templates #nodejs for beginners #mustache templating #mustache.js