#JavaScript IIFE
Explore tagged Tumblr posts
Text
Javascript functions interview questions, Closures & ES6 Part 2
javascript functions interview questions including closures, scope, IIFE, prototypes, and currying. Essential for frontend developers preparing for technical interviews in 2025. Javascript functions interview questions 🚀 Javascript functions interview questions 🚀 Javascript functions interview questions16. What is a Closure in JavaScript?17. What is Scope in JavaScript?18. What is the…
#advanced JavaScript interview questions#currying in JavaScript#JavaScript closures#JavaScript IIFE#JavaScript scope#JavaScript technical interview#prototype in JavaScript
0 notes
Text
Style Hijacker
Apparently free wordpress you arent allowed to write any actual code besides paragraphs like this one. I had made a style block to fix the RSS feeds widgets but it’s not allowed to be saved. So I encoded as base64 put that into a style injection script as javascript iife which can be executed by you if you really want in the address bar or your devtools console. Why? Why not. If you do the feeds…
0 notes
Video
youtube
Tech talk with Arcoiris Logics #javascript #mobileappdevelopment #codin... Title: Unlocking JavaScript Secrets: Hidden Tech Tips Every Developer Should KnowJavaScript continues to reign as one of the most powerful and widely used programming languages. From creating interactive websites to building complex applications, JavaScript powers the web in ways many developers are yet to fully understand. In this post, we’re diving into some hidden tech tips that can help you improve your JavaScript coding skills and efficiency.Here are some JavaScript tips for developers that will take your development game to the next level:1. Use Destructuring for Cleaner CodeJavaScript’s destructuring assignment allows you to extract values from arrays or objects into variables in a cleaner and more readable way. It’s perfect for dealing with complex data structures and improves the clarity of your code.javascriptCopy codeconst user = { name: "John", age: 30, location: "New York" }; const { name, age } = user; console.log(name, age); // John 30 2. Master Arrow FunctionsArrow functions provide a shorter syntax for writing functions and fix some common issues with the this keyword. They are especially useful in callback functions and higher-order functions.javascriptCopy codeconst greet = (name) => `Hello, ${name}!`; console.log(greet("Alice")); // Hello, Alice! 3. Leverage Default ParametersDefault parameters allow you to set default values for function parameters when no value is passed. This feature can help prevent errors and make your code more reliable.javascriptCopy codefunction greet(name = "Guest") { return `Hello, ${name}!`; } console.log(greet()); // Hello, Guest! 4. Mastering Promises and Async/AwaitPromises and async/await are essential for handling asynchronous operations in JavaScript. While callbacks were once the go-to solution, promises provide a more manageable way to handle complex asynchronous code.javascriptCopy codeconst fetchData = async () => { try { const response = await fetch("https://api.example.com"); const data = await response.json(); console.log(data); } catch (error) { console.error(error); } }; fetchData(); 5. Use Template Literals for Dynamic StringsTemplate literals make string interpolation easy and more readable. They also support multi-line strings and expression evaluation directly within the string.javascriptCopy codeconst user = "Alice"; const message = `Hello, ${user}! Welcome to JavaScript tips.`; console.log(message); 6. Avoid Global Variables with IIFE (Immediately Invoked Function Expressions)Global variables can be a source of bugs, especially in large applications. An IIFE helps by creating a local scope for your variables, preventing them from polluting the global scope.javascriptCopy code(function() { const temp = "I am local!"; console.log(temp); })(); 7. Array Methods You Should KnowJavaScript offers powerful array methods such as map(), filter(), reduce(), and forEach(). These methods allow for more functional programming techniques, making code concise and easier to maintain.javascriptCopy codeconst numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8] 8. Take Advantage of Spread OperatorThe spread operator (...) can be used to copy elements from arrays or properties from objects. It’s a game changer when it comes to cloning data or merging multiple arrays and objects.javascriptCopy codeconst arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; console.log(arr2); // [1, 2, 3, 4, 5] 9. Debugging with console.table()When working with complex data structures, console.table() allows you to output an object or array in a neat table format, making debugging much easier.javascriptCopy codeconst users = [{ name: "John", age: 25 }, { name: "Alice", age: 30 }]; console.table(users); 10. Use Strict Mode for Cleaner CodeActivating strict mode in JavaScript helps eliminate some silent errors by making them throw exceptions. It’s especially useful when debugging code or working in larger teams.javascriptCopy code"use strict"; let x = 3.14; ConclusionJavaScript offers a wealth of features and hidden gems that, when mastered, can drastically improve your coding skills. By incorporating these tips into your everyday coding practices, you'll write cleaner, more efficient code and stay ahead of the curve in JavaScript development.As technology continues to evolve, staying updated with JavaScript tips and best practices will ensure you're always on top of your development game. Happy coding!#JavaScript #WebDevelopment #TechTips #Coding #DeveloperLife #WebDevTips #JSDevelopment #JavaScriptTips #FrontendDevelopment #ProgrammerLife #JavaScriptForDevelopers #TechCommunity #WebDev
0 notes
Text
In-Page Logging for Web Devs - PrettyLogger.js
PrettyLogger is a tiny JavaScript that logs plain messages, objects, and event DOM elements directly into your page for easy debugging. Instead of sifting through browser console logs, you can view debug information in context, right alongside your application. This makes identifying and resolving issues during development easier. How it works: PrettyLogger uses an IIFE (Immediately Invoked…
1 note
·
View note
Text
What are Self Invoking Functions in JavaScript? explain in detail
JavaScript, the foundation of dynamic web applications, is continually evolving to fit the needs of contemporary development processes. Among its many features and approaches, one sometimes missed gem is the self-invoking capability. Also known as Immediately Invoked Function Expressions (IIFE), these functions have a slight but powerful capacity to improve code structure and maintainability.
Read more: https://www.mindstick.com/articles/335487/what-are-self-invoking-functions-in-javascript-explain-in-detail
0 notes
Text
How Chrome Extensions Can Scrape Hidden Information From Network Requests By Overriding XMLHttpRequest

Chrome extensions offer a versatile way to enhance browsing experiences by adding extra functionality to the Chrome browser. They serve various purposes, like augmenting product pages with additional information on e-commerce sites, scraping data from social media platforms such as LinkedIn or Twitter for analysis or future use, and even facilitating content scraping services for retrieving specific data from websites.
Scraping data from web pages typically involves injecting a content script to parse HTML or traverse the DOM tree using CSS selectors and XPaths. However, modern web applications built with frameworks like React or Vue pose challenges to this traditional scraping method due to their reactive nature.
When visiting a tweet on Twitter, essential details like author information, likes, retweets, and replies aren't readily available in the DOM. However, by inspecting the network tab, one can find API calls containing this hidden data, inaccessible through traditional DOM scraping. It's indeed possible to scrape this information from API calls, bypassing the limitations posed by the DOM.
A secondary method for scraping data involves intercepting API calls by overriding XMLHttpRequest. This entails replacing the native definition of XMLHttpRequest with a modified version via a content script injection. By doing so, developers gain the ability to monitor events within their modified XMLHttpRequest object while still maintaining the functionality of the original XMLHttpRequest object, allowing for seamless traffic monitoring without disrupting the user experience on third-party websites.
Step-by-Step Guide to Overriding XMLHttpRequest
Create a Script.js
This is an immediately invoked function expression (IIFE). It creates a private scope for the code inside, preventing variables from polluting the global scope.
XHR Prototype Modification: These lines save references to the original send and open methods of the XMLHttpRequest prototype.
Override Open Method: This code overrides the open method of XMLHttpRequest. When we create an XMLHttpRequest, this modification stores the request URL in the URL property of the XHR object.
Override Send Method: This code overrides the send method of XMLHttpRequest. It adds an event listener for the 'load' event. If the URL contains the specified string ("UserByScreenName"), it executes code to handle the response. After that, it calls the original send method.
Handling the Response: If the URL includes "UserByScreenName," it creates a new div element, sets its innerText to the intercepted response, and appends it to the document body.
Let's explore how we can override XMLHttpRequest!
Creating a Script Element: This code creates a new script element, sets its type to "text/javascript," specifies the source URL using Chrome.runtime.getURL("script.js"), and then appends it to the head of the document since it is a common way to inject a script into a web page.
Checking for DOM Elements: The checkForDOM function checks if the document's body and head elements are present. If they are, it calls the interceptData function. If not, it schedules another call to checkForDOM using requestIdleCallback to ensure the script waits until the necessary DOM elements are available.
Scraping Data from Profile: The scrapeDataProfile function looks for an element with the ID "__interceptedData." If found, it parses the JSON content of that element and logs it to the console as the API response. If not found, it schedules another call to scrapeDataProfile using requestIdleCallback.
Initiating the Process: These lines initiate the process by calling requestIdleCallback on checkForDOM and scrapeDataProfile. This ensures that the script begins by checking for the existence of the necessary DOM elements and then proceeds to scrape data when the "__interceptedData" element is available.
Pros
You can obtain substantial information from the server response and store details not in the user interface.
Cons
The server response may change after a certain period.
Here's a valuable tip
By simulating Twitter's internal API calls, you can retrieve additional information that wouldn't typically be displayed. For instance, you can access user details who liked tweets by invoking the API responsible for fetching this data, which is triggered when viewing the list of users who liked a tweet. However, it's important to keep these API calls straightforward, as overly frequent or unusual calls may trigger bot protection measures. This caution is crucial, as platforms like LinkedIn often use such strategies to detect scrapers, potentially leading to account restrictions or bans.
Conclusion
To conclude the entire situation, one must grasp the specific use case. Sometimes, extracting data from the user interface can be challenging due to its scattered placement. Therefore, opting to listen to API calls and retrieve data in a unified manner is more straightforward, especially for a browser extension development company aiming to streamline data extraction processes. Many websites utilize APIs to fetch collections of entities from the backend, subsequently binding them to the UI; this is precisely why intercepting API calls becomes essential.
#Content Scraping Services#Innovative Scrapping Techniques#Advanced Information Scraping Methods#browser extension development services
0 notes
Link
An Immediately-Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. It is a design pattern also known as a self-executing anonymous function. It runs automatically by wrapping it in parenthesis and adding a set of parenthesis at the end. The main purpose of this pattern is to create a new scope hidden from the outside scope so that any variables declared within the IIFE cannot be accessed from outside its scope. You can learn more about IIFE and its use cases in this article.
0 notes
Text
JavaScript Immediately-invoked Function Expressions (IIFE)
IIFE a function that runs as soon as it's defined. Usually it's anonymous (doesn't have a function name), but it also can be named. You can run functions instantly after they are constructed by using an immediately-invoked function expression. IIFEs are incredibly helpful since they can be used to easily separate variable declarations while not contaminating the global object. To execute functions instantly, as soon as they are constructed, use an Immediately-invoked Function Expression (IIFE, for friends). IIFEs are a great tool for isolating variable declarations because they don't contaminate the global object. The syntax that designates an IIFE is as follows: (function() { /* */ })() IIFEs may also be defined using arrow functions: (() => { /* */ })() In order to execute a function, we basically declare it inside parentheses and add the () sign: (/* function */). (). Our function is actually classified as an expression internally because of those encircling parentheses. If we hadn't specified a name, the function declaration would not be valid: Function expressions don't need a name, although function declarations do. There is no difference if you place the calling parentheses inside the expression parenthesis; this is merely a matter of preference: (function() { /* */ }()) (() => { /* */ }())
Explanation
So, this is how it functions. Recall the distinction between function expressions (var a = function()) and function statements (function a ())? Thus, IIFE is an expression of a function. We enclose our function declaration in parenthesis to turn it into an expression. Since JS doesn't permit statements in parenthesis, we do it to explicitly inform the parser that it is an expression rather than a statement. The two () braces that follow the function indicate how to call the function that was just declared. I'm done now. The rest are specifics. - It is not necessary for the IIFE function to be anonymous. This one will function flawlessly and aid in locating your function in a stacktrace when debugging: (function myIIFEFunc() { console.log("Hi, I'm IIFE!"); })(); // outputs "Hi, I'm IIFE!" - It can take some parameters: (function myIIFEFunc(param1) { console.log("Hi, I'm IIFE, " + param1); })("John"); // outputs "Hi, I'm IIFE, John" The function's param1 is supplied the value "Yuri" in this case. - It can return a value: var result = (function myIIFEFunc(param1) { console.log("Hi, I'm IIFE, " + param1); return 1; })("John"); // outputs "Hi, I'm IIFE, John" // result variable will contain 1 The most typical technique to define IIFE is to enclose the function declaration in parenthesis, but you are not required to do so. You can substitute any of the following forms instead: - ~function(){console.log("hi I'm IIFE")}() - !function(){console.log("hi I'm IIFE")}() - +function(){console.log("hi I'm IIFE")}() - -function(){console.log("hi I'm IIFE")}() - (function(){console.log("hi I'm IIFE")}()); - var i = function(){console.log("hi I'm IIFE")}(); - true && function(){ console.log("hi I'm IIFE") }(); - 0, function(){ console.log("hi I'm IIFE") }(); - new function(){ console.log("hi I'm IIFE") } - new function(){ console.log("hi I'm IIFE") }() Please refrain from using any of these forms to impress your coworkers, but be aware that you might come across them in someone's code.
Applications and usefulness
If you declare variables and functions inside an IIFE, they are hidden from the outside world, allowing you to: - Use the IIFE to isolate specific sections of the code and hide implementation details. - By giving parameters to the IIFE for frequently used global objects (such as windows, documents, jQuery, etc.), you may specify the input interface of your code. You can then utilise a local scope to refer to these global objects inside the IIFE. - When using closures in loops, use it in closures. - IIFE serves as the foundation for the module pattern in ES5 code, preventing global scope pollution and providing the module interface to the outside world. Read the full article
0 notes
Text
JavaScript Immediately-invoked Function Expressions (IIFE)
New Post has been published on https://www.codesolutionstuff.com/javascript-immediately-invoked-function-expressions-iife/
JavaScript Immediately-invoked Function Expressions (IIFE)
IIFE a function that runs as soon as it’s defined. Usually it’s anonymous (doesn’t have a function name), but it also can be named.
You can run functions instantly after they are constructed by using an immediately-invoked function expression. IIFEs are incredibly helpful since they can be used to easily separate variable declarations while not contaminating the global object.
To execute functions instantly, as soon as they are constructed, use an Immediately-invoked Function Expression (IIFE, for friends).
IIFEs are a great tool for isolating variable declarations because they don’t contaminate the global object.
The syntax that designates an IIFE is as follows:
(function() /* */ )()
IIFEs may also be defined using arrow functions:
(() => /* */ )()
In order to execute a function, we basically declare it inside parentheses and add the () sign: (/* function */). ().
Our function is actually classified as an expression internally because of those encircling parentheses. If we hadn’t specified a name, the function declaration would not be valid:
Function expressions don’t need a name, although function declarations do.
There is no difference if you place the calling parentheses inside the expression parenthesis; this is merely a matter of preference:
(function() /* */ ()) (() => /* */ ())
Explanation
So, this is how it functions. Recall the distinction between function expressions (var a = function()) and function statements (function a ())? Thus, IIFE is an expression of a function. We enclose our function declaration in parenthesis to turn it into an expression. Since JS doesn’t permit statements in parenthesis, we do it to explicitly inform the parser that it is an expression rather than a statement.
The two () braces that follow the function indicate how to call the function that was just declared.
I’m done now. The rest are specifics.
It is not necessary for the IIFE function to be anonymous. This one will function flawlessly and aid in locating your function in a stacktrace when debugging:
(function myIIFEFunc() console.log("Hi, I'm IIFE!"); )(); // outputs "Hi, I'm IIFE!"
It can take some parameters:
(function myIIFEFunc(param1) console.log("Hi, I'm IIFE, " + param1); )("John"); // outputs "Hi, I'm IIFE, John"
The function’s param1 is supplied the value “Yuri” in this case.
It can return a value:
var result = (function myIIFEFunc(param1) console.log("Hi, I'm IIFE, " + param1); return 1; )("John"); // outputs "Hi, I'm IIFE, John" // result variable will contain 1
The most typical technique to define IIFE is to enclose the function declaration in parenthesis, but you are not required to do so. You can substitute any of the following forms instead:
~function()console.log("hi I'm IIFE")()
!function()console.log("hi I'm IIFE")()
+function()console.log("hi I'm IIFE")()
-function()console.log("hi I'm IIFE")()
(function()console.log("hi I'm IIFE")());
var i = function()console.log("hi I'm IIFE")();
true && function() console.log("hi I'm IIFE") ();
0, function() console.log("hi I'm IIFE") ();
new function() console.log("hi I'm IIFE")
new function() console.log("hi I'm IIFE") ()
Please refrain from using any of these forms to impress your coworkers, but be aware that you might come across them in someone’s code.
Applications and usefulness
If you declare variables and functions inside an IIFE, they are hidden from the outside world, allowing you to:
Use the IIFE to isolate specific sections of the code and hide implementation details.
By giving parameters to the IIFE for frequently used global objects (such as windows, documents, jQuery, etc.), you may specify the input interface of your code. You can then utilise a local scope to refer to these global objects inside the IIFE.
When using closures in loops, use it in closures.
IIFE serves as the foundation for the module pattern in ES5 code, preventing global scope pollution and providing the module interface to the outside world.
IIFE, JavaScript, webpack
0 notes
Text
Omg. I love how serendipity helps me out sometimes. Just yesterday I mentioned that I didn’t really understand the point of IIFEs, then today I happened to discover a resource that explains them – plus a bunch of other stuff – incredibly well.
The resource in question is this free video course called “JavaScript Scopes and Closures In-Depth” by Koushik Kothagal. It has three units: “1. Understanding Scopes”, “2. Compilation and Interpretation”, and “3. Closures”. I just watched all of Unit 1, and oh my gosh, Koushik explains things SO well. I’ve been confused by some of these concepts for months, and now it feels like I finally really have a handle on them! And one of the Unit 1 videos also casually explains IIFEs in about one minute, and in such a way that I don’t think I’ll ever forget their purpose now.
In a nutshell: We all know we want to avoid declaring global variables, and one of the primary reasons for that is that they might accidentally overwrite other variables that share their name. So it’s better to declare them inside a function, because the main way to create a non-global scope in JS is by putting stuff inside a function. However, if you name your function, then the function ITSELF still counts as a global variable and runs into the exact same problem: it could potentially overwrite another function (or variable) with the same name! So the very simple solution is to make it a nameless function. And how do you run a nameless function? By making it an IIFE. Q, E, and D.
I am so excited to watch Units 2 and 3 of this course. Thank you Koushik!
(He also has a website that I’ll have to check out, called Java Brains.)
1 note
·
View note
Text
An Alternative for IIFEs In JavaScript
In the past to ensure global values were not created accidentally, an Immediately Invoked Function Expression (IIFE) had to be used:
function printErrorOnly(callback) { // Errors should be handled in a direct way, but this is just for // demonstration purposes. try { callback(); } catch(e) { console.log(e); } } (function() { var a = 1; let b = 2; const c = 3; console.log(a, b, c); // 1 2 3 })(); printErrorOnly(() => a); // ReferenceError: a is not defined... printErrorOnly(() => b); // ReferenceError: b is not defined... printErrorOnly(() => c); // ReferenceError: c is not defined...
Using an Arrow Function will also work. Now with let and const a block can be used because they only exist in that block (block scoped):
{ var a = 1; let b = 2; const c = 3; console.log(a, b, c); // 1 2 3 }; printErrorOnly(() => a); // (no message and no error) printErrorOnly(() => b); // ReferenceError: b is not defined... printErrorOnly(() => c); // ReferenceError: c is not defined...
A much simpler syntax. But note how the var was leaked since it is not block scoped. In the vast majority of cases let or const can be used in place of var, so a simple block will work to provide isolation. Though for libraries that wrap unknown code (e.g. Webpack) or legacy code, IIFEs still need to be used. In the future this will be solved by ES6 Modules which provide their own top level scope.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/iifeReplace.js
11 notes
·
View notes
Video
youtube
JavaScript - ¿Qué es IIFE JavaScript? [IIFE] ➡️ IIFE Es un patrón en JavaScript que ejecuta una función tan pronto como se declara. Esto se conoce como patrón auto ejecutable, y sencillamente hace que una función se ejecute inmediatamente.
0 notes
Text
Website development and choosing a competitive digital agency Cambridge
If you are asking “where can I find the find a new competitive digital agency Cambridge” for my business, I reveal here some practical tips & hints to help you discover the best agency for your new website requirements.
Web programming, also known as web development, is the creation of dynamic web applications. Examples of web applications are social networking sites like Facebook or e-commerce sites like Amazon. Some of those applications have most of their logic living on a web server which renders HTML, CSS, and JavaScript to create an application.
Website development refers to the work that goes into building a website. This could apply to anything from creating a single plain-text webpage to developing a complex web application or social network. While every website is built slightly differently, there are a few fundamental components that handle every interaction between a user and the site.
Today no business can function without a web presence and website Development is a very basic requirement for any global company’s success and a great way to keep a personal recommendation to client. Web site Development makes a website more attractive that help to grow your business. Other applications only utilise the server to create their initial state, download the logic to run the application, and then use the server only to retrieve and store data.
Iif you are looking for free advice on how to discover the most competitive for website development, this exclusive article should reveal some practical and cheapest advice.
1 note
·
View note
Text
Svelte + Tailwind + Storybook Starter Template
First of all, here's the link to the Github repo, go ahead and start working on your project than fiddle with the configurations. Trust me that takes a hell lot of time.
Visit this website to see the outcome: Svelte + TailwindCSS + Storybook
// Quickstart npx degit jerriclynsjohn/svelte-storybook-tailwind my-svelte-project cd my-svelte-project yarn yarn dev yarn stories
Svelte and TailwindCSS is an awesome combination for Frontend development, but sometimes the setup seems a bit non intuitive, especially when trying to try out this awesome combination. When integrating Storybook, which is another awesome tool for UI Component development and documentation, there is no obvious place to get how it's done. This repo was made to address just that!
You can easily start your project with this template, instead of wasting time figuring out configurations for each integration.
What do you get in this repo
A fully functional Svelte + TailwindCSS integration with side-by-side implementation of independent Storybook
Storybook with 5 essential Addons
Storybook populated with basic examples of Svelte + TailwindCSS
Addons
Accessibility Addon
Accessibility Addon - Colorblindness Emulation
Actions Addon
Notes Addon
Source Addon
Viewport Addon
Svelte + TailwindCSS + Storybook
Storybook is an open source tool for developing JavaScript UI components in isolation
Svelte is a component framework that allows you to write highly-efficient, imperative code, that surgically updates the DOM to maintain performance.
TailwindCSS is a highly customizable, low-level CSS framework that gives you all of the building blocks you need to build bespoke designs without any annoying opinionated styles you have to fight to override.
Steps to build
Clone this repo git clone https://github.com/jerriclynsjohn/svelte-storybook-tailwind.git
Go to the directory cd svelte-storybook-tailwind
Install dependencies yarn
To develop your Svelte App: yarn dev
To develop UI components independent of your app: yarn stories
Documentations
Svelte - API and Tutorial
TailwindCSS - Docs and Tutorial
Storybook - Docs and Tutorial (No Svelte Yet!)
Steps to build it all by yourself and some tips [Warning: It's lengthy]
Instantiate Svelte App
Start the template file using npx degit sveltejs/template svelte-storybook-tailwind
Go to the directory cd svelte-storybook-tailwind
Install dependencies yarn
Try run the svelte app yarn dev
Add Tailwind into the project
Install dependencies: yarn add -D tailwindcss @fullhuman/postcss-purgecss autoprefixer postcss postcss-import svelte-preprocess
Change the rollup config as shown:
import svelte from 'rollup-plugin-svelte'; import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import livereload from 'rollup-plugin-livereload'; import { terser } from 'rollup-plugin-terser'; import postcss from 'rollup-plugin-postcss'; import autoPreprocess from 'svelte-preprocess'; const production = !process.env.ROLLUP_WATCH; export default { input: 'src/main.js', output: { sourcemap: true, format: 'iife', name: 'app', file: 'public/bundle.js', }, plugins: [ svelte({ preprocess: autoPreprocess({ postcss: true, }), // enable run-time checks when not in production dev: !production, // we'll extract any component CSS out into // a separate file — better for performance css: css => { css.write('public/bundle.css'); }, }), postcss({ extract: 'public/utils.css', }), // If you have external dependencies installed from // npm, you'll most likely need these plugins. In // some cases you'll need additional configuration — // consult the documentation for details: // https://github.com/rollup/rollup-plugin-commonjs resolve({ browser: true, dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/'), }), commonjs(), // Watch the `public` directory and refresh the // browser on changes when not in production !production && livereload('public'), // If we're building for production (npm run build // instead of npm run dev), minify production && terser(), ], watch: { clearScreen: false, }, };
Add tailwind config using the command npx tailwind init
Add PostCSS config ./postcss.config.js as follows:
const production = !process.env.ROLLUP_WATCH; const purgecss = require('@fullhuman/postcss-purgecss'); module.exports = { plugins: [ require('postcss-import')(), require('tailwindcss'), require('autoprefixer'), production && purgecss({ content: ['./**/*.html', './**/*.svelte'], defaultExtractor: content => { const regExp = new RegExp(/[A-Za-z0-9-_:/]+/g); const matchedTokens = []; let match = regExp.exec(content); // To make sure that you do not lose any tailwind classes used in class directive. // https://github.com/tailwindcss/discuss/issues/254#issuecomment-517918397 while (match) { if (match[0].startsWith('class:')) { matchedTokens.push(match[0].substring(6)); } else { matchedTokens.push(match[0]); } match = regExp.exec(content); } return matchedTokens; }, }), ], };
Build the project with some TailwindCSS utilities yarn dev
Add Storybook into the Svelte Project
Add Storybook dependencies yarn add -D @storybook/svelte
Add 5 commonly used Storybook Addons:
Source: yarn add -D @storybook/addon-storysource
Actions: yarn add -D @storybook/addon-actions
Notes: yarn add -D @storybook/addon-notes
Viewport: yarn add -D @storybook/addon-viewport
Accessibility: yarn add @storybook/addon-a11y --dev
Create an addon file at the root .storybook/addons.js with the following content and keep adding additional addons in this file.
import '@storybook/addon-storysource/register'; import '@storybook/addon-actions/register'; import '@storybook/addon-notes/register'; import '@storybook/addon-viewport/register'; import '@storybook/addon-a11y/register';
Create a config file at the root .storybook/config.js with the following content:
import { configure, addParameters, addDecorator } from '@storybook/svelte'; import { withA11y } from '@storybook/addon-a11y'; // automatically import all files ending in *.stories.js const req = require.context('../storybook/stories', true, /\.stories\.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } configure(loadStories, module); addDecorator(withA11y); addParameters({ viewport: { viewports: newViewports } });
Add tailwind configs in the webpack.config.js under .storybook and also accommodate for Source addon:
const path = require('path'); module.exports = ({ config, mode }) => { config.module.rules.push( { test: /\.css$/, loaders: [ { loader: 'postcss-loader', options: { sourceMap: true, config: { path: './.storybook/', }, }, }, ], include: path.resolve(__dirname, '../storybook/'), }, //This is the new block for the addon { test: /\.stories\.js?$/, loaders: [require.resolve('@storybook/addon-storysource/loader')], include: [path.resolve(__dirname, '../storybook')], enforce: 'pre', }, ); return config; };
Create the postcss.config.js under .storybook:
var tailwindcss = require('tailwindcss'); module.exports = { plugins: [ require('postcss-import')(), tailwindcss('./tailwind.config.js'), require('autoprefixer'), ], };
Make sure you have babel and svelte-loader dependencies yarn add -D babel-loader @babel/core svelte-loader
Add npm script in your package.json
{ "scripts": { // Rest of the scripts "stories": "start-storybook", "build-stories": "build-storybook" } }
Add a utils.css file under storybook/css/ and make sure you import 'utils.css' in your stories.js files:
/* Import Tailwind as Global Utils */ @import 'tailwindcss/base'; @import 'tailwindcss/components'; @import 'tailwindcss/utilities';
Write your Svelte component in storybook\components and yes you can use your regular .svelte file. The only thing is that you cant use templates in a story yet, not supported, but yes you can compose other components together. For the starter pack lets just create a clickable button.
<script> import { createEventDispatcher } from 'svelte'; export let text = ''; const dispatch = createEventDispatcher(); function onClick(event) { dispatch('click', event); } </script> <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" on:click={onClick}> {text} </button>
Write your stories in storybook/stories and you can name any number of story file with <anything>.stories.js, for the starter package we can create stories of Button with the readme notes at <anything>.stories.md. Note: reference the css here to make sure that tailwind is called by postcss:
import '../../css/utils.css'; import { storiesOf } from '@storybook/svelte'; import ButtonSimple from '../../components/buttons/button-simple.svelte'; import markdownNotes from './buttons.stories.md'; storiesOf('Buttons | Buttons', module) //Simple Button .add( 'Simple', () => ({ Component: ButtonSimple, props: { text: 'Button' }, on: { click: action('I am logging in the actions tab too'), }, }), { notes: { markdown: markdownNotes } }, )
Write your own Documentation for the Component which will <anything>.stories.md :
# Buttons _Examples of building buttons with Tailwind CSS._ --- Tailwind doesn't include pre-designed button styles out of the box, but they're easy to build using existing utilities. Here are a few examples to help you get an idea of how to build components like this using Tailwind.
Run your storyboard yarn stories and you'll see this:
You can add more addons and play around with them.
That's a wrap!
#template#storybook#svelte#tailwindcss#ui#component#frontend#webdevelopment#postcss#purgecss#autoprefixer#node#javascript#css#html5
2 notes
·
View notes
Video
youtube
IIFE in JavaScript | JavaScript IIFE | JavaScript IIFE in Hindi | IIFE क...
Follow us for more such interview questions: https://www.tumblr.com/blog/view/programmingpath
Visit On: Youtube: https://youtu.be/Qu_MH-qKL2k Website: http://programmingpath.in
#javascript #javascript_in_hindi #javascript_interview #interview_question #programming_path #interview #programming_interview_question #interviewquestions #top_javascript_interview_question #best_javascript_interview_question #programming
1 note
·
View note
Text
JavaScript Immediately-invoked Function Expressions (IIFE) - CodeSolutionStuff
#artificial intelligence#Programming#php#cloud#machine learning#laravel#JavaScript#DataScience#MachineLearning#Analytics#AI#ML#angular#Tech#Python#ReactJS#DataScientist#Coding#SQL#bot#Cloud#Typescript#Github#Data#BigData#DL#machinelearning
0 notes