Tumgik
#babel-plugin-lodash
codehunter · 2 years
Text
Preset files are not allowed to export objects
I have a carousel file in which I want to get index.js and build block.build.js, so my webpack.config.js is:
var config = { entry: './index.js', output: { path: __dirname, filename: 'block.build.js', }, devServer: { contentBase: './Carousel' }, module : { rules : [ { test: /.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'es2015'], plugins: ['transform-class-properties'] } } ] }};module.exports = config;
The package.json which I use is below:
{ "name": "carousel", "version": "1.0.0", "description": "", "main": "webpack.config.js", "dependencies": { "@babel/core": "^7.0.0-beta.40", "babel-cli": "^6.26.0", "babel-loader": "^8.0.0-beta.0", "babel-plugin-lodash": "^3.3.2", "babel-plugin-react-transform": "^3.0.0", "babel-preset-react": "^6.24.1", "cross-env": "^5.1.3", "lodash": "^4.17.5", "react": "^16.2.0", "react-dom": "^16.2.0", "react-swipeable": "^4.2.0", "styled-components": "^3.2.1" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "watch": "webpack --watch", "start": "webpack-dev-server --open", "build": "webpack" }, "devDependencies": { "webpack": "^4.1.1", "webpack-cli": "^2.0.10", "webpack-dev-server": "^3.1.0" }, "author": "brad traversy", "license": "ISC"}
… but I get this error message:
ERROR in ./index.jsModule build failed: Error: Plugin/Preset files are not allowed to export objects, only functions.
Does anyone know how to solve this?
https://codehunter.cc/a/reactjs/preset-files-are-not-allowed-to-export-objects
0 notes
qwertsypage · 4 years
Text
Auth0: Vue & TypeScript Quickstart SDK - The Missing Docs
Tumblr media
Authentication is hard. Even if you know the ins and outs of it, handling registration, login, email verification, forgotten password, secret rotation... and what not... is a tedious work.
For this reason, we use auth providers such as AWS Cognito or Auth0. But this comes with its own drawback, namely that you are at the provider's mercy when it comes to examples and tutorials. If a resource you need does not exist, you either need to contact support and wait for them (but nobody got time for that), or figure it out yourself by the good ol' trial and error method.
A couple of days ago, I had to use Auth0 with Vue.js and TypeScript. Now, Auth0 has an excellent tutorial for Vue.js, but I could not find any examples in TypeScript. So seeing no better option, I started annotating the code provided by the tutorial.
I finished it, and in this blogpost, I'll walk you through the details, so you don't have to repeat this chore.
We will follow the original Auth0 Vue tutorial structure which can be found here. To make it easier to compare the two, we'll use the exact same first-level headings as the original.
You can find my complete auth0 vue typescript repo on RisingStack's Github.
Configure Auth0
First, you'll need to set up your Auth0 application. That part is very well written in the original tutorial, and I would like to be neither repetitive nor plagiarize Auth0's content, so please go ahead and read the first section there, then come back.
Create a Sample Application
Now we already start to diverge from the Auth0 tutorial.
If you already have an existing app, make sure that typescript, vue-class-component, and vue-property-decorator are present in your package.json, as we'll use class components.
If you don't have one, let's create a sample app.
$ vue create auth0-ts-vue
When prompted, select Manually select features.
Tumblr media
We'll need Babel, TypeScript, and Router.
Tumblr media
The next 3 questions are about deciding whether you want to use class-style component syntax, Babel, and history mode. Hit enter for all three to answer "Yes". You might opt-out from history mode if you really want to.
Tumblr media
It is entirely up to you if you want to use dedicated config files or not, and if you want to save this as a preset.
Grab a beverage of your preference while the dependencies are being installed.
Install the SDK
Once it's done, we need to install our auth0 dependencies.
$ cd auth0-ts-vue-example $ npm install @auth0/auth0-spa-js
The auth0-spa-js package comes with its own type definitions, so we're all set for now.
Modify your Webpack Config
If you followed the original Auth0 tutorials configuration part, you've set up your URLs to listen at port 3000. Time to hard code this into our webpack dev-server.
Create a vue.config.js file in the root directory of your app.
const webpack = require('webpack') module.exports = { devServer: { port: 3000 } }
This way, we don't have to specify the PORT env var when we run our app. We'd need to change it in Auth0 anyway all the time, while we're developing it.
Start the application
$ npm run serve
Leave it running so we can leverage Webpack's incremental build throughout the process.
Create an Authentication Wrapper
Have you ever created a Vue.js plugin? Well, now is the time!
The easiest way to use Auth0 in your app is to make it available on this in each of your components, just as you do with $route after you've installed Vue Router.
It would be nice if this was a separate dependency, but for the sake of simplicity, let it live inside our codebase.
Create a directory called auth inside your src dir then create the following files: index.ts auth.ts, VueAuth.ts, User.ts. The original tutorial has them all in one file. Still, in my opinion, it is easier to understand what's happening if we separate the matters a bit, and it also results in nicer type definitions too.
Our index.ts will be a simple barrel file.
export * from './auth'
auth.ts is where we define the plugin. VueAuth.ts is a wrapper Vue object around auth0-spa-js, so we can leverage the observability provided by Vue, and User.ts is a class to make its type definition nicer.
Defining our User
Let's go from the inside out and take a look at User.ts
import { camelCase } from 'lodash' export class User { sub: string names: string nickname: string picture: string updatedAt: string email: string emailVerified: boolean provider?: string id?: string givenName?: string familyName?: string locale?: string [key: string]: string | boolean | undefined constructor (auth0User: { [key: string]: string | boolean | undefined }) { if (!auth0User) return for (const key in auth0User) { this[key] = auth0User[key] } this.sub = auth0User.sub as string this.provider = this.sub.split('|')[0] this.id = this.sub.split('|')[1] } }
Now, this requires a bit of explanation. The first block of fields are the one that are always present, no matter what login scheme the user used. Sub is the OpenID ID Token's Subject Identifier, which contains the authentication provider (eg. auth0 or google) and the actual user id, separated by a |. The other mandatory fields are probably self-explanatory.
Next are provider and id, which are a result of splitting sub, so they should be there, but we cannot be sure. The last are the ones that were only present when Google OAuth is used as the provider. There might be more, depending on what connections you set up and what other data you request. Or you could even code custom fields in the returned ID Token... but I digress.
Last we tell TypeScript, that we want to be able to use the bracket notation on our object by adding [key: string]: any
Our constructor takes a raw user object with similar fields but snake_cased. That's why we camelCase them and assign each of them to our User object. Once we're done, we extract the provider and the id from the subfield.
Show me the Wrapper
Time to take a look at VueAuth.ts
import { Vue, Component } from 'vue-property-decorator' import createAuth0Client, { PopupLoginOptions, Auth0Client, RedirectLoginOptions, GetIdTokenClaimsOptions, GetTokenSilentlyOptions, GetTokenWithPopupOptions, LogoutOptions } from '@auth0/auth0-spa-js' import { User } from './User' export type Auth0Options = { domain: string clientId: string audience?: string [key: string]: string | undefined } export type RedirectCallback = (appState) => void @Component({}) export class VueAuth extends Vue { loading = true isAuthenticated? = false user?: User auth0Client?: Auth0Client popupOpen = false error?: Error async getUser () { return new User(await this.auth0Client?.getUser()) } /** Authenticates the user using a popup window */ async loginWithPopup (o: PopupLoginOptions) { this.popupOpen = true try { await this.auth0Client?.loginWithPopup(o) } catch (e) { console.error(e) this.error = e } finally { this.popupOpen = false } this.user = await this.getUser() this.isAuthenticated = true } /** Authenticates the user using the redirect method */ loginWithRedirect (o: RedirectLoginOptions) { return this.auth0Client?.loginWithRedirect(o) } /** Returns all the claims present in the ID token */ getIdTokenClaims (o: GetIdTokenClaimsOptions) { return this.auth0Client?.getIdTokenClaims(o) } /** Returns the access token. If the token is invalid or missing, a new one is retrieved */ getTokenSilently (o: GetTokenSilentlyOptions) { return this.auth0Client?.getTokenSilently(o) } /** Gets the access token using a popup window */ getTokenWithPopup (o: GetTokenWithPopupOptions) { return this.auth0Client?.getTokenWithPopup(o) } /** Logs the user out and removes their session on the authorization server */ logout (o: LogoutOptions) { return this.auth0Client?.logout(o) } /** Use this lifecycle method to instantiate the SDK client */ async init (onRedirectCallback: RedirectCallback, redirectUri: string, auth0Options: Auth0Options) { // Create a new instance of the SDK client using members of the given options object this.auth0Client = await createAuth0Client({ domain: auth0Options.domain, client_id: auth0Options.clientId, // eslint-disable-line @typescript-eslint/camelcase audience: auth0Options.audience, redirect_uri: redirectUri // eslint-disable-line @typescript-eslint/camelcase }) try { // If the user is returning to the app after authentication.. if ( window.location.search.includes('error=') || (window.location.search.includes('code=') && window.location.search.includes('state=')) ) { // handle the redirect and retrieve tokens const { appState } = await this.auth0Client?.handleRedirectCallback() ?? { appState: undefined } // Notify subscribers that the redirect callback has happened, passing the appState // (useful for retrieving any pre-authentication state) onRedirectCallback(appState) } } catch (e) { console.error(e) this.error = e } finally { // Initialize our internal authentication state when the page is reloaded this.isAuthenticated = await this.auth0Client?.isAuthenticated() this.user = await this.getUser() this.loading = false } } }
It might make sense to compare this with the original tutorial.
In the original tutorial, a Vue object is created while we're creating a class to make its annotation easier. There you can find it as:
// The 'instance' is simply a Vue object instance = new Vue({ ... })
Now let's unpack it.
First, we need to import a couple of types, including our User class.
Then we create the Auth0Options and RedirectCallback type aliases for convenience.
Instead of creating a simple Vue object, we define a Class Component. The public fields are the same as the data object in the original, whereas the static ones are the parameters passed to the plugin.
We differ in two substantial way from the original tutorial:
We have one less method: handleRedirectCallback is not used anywhere in the original, so we omitted it.
Instead of setting up the Auth0 Client in the Vue object's created hook, we use a separate method called init. Aside from that, the contents of the two are identical.
The reason for using a separate method is simple: The created hook is used in place of a constructor when it comes to Class Components, as the constructor of the class is usually called by Vue.
First, a component object is created just like when using Vue({}), passing it the data, methods, watchers, paramlist, and all the things we usually define for components. When this is done, the created hook is called. Later, when the component is actually used and rendered, the params are passed to it, and mounted, or updated.
The problem with the original one is that we cannot pass parameters to the created method. Neither can we write a proper constructor. So we need to have our own method we will call right after the object is instantiated just as it's done with created by Vue.
Let's dissect init a bit.
First, we create and auth0Client.
Then, in the try-catch block, we check if the user is returning after authentication and handle it. We check if the query params contain any signs of redirection. If they do, we call auth0Client.handleRedirectCallback, which parses the URL and either rejects with an error or resolves with and appState.
Then, we pass on the appState to onRedirectCallback. This is a function we can pass to the plugin when we install it to Vue, so we can handle the app level ramifications of a login.
For the other methods, getUser is a simple wrapper around the authClient's getUser method. We pass on the resolved promise to our User's constructor to create a nicely looking User object.
Next, there is loginWithPopup, which we won't use, as popups can be blocked by browsers. So we'll go with the redirect way, where the user is redirected to Auth0, login, then the callback URL is called by Auth0 passing information to our app in the callback URL's query.
The information in the URL is parsed by auth0Client.handleRedirectCallback which will return a Promise<RedirectCallbackResult>. The Promise will be rejected if there is an error in the authentication flow.
We have a couple of simple wrappers around the auth0Client. loginWithRedirect initiates the flow I described above, logout speaks for itself.
Finally, we set up the user and check if we're authenticated.
Let's turn this into a Plugin
Now, all we need to do is create a proper plugin.
If you take a look at Vue's documentation about plugins, you'll see that we need to create an object that exposes an install method. This method will be called when we pass the object to Vue.use and it will receive the Vue constructor and optionally... options.
type Auth0PluginOptions = { onRedirectCallback: RedirectCallback, redirectUri: string, domain: string, clientId: string, audience?: string, [key: string]: string | RedirectCallback | undefined } export const Auth0Plugin = { install (Vue: VueConstructor, options: Auth0PluginOptions) { Vue.prototype.$auth = useAuth0(options) } }
In our install method, we add an $auth member to any Vue object, so the VueAuth object is available everywhere, just as vue-router is.
Let's implement the useAuth function.
/** Define a default action to perform after authentication */ const DEFAULT_REDIRECT_CALLBACK = () => window.history.replaceState({}, document.title, window.location.pathname) let instance: VueAuth /** Returns the current instance of the SDK */ export const getInstance = () => instance /** Creates an instance of the Auth0 SDK. If one has already been created, it returns that instance */ export const useAuth0 = ({ onRedirectCallback = DEFAULT_REDIRECT_CALLBACK, redirectUri = window.location.origin, ...options }) => { if (instance) return instance // The 'instance' is simply a Vue object instance = new VueAuth() instance.init(onRedirectCallback, redirectUri, options as Auth0Options) return instance }
useAuth returns a singleton VueAtuh instance, and extracts the onRedirectCallback and redirectUri from the options object. What's left is an Auth0Options type which we'll pass on straight to the auth0Client.
You can see the init method in action we created earlier. Then VueAuth is instantiated if it hasn't been already. Above that, we also expose a getInstance function, in case we need to use it outside of a Vue component.
Let's see here the whole auth.ts for your copy-pasting convenience:
import { VueConstructor } from 'vue' import { VueAuth, Auth0Options, RedirectCallback } from './VueAuth' type Auth0PluginOptions = { onRedirectCallback: RedirectCallback, domain: string, clientId: string, audience?: string, [key: string]: string | RedirectCallback | undefined } /** Define a default action to perform after authentication */ const DEFAULT_REDIRECT_CALLBACK = (appState) => window.history.replaceState({}, document.title, window.location.pathname) let instance: VueAuth /** Returns the current instance of the SDK */ export const getInstance = () => instance /** Creates an instance of the Auth0 SDK. If one has already been created, it returns that instance */ export const useAuth0 = ({ onRedirectCallback = DEFAULT_REDIRECT_CALLBACK, redirectUri = window.location.origin, ...options }) => { if (instance) return instance // The 'instance' is simply a Vue object instance = new VueAuth() instance.init(onRedirectCallback, redirectUri, options as Auth0Options) return instance } // Create a simple Vue plugin to expose the wrapper object throughout the application export const Auth0Plugin = { install (Vue: VueConstructor, options: Auth0PluginOptions) { Vue.prototype.$auth = useAuth0(options) } }
As you can see, we're extending the Vue constructor with a new instance member. If we try to access it in a component, the TypeScript compiler will start crying as it has no idea what happened. We'll fix this a bit later down the line.
Now, the Auth0Options are the ones that are needed for the client to identify your tenant. Copy the Client ID and Domain from your Auth0 applications settings and store them in a file called auth.config.json for now. It would be nicer to inject them as environment variables through webpack, but as these are not sensitive data, we'll be just fine like that as well.
With all that said, I will not include my auth.config.json in the reference repo, only an example you'll need to fill in with your data.
{ "domain": "your tenant's domain", "clientId": "your app's clientId" }
Make sure to add "resolveJsonModule": true, to your tsconfig.json.
Finally, we're ready to create our main.ts.
import Vue from 'vue' import App from './App.vue' import router from './router' import { Auth0Plugin } from './auth' import { domain, clientId } from '../auth.config.json' Vue.use(Auth0Plugin, { domain, clientId, onRedirectCallback: (appState) => { router.push( appState && appState.targetUrl ? appState.targetUrl : window.location.pathname ) } }) Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')
The onRedirectCallback redirects the user to a protected route after they have authenticated. We'll cover this a bit later when we create an actual protected route.
Log in to the App
Time to put the authentication logic to use.
First, we'll add a Login / Logout button to Home.vue
<template> <div class="home"> <img alt="Vue logo" src="../assets/logo.png" /> <HelloWorld msg="Welcome to Your Vue.js App" /> <!-- Check that the SDK client is not currently loading before accessing is methods --> <div v-if="!$auth.loading"> <!-- show login when not authenticated --> <button v-if="!$auth.isAuthenticated" @click="login">Log in</button> <!-- show logout when authenticated --> <button v-if="$auth.isAuthenticated" @click="logout">Log out</button> </div> </div> </template>
We'll also need to update the logic in the script tag of Home
<script lang="ts"> import { Component, Vue } from 'vue-property-decorator' import HelloWorld from '@/components/HelloWorld.vue' @Component({ components: { HelloWorld } }) export default class Home extends Vue { login () { this.$auth.loginWithRedirect({}) } // Log the user out logout () { this.$auth.logout({ returnTo: window.location.origin }) } } </script>
First, we turn the original example component into a Class Component. Second, the methods simply call the methods of VueAuth exposed by our Auth0Plugin.
But what's that? this.$auth is probably underlined in your IDE. Or if you try to compile the code you'll get the following error:
Tumblr media
Of course, we still have to tell the compiler that we have augmented the Vue constructor with our $auth member.
Let's create a shims-auth0.d.ts file in our src directory. If you're using VSCode, you might need to reload the window to make the error go away.
import { VueAuth } from './auth/VueAuth' declare module 'vue/types/vue' { interface Vue { $auth: VueAuth } }
Checkpoint
Now, let's try to compile our code. If you have configured your Auth0 credentials correctly, you should be redirected to the Auth0 Universal Login page when you click Login, and back to your app against once you have logged in.
Then, you should be able to click Log out and have the application log you out.
Display the User's Profile
So far so good, but let's try to create a protected route. Displaying the user's profile seems like a prime target for that.
Let's create a file called Profile.vue in src/views.
<template> <div> <div> <img :src="$auth.user.picture"> <h2></h2> <p></p> </div> <div> <pre></pre> </div> </div> </template>
That's it. We read all the information we need from $auth.user we've already set up in VueAuth.ts.
Add a route to the Profile component
Let's update the app's routing configuration, so the users can access their profile.
Open up src/router/index.ts and add the following to the routes array.
//.. other imports // NEW - Import the profile component import Profile from "../views/Profile.vue"; Vue.use(VueRouter) const routes: Array<RouteConfig> = [ routes: [ // .. other routes and pages .. // NEW - add the route to the /profile component { path: "/profile", name: "profile", component: Profile } ] }); export default router
Now we need to update the navigation bar in App.vue
<template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> <span v-if="$auth.isAuthenticated"> | <router-link to="/profile">Profile</router-link> </span> </div> <router-view/> </div> </template>
Checkpoint
The code should compile, so let's check if we can navigate to the Profile page and see the data. For added profit, try logging in with both Google and register a username and password. Take note of the data you get.
Secure the Profile Page
We have the route, time to make it protected. Let's create a new file in src/auth called authGaurd.ts.
import { getInstance } from './auth' import { NavigationGuard } from 'vue-router' export const authGuard: NavigationGuard = (to, from, next) => { const authService = getInstance() const fn = () => { // Unwatch loading unwatch && unwatch() // If the user is authenticated, continue with the route if (authService.isAuthenticated) { return next() } // Otherwise, log in authService.loginWithRedirect({ appState: { targetUrl: to.fullPath } }) } // If loading has already finished, check our auth state using `fn()` if (!authService.loading) { return fn() } // Watch for the loading property to change before we check isAuthenticated const unwatch = authService.$watch('loading', (loading: boolean) => { if (loading === false) { return fn() } }) }
First, we put auth.ts's getInstance to use. Then we create a function that checks if the user is authenticated. If they are, we call next, otherwise redirect them to login.
However, we should only call this function, if the authService is not loading, as otherwise, we still don't have any settled information about the login process.
If it is still loading, we set up a watcher for authService.loading, so when it turns true, we call our guard function. Also, please notice that we use the unwatch function returned by $watch to clean up after ourselves in fn.
I personally prefer giving descriptive names to my functions, but I only wanted to change things for the sake of either type annotation, or stability, so forgive me for keeping fn as it is to maintain parity with the JS tutorial.
Guidance with Auth0, Vue & TypeScript
Auth0 and all other authentication providers relieve us from the tedious job of handling user management ourselves. Auth0 itself excels in having a lot of educational resources for their users. The original Vue tutorial was really helpful, but seeing that TypeScript is becoming the industry standard when it comes to writing anything that should be run by JavaScript runtimes, it would be nice to see more TypeScript tutorials.
I hope this article manages to fill in a bit of this gap. If you liked what you just read, please share it with those who might need guidance with Auth0, Vue & TypeScript!
Happy authenticating!
Auth0: Vue & TypeScript Quickstart SDK - The Missing Docs published first on https://koresolpage.tumblr.com/
0 notes
t-baba · 6 years
Photo
Tumblr media
D3.js 5.0, and an introduction to functional programming in JS
#378 — March 23, 2018
Read on the Web
JavaScript Weekly
Tumblr media
D3.js 5.0 Released — D3 continues to be a fantastic choice for data visualization with JavaScript. Changes in 5.0 include using promises to load data instead of callbacks, contour plots, and density contours.
Mike Bostock
Lazy Loading Modules with ConditionerJS — Linking JavaScript functionality to DOM elements can become a tedious task. See how ConditionerJS makes progressive enhancement easier in this thorough tutorial.
Smashing Magazine
The Best JavaScript Debugging Tools for 2018 — If you work with JavaScript, you’ll know that it doesn’t always play nice. Here we look at the best JavaScript debugging tools you can use to clean up your code and provide great software experiences to your users.
RAYGUN sponsor
▶  A 10 Video Introduction to Functional JavaScript with Ramda — Want to get started with functional programming in JavaScript? Ramda is a more functional alternative to libraries like Lodash, and these brief videos cover the essentials. You may also appreciate Kyle Simpson’s Functional-Light JavaScript if you set off on the functional programming journey.
James Moore
JavaScript vs. TypeScript vs. ReasonML: Pros and Cons — Dr. Axel is becoming a fan of static typing for larger projects and explains the pros and cons of it and how static typing relates to the TypeScript and ReasonML projects.
Dr. Axel Rauschmayer
A Proposal for Package Name Maps for ES Modules — Or how to solve the web’s “bare import specifier” problem.
Domenic Denicola
A TC39 Proposal for Object.fromEntries — It would transform a list of key/value pairs into an object.
TC39 news
How Unsplash Gradually Migrated to TypeScript
Oliver Joseph Ash
💻 Jobs
Engineering Manager — You’ll lead a team in building a product at scale and get the opportunity to manage and mentor while helping shape decisions.
Skillshare
Software Engineer at Fat Lama (London) — Technology and engineering is at the heart of what we do at Fat Lama - help us build the rental marketplace for everything.
Fat Lama
JavaScript Expert? Sign Up for Vettery — Create your profile and we’ll connect you with top companies looking for talented front-end developers.
Vettery
Place your own job listing in a future issue
📘 Tutorials & Tips
Getting Started with the Web MIDI API — Covers the basics of MIDI and the Web MIDI API showing how simple it is to create frontend apps that respond to musical inputs. It’s niche but also neat the Web platform can do this.
Peter Anglea
▶  7 Secret Patterns Vue Consultants Don&'t Want You to Know — Clickbaity talk title, but Chris is both on the Vue core team and a great speaker :-)
Chris Fritz
Learn to Build JavaScript Apps with MongoDB in M101JS, MongoDB for Node Developers — MongoDB University courses are free and give you everything you need to know about MongoDB.
MongoDB sponsor
How to Write Powerful Schemas in JavaScript — An introduction to schm, a library for building model schemas in a functional, composable way.
Diego Haz
Getting Smaller Lodash Bundles with Webpack and Babel — Plus some tips for working with lodash-webpack-plugin.
Nolan Lawson
Elegant Patterns in Modern JavaScript: RORO — RORO stands for Receive an Object, Return an Object.
Bill Sourour
The Ultimate Angular CLI Reference Guide — Create new Angular 2+ apps, scaffold components, run tests, build for production, and more.
Jurgen Van de Moere
▶  Add ESLint and Prettier to VS Code for 'Create React App' Apps
Elijah Manor
Tips for Using ESLint in a Legacy Codebase — Techniques that can help you significantly reduce the number of errors you see.
Sheshbabu Chinnakonda
Free eBook: A Roundup of Managed Kubernetes Platforms
Codeship sponsor
Lookaheads (and Lookbehinds) in JS Regular Expressions
Stefan Judis
Unblocking Clipboard Access in Chrome 66+ — The Async Clipboard API supersedes the document.execCommand approach.
Jason Miller
Building Office 365/SharePoint Applications with Aurelia
Magnus Danielson
🔧 Code and Tools
GPU-Accelerated Neural Networks in JavaScript — A look at four libraries providing this type of functionality.
Sebastian Kwiatkowski
Get the Best, Most Complete Collection of Angular UI Controls: Wijmo — Wijmo’s dependency-free UI controls include rich declarative markup, full IntelliSense, and the best data grid.
GrapeCity Wijmo sponsor
better-sqlite3: A Simple, Fast SQLite3 Library for Node
Joshua Wise
Tumblr media
ngx-datatable: A Feature-Rich Data-Table Component for Angular — No external dependencies. Demos here.
Swimlane
vue-content-loader: SVG-based 'Loading Placeholder' Component — It’s a port of ReactContentLoader.
EGOIST
DrawerJS: A Customizable HTML Canvas Drawing Tool — Live demo.
Carsten Schäfer
by via JavaScript Weekly https://ift.tt/2pzqNa9
0 notes
ianasennus · 6 years
Text
[Udemy] Functional Programming For Beginners With JavaScript
A practical guide that teaches you Functional Programming With JavaScript. Optimally paced, No-nonsense. Learn quickly!   What Will I Learn?   The essence of Functional Programming, without all the unneeded technical Jargon How to create applications, in a functional programming style Build sophisticated apps, with simple code What Pure Functions are, and why you should use them How to create new logic, without writing the logic, by using Function Composition What Currying And Partial Application are, and how they are helpful What Immutable Data Structures are, and why you should use them Why Eliminating and Controlling Side Effects is so important The benefits of Higher Order Functions How to write code in a style that minimizes the risk of difficult bugs The Beauty of Declarative Programming How the Ramda JavaScript library, makes functional techniques simple in JavaScript Requirements A Mac, PC or Linux Machine Already taken one or more courses in a programming language A desire to create applications, with the simplest code possible Description “Why should I learn Functional Programming?” Most software written today, is overly complex, difficult to understand, challenging to test, hard to change and filled with hard find bugs. Ouch! So how do we end up with these problems? Here’s a few of the many reasons: Not using the simplest building blocks possible… If you start with something complicated, you’ll end up with something even more complicated. Programming in a style that is more susceptible to complex bugs Not properly respecting and handling Side effects(talking to servers, input / output, etc) “Sprinkling” Application State all throughout codebases Unnecessarily mutating data Code Duplication (particularly sneaky ones, like similar class methods in Object Oriented Programming ) Writing more code than necessary These are just a few of the many problems that lead to frustrating jobs, working on codebases that are hard to maintain and add features to. Functional programming addresses the above problems in the following ways: Simpler apps, because functional programming uses the simplest building blocks possible, just plain old data and pure functions to transform the data (easier to understand and work with) Uses code styles that are simpler and less prone to complicated bugs (more time doing productive work) Eliminating Side Effects, as much as possible and controlling them when they are needed (reduces bugs) Avoids data mutation as much as possible (reduces bugs) Uses pure functions, that can work with many different types of data (improved code reuse) Uses generalized functions, that can be specialized to suit different needs (less code, same functionality) Creating new functions, without adding any new logic, using function composition (more functionality, no code added) Functional programming, in my experience, is more productive than Object Oriented Programming because there are fewer things to think about, so you don’t overwhelm your working memory.  Usually your just thinking about plain old data, and data transformations, using functions.  Additionally, in Functional Programming, there aren’t tons of competing ways of doing the same thing, so you don’t have to think about unnecessary things. Functional Programming is constraining, and thats a good thing. You’re able to better focus, on the problem you’re solving, rather than the tools you’re using to solve the problem. In Object Oriented Programming, you have to think about many different types of complicated, stateful objects that can be interacted with in different ways.  You’ve got to think about more than just data, and data transformation… You’ve got to think about things like State and Side Effects, far more than you do in Functional Programming. “What will I learn in this course?” You’ll learn how to create front end web applications in a Functional Programming Style, through hands on learning.  You’ll be building 5 significant web applications in this course, from the ground up.  At the end of this course, you’ll understand and appreciate the things that are important to Functional Programmers and odds are, you’ll fundamentally change how you write programs.  “What frontend framework will I learn?” I could teach you Functional Programming using a popular frontend framework like React or Vuejs, but frameworks come and go, and the principles I’ll teach you are timeless principles that transcend frameworks… So Instead, you’ll learn functional programming by just using Modern JavaScript, and a few helper libraries.  The knowledge and skills you’ll learn in this course can be used with the popular frameworks of today and tomorrow! “Will this course be 100% JavaScript from scratch?” We won’t be using any frameworks, but we will use a few helper libraries where it makes sense as described below. “What JavaScript Libraries are used in this course, and why even include libraries?” The main focus of this course is teaching you Functional Programming concepts.  Manually writing everything from scratch, could very well distract from the core concepts, so to stay focused, we’ll use a few libraries where it makes sense.   Libraries used: Ramda - We’ll use the awesome Ramda JavaScript Library, which similar to lodash and underscore, but it’s built to leverage Functional Programming Concepts.  In my opinion, this library is a must use library for functional programming in JavaScript. Hyperscript - We’ll use the hyperscript library to generate html and css.  For example, we’ll call hyperscripts ‘div' function to generate html divs.  ie div('hello’) => <div>hello</div> Tachyons - This is a css framework that embraces Functional Programming concepts like composition. Webpack/Babel - We’ll setup a minimal build system using webpack, babel and a few related plugins.  This is a onetime setup step. Virtual-Dom - We’ll use a virtual dom library to efficiently update webpages.  This is the technology used by modern frameworks like React and Vuejs.  This is a onetime setup step. “I’m a backend developer, but I’d like to learn Functional Programming… Should I take this course?” The knowledge and fundamental principles you’ll learn in this course, can easily be translated to the backend.  I’m teaching you Functional Programming for the frontend, because programming on the front end can be quite challenging and Functional Programming is a particularly good fit for the front end.  It’s important to note, this course focuses on Modern JavaScript and doesn’t use a front end framework, so you won’t have to learn frontend technologies that you may never use. “Can I write Functional Programs in JavaScript?” Yes, absolutely.  JavaScript allows you to program in many different styles, and using functional programming is an excellent choice. You’ll start by learning Functional Programming techniques using modern JavaScript ( ES2018 ), then later you’ll learn about the excellent Ramda JavaScript library. You may have heard the phrase "JavaScript, the good parts".  When you’re programming in a functional style, you’re simply using the good parts of the language, and you’ll naturally avoid the bad and confusing parts (like the this keyword ?(?_?)?).   “Isn’t Functional Programming just a small niche in Computer Science?” This used to be true, but not anymore.  For decades Object Oriented Programming was the dominant force in software development, but in the last few years Functional Programming has had huge growth, and it’s used in big companies like Facebook, Twitter and even Walmart.  But it’s not just the big companies that are using Functional Programming, small and medium sized companies all over the world are turning to Functional Programming. In December 2017, Forrester research released a study titled “The New Dawn Of Functional Programming”, which asserts “Functional Programming is beginning to hit the mainstage… the software development world is outgrowing stateful, object-oriented development”. It always makes sense to learn upward trending technologies, and Functional Programming is an excellent choice for this reason and many more. “Don’t I have to be a Math genius to understand Functional Programming?” Absolutely Not! For decades the primary adopters of Functional Programming, were largely academics and people interested in specialized areas of Math.  During that time, most working programmers (myself included) didn’t really understand Functional Programming, and the people who did understand Functional Programming, didn’t do a great job explaining what it was, what the benefits were, how to do it… etc. The truth is, you don’t need to be a Math genius to understand Functional Programming.  The essence of Functional Programming, has little to do with Math, which you’ll see in this course. “Won’t I have to learn a whole new vocabulary to understand Functional Programming?” No! I won’t bombard you with unneeded technical Jargon, in fact I avoid it as much as possible, and when I do use new Functional Programming vocabulary, it’s usually just to associate a name, to something you already learned with plain old spoken english. “Will the knowledge I gain in this course be obsolete in a year or two, just like my Angular 1 knowledge is?” No! What you’ll learn in this course will be relevant and useful for years and probably decades.  “How is that possible?” Because, I’m not teaching you functional programming in the context of particular framework like React or Vue.js.  Frameworks come and go, but the skills you’ll learn in this course transcend the popular framework of the day. “How is it that Code written in a functional programming style, is less prone to have hard to find bugs?” The most difficult to find and fix bugs, are related to code that allows Side Effects (talking to servers, state changes etc). Functional Programming puts a significant emphasis on Eliminating and Controlling Side Effects… So, it would make sense that eliminating Side Effects where possible, and tightly controlling side effects when they are needed would result in fewer complicated bugs.   “You say Functional Programming is simple, but I’ve tried Functional Programming and it was hard!?” Ah, I didn’t say it was easy, I said it was simple.  Writing simple code, isn’t easy, often it’s difficult.  But sophisticated software built with a simple codebase is a thing of beauty, and it’s totally worth it.   If you know and love Object Oriented Programming, you may be in for a challenge.  Much of what you know about programming, must be re-evaluated and often disregarded.  I suspect, it might be easier for a new programmer to learn functional programming vs an experienced Object Oriented Programmer, because Functional Programming is so different from Object Oriented Programming… But again, it’s totally worth it :) “I don’t understand some of the things your talking about like 'side effects’ and 'pure functions’?” Don’t worry, in this course I start with the very basics, so you should have no problem following along. Additionally, I offer some very unique, free options for getting help, which I describe in the video, on how to get help. “Is this course for me?” This course is meant for 2 types of students: New programmers who have taken an introductory programming course Experienced programmers who are interested in learning Functional Programming * * There might be a couple videos the Experienced programmer could skip, but I suggest re-familiarizing yourself with the basics, as they are presented from a Functional Programming Perspective. If you’re not sure if this course is right for you, remember there is virtually no risk to you as you’ll have 30 days to return the course for a refund. “Why should I take this course from you?” My courses are different from most Instructors.  I don’t believe a course should cover every single part of a language or technology. I’ll explain why with an analogy. Imagine you wanted to learn Spanish.  One approach to learning Spanish would be to learn every single Spanish word.  There are around 100,000 words in a Spanish dictionary… ouch!   Here’s the thing, 1,000 Spanish words that make up 80% of all spoken Spanish… 2,000 words makeup 95% of all spoken words. Wouldn’t it be better to focus on learning the 1,000 or 2,000 most used Spanish words?  You’d be fluent much quicker… In fact, trying to learn all 100,000 Spanish words, kind of sounds ridiculous, when you realize most of them are never used. These same principles apply to Programming Languages and Technologies.  Many instructors make 10, 20 and +30 hour courses, jam packed full of stuff you could just avoid! I don’t want to waste your time, so I’ll only be teaching you the most used parts of JavaScript and Functional Programming, so you’ll be fluent much faster. Who is the target audience? This course is for new programmers, who have completed at least one introductory programming course. This course is also for experienced programmers, who are new to Functional Programming. source https://ttorial.com/functional-programming-beginners-javascript
source https://ttorialcom.tumblr.com/post/175965303613
0 notes
ttorialcom · 6 years
Text
[Udemy] Functional Programming For Beginners With JavaScript
A practical guide that teaches you Functional Programming With JavaScript. Optimally paced, No-nonsense. Learn quickly!   What Will I Learn?   The essence of Functional Programming, without all the unneeded technical Jargon How to create applications, in a functional programming style Build sophisticated apps, with simple code What Pure Functions are, and why you should use them How to create new logic, without writing the logic, by using Function Composition What Currying And Partial Application are, and how they are helpful What Immutable Data Structures are, and why you should use them Why Eliminating and Controlling Side Effects is so important The benefits of Higher Order Functions How to write code in a style that minimizes the risk of difficult bugs The Beauty of Declarative Programming How the Ramda JavaScript library, makes functional techniques simple in JavaScript Requirements A Mac, PC or Linux Machine Already taken one or more courses in a programming language A desire to create applications, with the simplest code possible Description "Why should I learn Functional Programming?" Most software written today, is overly complex, difficult to understand, challenging to test, hard to change and filled with hard find bugs. Ouch! So how do we end up with these problems? Here’s a few of the many reasons: Not using the simplest building blocks possible… If you start with something complicated, you’ll end up with something even more complicated. Programming in a style that is more susceptible to complex bugs Not properly respecting and handling Side effects(talking to servers, input / output, etc) “Sprinkling” Application State all throughout codebases Unnecessarily mutating data Code Duplication (particularly sneaky ones, like similar class methods in Object Oriented Programming ) Writing more code than necessary These are just a few of the many problems that lead to frustrating jobs, working on codebases that are hard to maintain and add features to. Functional programming addresses the above problems in the following ways: Simpler apps, because functional programming uses the simplest building blocks possible, just plain old data and pure functions to transform the data (easier to understand and work with) Uses code styles that are simpler and less prone to complicated bugs (more time doing productive work) Eliminating Side Effects, as much as possible and controlling them when they are needed (reduces bugs) Avoids data mutation as much as possible (reduces bugs) Uses pure functions, that can work with many different types of data (improved code reuse) Uses generalized functions, that can be specialized to suit different needs (less code, same functionality) Creating new functions, without adding any new logic, using function composition (more functionality, no code added) Functional programming, in my experience, is more productive than Object Oriented Programming because there are fewer things to think about, so you don’t overwhelm your working memory.  Usually your just thinking about plain old data, and data transformations, using functions.  Additionally, in Functional Programming, there aren’t tons of competing ways of doing the same thing, so you don’t have to think about unnecessary things. Functional Programming is constraining, and thats a good thing. You’re able to better focus, on the problem you’re solving, rather than the tools you’re using to solve the problem. In Object Oriented Programming, you have to think about many different types of complicated, stateful objects that can be interacted with in different ways.  You’ve got to think about more than just data, and data transformation… You’ve got to think about things like State and Side Effects, far more than you do in Functional Programming. “What will I learn in this course?” You'll learn how to create front end web applications in a Functional Programming Style, through hands on learning.  You'll be building 5 significant web applications in this course, from the ground up.  At the end of this course, you'll understand and appreciate the things that are important to Functional Programmers and odds are, you'll fundamentally change how you write programs.  “What frontend framework will I learn?” I could teach you Functional Programming using a popular frontend framework like React or Vuejs, but frameworks come and go, and the principles I'll teach you are timeless principles that transcend frameworks... So Instead, you'll learn functional programming by just using Modern JavaScript, and a few helper libraries.  The knowledge and skills you'll learn in this course can be used with the popular frameworks of today and tomorrow! “Will this course be 100% JavaScript from scratch?” We won't be using any frameworks, but we will use a few helper libraries where it makes sense as described below. “What JavaScript Libraries are used in this course, and why even include libraries?” The main focus of this course is teaching you Functional Programming concepts.  Manually writing everything from scratch, could very well distract from the core concepts, so to stay focused, we'll use a few libraries where it makes sense.   Libraries used: Ramda - We'll use the awesome Ramda JavaScript Library, which similar to lodash and underscore, but it's built to leverage Functional Programming Concepts.  In my opinion, this library is a must use library for functional programming in JavaScript. Hyperscript - We'll use the hyperscript library to generate html and css.  For example, we'll call hyperscripts 'div' function to generate html divs.  ie div('hello') => <div>hello</div> Tachyons - This is a css framework that embraces Functional Programming concepts like composition. Webpack/Babel - We'll setup a minimal build system using webpack, babel and a few related plugins.  This is a onetime setup step. Virtual-Dom - We'll use a virtual dom library to efficiently update webpages.  This is the technology used by modern frameworks like React and Vuejs.  This is a onetime setup step. “I'm a backend developer, but I'd like to learn Functional Programming... Should I take this course?” The knowledge and fundamental principles you'll learn in this course, can easily be translated to the backend.  I'm teaching you Functional Programming for the frontend, because programming on the front end can be quite challenging and Functional Programming is a particularly good fit for the front end.  It's important to note, this course focuses on Modern JavaScript and doesn't use a front end framework, so you won't have to learn frontend technologies that you may never use. “Can I write Functional Programs in JavaScript?” Yes, absolutely.  JavaScript allows you to program in many different styles, and using functional programming is an excellent choice. You'll start by learning Functional Programming techniques using modern JavaScript ( ES2018 ), then later you'll learn about the excellent Ramda JavaScript library. You may have heard the phrase "JavaScript, the good parts".  When you're programming in a functional style, you're simply using the good parts of the language, and you'll naturally avoid the bad and confusing parts (like the this keyword ?(?_?)?).   “Isn’t Functional Programming just a small niche in Computer Science?” This used to be true, but not anymore.  For decades Object Oriented Programming was the dominant force in software development, but in the last few years Functional Programming has had huge growth, and it’s used in big companies like Facebook, Twitter and even Walmart.  But it’s not just the big companies that are using Functional Programming, small and medium sized companies all over the world are turning to Functional Programming. In December 2017, Forrester research released a study titled “The New Dawn Of Functional Programming”, which asserts “Functional Programming is beginning to hit the mainstage… the software development world is outgrowing stateful, object-oriented development”. It always makes sense to learn upward trending technologies, and Functional Programming is an excellent choice for this reason and many more. “Don’t I have to be a Math genius to understand Functional Programming?” Absolutely Not! For decades the primary adopters of Functional Programming, were largely academics and people interested in specialized areas of Math.  During that time, most working programmers (myself included) didn’t really understand Functional Programming, and the people who did understand Functional Programming, didn’t do a great job explaining what it was, what the benefits were, how to do it… etc. The truth is, you don’t need to be a Math genius to understand Functional Programming.  The essence of Functional Programming, has little to do with Math, which you’ll see in this course. “Won’t I have to learn a whole new vocabulary to understand Functional Programming?” No! I won’t bombard you with unneeded technical Jargon, in fact I avoid it as much as possible, and when I do use new Functional Programming vocabulary, it’s usually just to associate a name, to something you already learned with plain old spoken english. “Will the knowledge I gain in this course be obsolete in a year or two, just like my Angular 1 knowledge is?” No! What you’ll learn in this course will be relevant and useful for years and probably decades.  “How is that possible?” Because, I’m not teaching you functional programming in the context of particular framework like React or Vue.js.  Frameworks come and go, but the skills you’ll learn in this course transcend the popular framework of the day. “How is it that Code written in a functional programming style, is less prone to have hard to find bugs?” The most difficult to find and fix bugs, are related to code that allows Side Effects (talking to servers, state changes etc). Functional Programming puts a significant emphasis on Eliminating and Controlling Side Effects... So, it would make sense that eliminating Side Effects where possible, and tightly controlling side effects when they are needed would result in fewer complicated bugs.   “You say Functional Programming is simple, but I’ve tried Functional Programming and it was hard!?” Ah, I didn’t say it was easy, I said it was simple.  Writing simple code, isn’t easy, often it’s difficult.  But sophisticated software built with a simple codebase is a thing of beauty, and it’s totally worth it.   If you know and love Object Oriented Programming, you may be in for a challenge.  Much of what you know about programming, must be re-evaluated and often disregarded.  I suspect, it might be easier for a new programmer to learn functional programming vs an experienced Object Oriented Programmer, because Functional Programming is so different from Object Oriented Programming… But again, it’s totally worth it :) “I don't understand some of the things your talking about like 'side effects' and 'pure functions'?” Don't worry, in this course I start with the very basics, so you should have no problem following along. Additionally, I offer some very unique, free options for getting help, which I describe in the video, on how to get help. “Is this course for me?” This course is meant for 2 types of students: New programmers who have taken an introductory programming course Experienced programmers who are interested in learning Functional Programming * * There might be a couple videos the Experienced programmer could skip, but I suggest re-familiarizing yourself with the basics, as they are presented from a Functional Programming Perspective. If you’re not sure if this course is right for you, remember there is virtually no risk to you as you’ll have 30 days to return the course for a refund. “Why should I take this course from you?” My courses are different from most Instructors.  I don’t believe a course should cover every single part of a language or technology. I’ll explain why with an analogy. Imagine you wanted to learn Spanish.  One approach to learning Spanish would be to learn every single Spanish word.  There are around 100,000 words in a Spanish dictionary... ouch!   Here’s the thing, 1,000 Spanish words that make up 80% of all spoken Spanish… 2,000 words makeup 95% of all spoken words. Wouldn’t it be better to focus on learning the 1,000 or 2,000 most used Spanish words?  You’d be fluent much quicker… In fact, trying to learn all 100,000 Spanish words, kind of sounds ridiculous, when you realize most of them are never used. These same principles apply to Programming Languages and Technologies.  Many instructors make 10, 20 and +30 hour courses, jam packed full of stuff you could just avoid! I don’t want to waste your time, so I’ll only be teaching you the most used parts of JavaScript and Functional Programming, so you’ll be fluent much faster. Who is the target audience? This course is for new programmers, who have completed at least one introductory programming course. This course is also for experienced programmers, who are new to Functional Programming. source https://ttorial.com/functional-programming-beginners-javascript
0 notes
dragoni · 7 years
Link
Glad to see per method packages being removed. No more inconsistent syntax or 3rd party package mishmash.
import debounce from 'lodash/debounce' vs import debounce from 'lodash.debounce'
v5.0.0 (~2017) Roadmap
Discontinue lodash-cli in favor of bundling with webpack
Discontinue per method packages in favor of modular lodash
Drop support for overreaching shims like core-js
ES2015+ syntax using babel-preset-env
Split “Collection” methods into array & object methods
Remove monolithic entry point in favor of cherry-picking with babel-plugin-lodash
Reduce lodash package size by more than 50%
Minify modules
Move browser/core monolithic bundles to a separate package (15% savings)
Move lodash/fp back to lodash-fp (35% savings)
Read the complete roadmap
0 notes
chikuwa-parfait · 8 years
Text
babel-plugin-lodashでlodashの一部の関数だけ取り込む
babel-plugin-lodashというBabelプラグインを見かけたので早速試しに使ってみた。
package.json
{ "private": true, "dependencies": { "lodash": "^3.10.1" }, "devDependencies": { "babel": "^6.3.26", "babel-cli": "^6.4.0", "babel-plugin-lodash": "^1.1.0", "babel-preset-es2015": "^6.3.13" } }
lodashがver.4.0.0になったのだけど、対応していないみたいなのでlodashのver.3をインストールした。 lodash-esというものが追加されていたようなのだけど、ver.4ならこちらを使えば動作するのだろうか。
.babelrc
{ "presets": [ "es2015" ], "plugins": [ "lodash" ] }
src/index.js
import _ from 'lodash'; console.log(_.get({ aaa: { bbb: 100 } }, 'aaa.bbb'));
コンパイル
$ ./node_modules/.bin/babel --out-dir ./lib ./src
lib/index.js
'use strict'; var _get = require('lodash/object/get'); var _get2 = _interopRequireDefault(_get); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } console.log((0, _get2.default)({ aaa: { bbb: 100 } }, 'aaa.bbb'));
_.getだけ使用しているので、それだけ取り込まれている。
これでさらにwebpackを使えばブラウザでも取り込まれるのだろうと思う。
0 notes