<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dev Khatri on Medium]]></title>
        <description><![CDATA[Stories by Dev Khatri on Medium]]></description>
        <link>https://medium.com/@devdecodes?source=rss-d50d3ebd404f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4CcleCg-61H8c6mir8Y97A@2x.jpeg</url>
            <title>Stories by Dev Khatri on Medium</title>
            <link>https://medium.com/@devdecodes?source=rss-d50d3ebd404f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 17 May 2026 12:22:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devdecodes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[You’re Not Lazy. Your Brain Is Addicted to Easy Dopamine.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://devdecodes.medium.com/youre-not-lazy-your-brain-is-addicted-to-easy-dopamine-808130cb7ca4?source=rss-d50d3ebd404f------2"><img src="https://cdn-images-1.medium.com/max/2000/0*EWrRtEz2roGboBNW" width="2000"></a></p><p class="medium-feed-snippet">How constant stimulation is quietly destroying your focus &#x2014; and what actually works to fix it.</p><p class="medium-feed-link"><a href="https://devdecodes.medium.com/youre-not-lazy-your-brain-is-addicted-to-easy-dopamine-808130cb7ca4?source=rss-d50d3ebd404f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://devdecodes.medium.com/youre-not-lazy-your-brain-is-addicted-to-easy-dopamine-808130cb7ca4?source=rss-d50d3ebd404f------2</link>
            <guid isPermaLink="false">https://medium.com/p/808130cb7ca4</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[focus]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[dopamine]]></category>
            <dc:creator><![CDATA[Dev Khatri]]></dc:creator>
            <pubDate>Sat, 02 May 2026 11:49:35 GMT</pubDate>
            <atom:updated>2026-05-02T11:53:06.683Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Redux Simplified: Understand Redux the Easy Way]]></title>
            <link>https://devdecodes.medium.com/redux-simplified-understand-redux-the-easy-way-d5b52cf16dfb?source=rss-d50d3ebd404f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5b52cf16dfb</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react-state-management]]></category>
            <dc:creator><![CDATA[Dev Khatri]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 06:40:57 GMT</pubDate>
            <atom:updated>2025-06-20T07:00:25.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is redux toolkit in react<strong>: Understand the Easy Way</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KeDX1yLpkedudP2d" /><figcaption>Photo by <a href="https://unsplash.com/@ilchben?utm_source=medium&amp;utm_medium=referral">Benjamin Ilchmann</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Redux Toolkit with simple analogy</h4><p>At my home (the App), we have a storeroom — this is our Redux store, where all important things are kept.</p><p>One day, my kids went there to play and dropped something — that’s an action (something happened in the app).</p><p>I, as a parent, heard the disturbance — this represents how the system becomes aware that a change occurred.</p><p>I rushed to the storeroom to see what happened and noticed,some bottles had fallen down, a few were broken, some were still intact</p><p>I asked my maid to clean up the mess and rearrange things (dispatch an action), buy new bottles from the market if needed (async thunk for async logic like API calls)</p><p>Once she got everything, I asked her to arrange the bottles back properly — that’s what a reducer does: cleanly update the state based on what happened.</p><p>When building complex React applications, managing state becomes a challenge. This is where Redux shines — offering a predictable state container that makes large-scale app development easier to manage and debug. In this post, we’ll cover the fundamentals of Redux, its principles, key concepts, and a practical guide to getting started with Redux Toolkit.</p><h4><strong>Why Redux?</strong></h4><p>Redux is built around a simple idea:</p><blockquote><em>Maintain a single centralized place for your application state and follow strict patterns to update it.</em></blockquote><p>This makes state predictable, easy to test, and easier to debug — even enabling time-travel debugging.</p><h4><strong>One-Way Data Flow</strong></h4><p>React and Redux both rely on one-way data flow. State is read from the store and updated by dispatching actions. All updates must happen immutably, ensuring past states are preserved.</p><h4><strong>Core Principles of Redux</strong></h4><p>Redux is based on three principles:</p><p>Single Source of Truth- All application state is stored in a single JavaScript object — the store.</p><p>State is Read-Only- The only way to change the state is by dispatching actions — plain objects that describe what happened.</p><p>Changes via Pure Functions- Updates are handled by pure functions called reducers. This ensures the update logic is testable, predictable, and doesn’t cause side effects.</p><h4><strong>Redux Terminology Explained</strong></h4><p>Let’s break down the building blocks of Redux:</p><h4>1. Store</h4><p>The central object that holds the entire state tree of your app.</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>const store = configureStore({ reducer: rootReducer })</pre><h4><strong>2. Action</strong></h4><p>A plain object that describes <em>what happened</em>.</p><pre>const addTodoAction = {<br>  type: &quot;todos/todoAdded&quot;,<br>  payload: &quot;Buy milk&quot;<br>}</pre><h4><strong>3. Action Creator</strong></h4><p>A function that returns an action object.</p><pre>const addTodo = text =&gt; ({<br>  type: &quot;todos/todoAdded&quot;,<br>  payload: text<br>})</pre><h4><strong>4. Dispatch</strong></h4><p>Used to send actions to the store.</p><pre>store.dispatch(addTodo(&quot;Buy milk&quot;))</pre><h4><strong>5. Reducer</strong></h4><p>A pure function that decides how the state should change based on the action.</p><pre>function todosReducer(state = [], action) {<br>  switch (action.type) {<br>    case &quot;todos/todoAdded&quot;:<br>      return [...state, { text: action.payload }]<br>    default:<br>      return state<br>  }<br>}</pre><h4><strong>6. Selector</strong></h4><p>A function to extract specific pieces of state.</p><pre>const selectTodos = state =&gt; state.todos</pre><h4><strong>7. Provider</strong></h4><p>Wraps your app and provides access to the Redux store.</p><pre>&lt;Provider store={store}&gt;<br>  &lt;App /&gt;<br>&lt;/Provider&gt;</pre><h4><strong>What Are Redux Slices?</strong></h4><p>Redux logic is typically split into slices — modular files for managing state and logic for a particular feature.</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;<br>const todosSlice = createSlice({<br>  name: &#39;todos&#39;,<br>  initialState: [],<br>  reducers: {<br>    todoAdded: (state, action) =&gt; {<br>      state.push({ text: action.payload })<br>    }<br>  }<br>})<br>export const { todoAdded } = todosSlice.actions<br>export default todosSlice.reducer</pre><blockquote><em>Redux Toolkit uses Immer internally, so you can write “mutable” code that stays immutable under the hood.</em></blockquote><h4><strong>Async Logic: Thunks and createAsyncThunk</strong></h4><p>Sometimes, you need to make async API calls. Redux Toolkit offers createAsyncThunk:</p><pre>import { createAsyncThunk } from &#39;@reduxjs/toolkit&#39;<br>export const fetchPosts = createAsyncThunk(<br>  &#39;posts/fetchPosts&#39;,<br>  async () =&gt; {<br>    const response = await fetch(&#39;/api/posts&#39;)<br>    return response.json()<br>  }<br>)</pre><p>In your slice:</p><pre>extraReducers: builder =&gt; {<br>  builder<br>    .addCase(fetchPosts.pending, state =&gt; { state.status = &#39;loading&#39; })<br>    .addCase(fetchPosts.fulfilled, (state, action) =&gt; {<br>      state.status = &#39;succeeded&#39;<br>      state.posts = action.payload<br>    })<br>    .addCase(fetchPosts.rejected, state =&gt; { state.status = &#39;failed&#39; })<br>}</pre><h4><strong>Optional Enhancements</strong></h4><ul><li>Prepare Callbacks — Preprocess actions before reducer logic (e.g., assigning unique IDs).</li><li>extraReducers — Listen to actions outside of this slice (e.g., logout action to reset state).</li></ul><h4><strong>Redux vs RTK Query</strong></h4><p>Redux Toolkit Query (RTK Query) is a powerful abstraction built on top of Redux. It simplifies:</p><ul><li>Data fetching</li><li>Caching</li><li>Auto re-fetching</li><li>Mutation handling</li></ul><p>If your Redux use case is mainly API-driven, RTK Query might be all you need.</p><h4><strong>High level Implementation notes</strong></h4><ul><li>Create a slice for your feature and export the reducer</li><li>Add the reducer to the store during configuration</li><li>Provide the store to your app using &lt;Provider&gt;</li><li>In your component: useSelector to read state, useDispatch to trigger updates</li></ul><p>Redux can look intimidating at first, but with Redux Toolkit, the boilerplate is dramatically reduced, and the structure becomes intuitive. By mastering slices, thunks, and the core concepts, you’ll be able to manage even the most complex state logic in your React applications.</p><p>Check out the official Redux Toolkit <a href="https://redux.js.org/">documentation </a>for real-world examples and best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5b52cf16dfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React Applications with Vitest: A Practical Guide]]></title>
            <link>https://devdecodes.medium.com/testing-react-applications-with-vitest-a-practical-guide-3cc90cb93048?source=rss-d50d3ebd404f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cc90cb93048</guid>
            <category><![CDATA[vites]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[vitest-in-react-guide]]></category>
            <category><![CDATA[vitest]]></category>
            <category><![CDATA[react-vitest-tutorial]]></category>
            <dc:creator><![CDATA[Dev Khatri]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 12:38:24 GMT</pubDate>
            <atom:updated>2025-06-14T12:38:24.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0ze7cTLNlYJczXMP" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vitest is a fast, lightweight, and modern testing framework designed for Vite-based projects. It provides a seamless testing experience with built-in support for TypeScript, mocking, and React components. In this blog, we’ll explore how Vitest is used in a React + Vite project and highlight some key features that makes it stand out.</p><h4>Setting Up Vitest</h4><p>The package.json file includes Vitest as a development dependency and a script to run tests:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;vitest&quot;<br>},<br>&quot;devDependencies&quot;: {<br>  &quot;vitest&quot;: &quot;^3.2.3&quot;,<br>  &quot;@testing-library/react&quot;: &quot;^16.3.0&quot;,<br>  &quot;@testing-library/jest-dom&quot;: &quot;^6.6.3&quot;,<br>  &quot;@testing-library/user-event&quot;: &quot;^14.6.1&quot;<br>}</pre><p>To install Vitest and related testing libraries, run:</p><p>npm install vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event --save-dev</p><h4>Writing a Simple Test</h4><p>An example of a test for a Results component using Vitest and Testing Library:</p><pre>import { render, screen } from &#39;@testing-library/react&#39;;<br>import { describe, it, expect } from &#39;vitest&#39;;<br>import Results from &#39;../../src/poll/Results&#39;;<br>describe(&#39;Results Component&#39;, () =&gt; {<br>  it(&#39;renders the results component correctly&#39;, () =&gt; {<br>    render(&lt;Results data={{}} showResult={false} totalVotes={0} /&gt;);<br>    const resultText = screen.queryByTestId(&#39;result-text&#39;);<br>    expect(resultText).toBeInTheDocument();<br>    expect(resultText).toHaveTextContent(&#39;yet to start..&#39;);<br>  });<br>});</pre><p>describe: Groups related tests</p><p>it: Defines an individual test case</p><p>expect: Asserts the expected behavior</p><h4>Mocking Data</h4><p>Mocking data is essential for testing components in isolation. Vitest makes it easy to mock data and external dependencies.</p><pre>export default {<br>  noVotes: {<br>    options: [],<br>  },<br>  withVotes: {<br>    options: [<br>      { text: &#39;Option A&#39;, votes: 5 },<br>      { text: &#39;Option B&#39;, votes: 3 },<br>    ],<br>  },<br>};</pre><p>You can use this mock data in your tests:</p><pre>import mockData from &#39;./mockData&#39;;</pre><pre>it(&#39;shows winning text when votes are present&#39;, () =&gt; {<br>  render(&lt;Results data={mockData.withVotes} showResult={true} totalVotes={8} /&gt;);<br>  const resultText = screen.queryByTestId(&#39;result-text&#39;);<br>  expect(resultText).toHaveTextContent(&#39;Option A is winning by 2 votes&#39;);<br>});</pre><h4>Testing User Interactions</h4><p>Vitest works seamlessly with @testing-library/user-event to simulate user interactions.</p><pre>import userEvent from &#39;@testing-library/user-event&#39;;<br><br>it(&#39;shows the final result when the button is clicked&#39;, async () =&gt; {<br>  render(&lt;Results data={mockData.withVotes} showResult={false} totalVotes={8} /&gt;);<br>  const button = screen.getByTestId(&#39;result-btn&#39;);<br>  expect(button).not.toBeDisabled();<br>  await userEvent.click(button);<br>  const resultText = await screen.findByTestId(&#39;result-text&#39;);<br>  expect(resultText).toHaveTextContent(&#39;Option A is the winner&#39;);<br>});</pre><h4>Running Tests</h4><p>To run your tests, use the test script:</p><p>npm run test</p><h4>Mocking Modules</h4><p>Vitest allows you to mock modules for testing purposes. For example, you can mock an API call:</p><pre>import { vi } from &#39;vitest&#39;;<br>vi.mock(&#39;../../src/api&#39;, () =&gt; ({<br>  fetchData: vi.fn(() =&gt; Promise.resolve({ data: &#39;mocked data&#39; })),<br>}));</pre><h4>Debugging Tests</h4><p>You can debug your tests by inspecting the rendered DOM using screen.debug():</p><pre>render(&lt;Results data={mockData.noVotes} showResult={false} totalVotes={0} /&gt;);<br>screen.debug();</pre><p>This outputs the current DOM structure to the console, helping you identify issues.</p><h4>Coverage Reports</h4><p>Vitest can generate code coverage reports to ensure your tests cover all critical parts of your application. Add the — coverage flag:</p><p>npx vitest --coverage</p><p>This generates a detailed report showing which lines of code are covered by your tests.</p><p>Vitest is a game-changer for testing modern React applications. Its speed, simplicity, and seamless integration with Vite make it an excellent choice for developers. By combining Vitest with Testing Library, you can write robust, user-focused tests that ensure your application works as expected.</p><h4>How They Work Together</h4><p>Vitest: Handles running the tests, mocking modules, and generating reports.</p><p>React Testing Library: Provides utilities to test React components in a way that mimics how users interact with the app.</p><p>Here’s how Vitest and React Testing Library work together in a test:</p><pre>import { render, screen } from &#39;@testing-library/react&#39;;<br>import userEvent from &#39;@testing-library/user-event&#39;;<br>import { describe, it, expect } from &#39;vitest&#39;;<br>import Results from &#39;../../src/poll/Results&#39;;<br>describe(&#39;Results Component&#39;, () =&gt; {<br>  it(&#39;shows the final result when the button is clicked&#39;, async () =&gt; {<br>    render(&lt;Results data={{ options: [{ text: &#39;Option A&#39;, votes: 5 }] }} showResult={false} totalVotes={5} /&gt;);<br>    <br>    const button = screen.getByTestId(&#39;result-btn&#39;);<br>    expect(button).not.toBeDisabled();<br>    await userEvent.click(button);<br>    const resultText = await screen.findByTestId(&#39;result-text&#39;);<br>    expect(resultText).toHaveTextContent(&#39;Option A is the winner&#39;);<br>  });<br>});</pre><p>In this example:</p><p>Vitest: Runs the test and provides the describe, it, and expect functions. React Testing Library: Handles rendering the component and simulating user interaction</p><h4>Conclusion</h4><p>Vitest and React Testing Library are not competitors but complementary tools. Vitest focuses on running and organizing tests, while React Testing Library ensures that your tests are user-centric. Together, they provide a powerful testing setup for modern React applications.</p><p>You can find the complete source code on <a href="https://github.com/khatridev/vite-vote-vitest">GitHub</a>. It includes all the examples and tests used in this blog.</p><p>If you found this useful, feel free to ⭐️ or contribute with improvements</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cc90cb93048" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Modular Web Apps with Vanilla JavaScript — No Frameworks Needed]]></title>
            <link>https://devdecodes.medium.com/building-modular-web-apps-with-vanilla-javascript-no-frameworks-needed-631710bae703?source=rss-d50d3ebd404f------2</link>
            <guid isPermaLink="false">https://medium.com/p/631710bae703</guid>
            <category><![CDATA[vanillajs]]></category>
            <category><![CDATA[modular]]></category>
            <category><![CDATA[simple-modular-js]]></category>
            <category><![CDATA[dom-with-pure-js]]></category>
            <category><![CDATA[modular-vanilla-js]]></category>
            <dc:creator><![CDATA[Dev Khatri]]></dc:creator>
            <pubDate>Mon, 26 May 2025 18:29:59 GMT</pubDate>
            <atom:updated>2025-05-26T18:29:59.839Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Modular Web Apps with Vanilla JavaScript — No Frameworks Needed</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZadR8xk-7OY-Nco-" /><figcaption>Photo by <a href="https://unsplash.com/@dmitriielj?utm_source=medium&amp;utm_medium=referral">Dmitrii E.</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In today’s web development world, frameworks like React, Vue, and Angular dominate the landscape — offering structure, reusability, and separation of concerns. But what if you could apply those same principles without relying on any external libraries or dependencies?</p><p>In this article, we will see how to structure a web application using <strong>modular, reusable components</strong> in pure, vanilla JavaScript. By embracing clean architecture and focusing on maintainable code.</p><p>Whether you’re learning JavaScript, building a lightweight project, or simply exploring how things work under the hood, this approach gives you a solid foundation for writing scalable, organized frontend code — all while keeping things dependency-free.</p><p><strong>Key Concepts</strong></p><h4>1. Components</h4><p>A component is a function that receives data (props) and returns a DOM element or fragment. This makes the component:</p><ul><li><strong>Reusable</strong>: Can be used in multiple places with different data.</li><li><strong>Isolated</strong>: Has no side effects or dependencies on global state.</li></ul><pre>// A generic component function<br>function createComponent(data) {<br>  const element = document.createElement(&#39;div&#39;);<br>  // ...populate element based on data...<br>  return element;<br>}</pre><h4>2. Views</h4><p>A <strong>view</strong> is a higher-level structure that organizes and renders multiple components to form a complete section or page of the application. Views:</p><ul><li><strong>Compose components:</strong> Use one or more components to build complex UIs.</li><li><strong>Handle layout:</strong> Define the structure and placement of components.</li><li><strong>Manage rendering:</strong> Often responsible for fetching data and updating the DOM.</li></ul><pre>function renderMainView(data) {<br>  const main = document.createElement(&#39;main&#39;);<br>  data.items.forEach(item =&gt; {<br>    const component = createComponent(item);<br>    main.appendChild(component);<br>  });<br>  return main;<br>}</pre><h4>3. Importing and Using Components</h4><p>Components and views are defined in separate modules/files and imported where needed. This keeps code organized and encourages reuse.</p><pre>import { renderMainView } from &#39;./views/mainView.js&#39;;<br><br>fetch(&#39;/api/data&#39;)<br>  .then(response =&gt; response.json())<br>  .then(data =&gt; {<br>    const app = document.getElementById(&#39;app&#39;);<br>    app.appendChild(renderMainView(data));<br>});</pre><h4>4. Stateless and Pure</h4><p>Components should avoid side effects and only use the data passed to them. This makes them predictable and easy to test.</p><ul><li><strong>Predictable</strong>: Easy to understand and reason about.</li><li><strong>Testable</strong>: Simple to verify with unit tests.</li></ul><h4>Conclusion</h4><p>By following these patterns, we can build scalable, maintainable, and reusable UI components in vanilla JavaScript.</p><p><strong>Example Project</strong>: Check out a reference implementation here: <a href="https://github.com/khatridev/match-opponent">khatridev/match-opponent</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631710bae703" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving from Create React App to Vite]]></title>
            <link>https://devdecodes.medium.com/moving-from-create-react-app-to-vite-0967c9bd7c68?source=rss-d50d3ebd404f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0967c9bd7c68</guid>
            <category><![CDATA[migrate-from-cra-to-vite]]></category>
            <category><![CDATA[react-app-to-vite]]></category>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[vitejs]]></category>
            <dc:creator><![CDATA[Dev Khatri]]></dc:creator>
            <pubDate>Mon, 20 Jan 2025 07:56:19 GMT</pubDate>
            <atom:updated>2025-01-20T09:21:35.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qu3rZKC-cjlIrWX5" /></figure><p>As a developer, I often found myself falling into the trap of endless scrolling on my phone while waiting for my React app to build using Create React App (CRA). The long build times would often pull me away from my laptop by the time the UI finally loaded in the browser. I know many developers can relate to this challenge.</p><p>Then one day, while researching solutions for React projects, I discovered <strong>Vite</strong> —pronounced /vit/</p><p>My excitement hit a brief pause when I realized I needed to update my existing Create React App (CRA) project to use Vite. The task seemed daunting at first, but I knew the switch was worth it.</p><p>I considered two options:</p><ol><li><strong>Create a new Vite project</strong> and migrate all the code into it. While straightforward, this approach felt too easy and involved recreating configurations from scratch.</li><li><strong>Integrate Vite configurations into my existing project.</strong></li></ol><p>I chose the second path. It allowed me to keep my existing setup intact while smoothly transitioning to Vite. This approach not only made the migration more seamless but also ensured both my codebase and I felt “comfortable” welcoming Vite into the workflow.</p><blockquote>This guide follows the project with js/jsx files</blockquote><p><strong>Step 1: Add new dependencies</strong></p><p>Check package.json of vite project, identify dependencies that are new in the vite project. The most important dependency you will find, <em>@vitejs/plugin-react-swc</em></p><blockquote>SWC is a compiler/transpiler and bundler for Javascript/Typescript, generally it’s faster than other options like babel, tsc, esbuild. It is a super cool topic to deep dive.</blockquote><pre>npm install @vitejs/plugin-react-swc --save-dev<br>npm install vite vite-plugin-commonjs --save-dev<br>npm install typescript @types/node @types/react @types/react-dom --save-dev</pre><p><strong>Step 2: Create vite.config.ts</strong></p><blockquote>treat-js-files-as-jsx <em>is the plugin required if project files are in js and you cannot rename to jsx at the moment</em></blockquote><pre>import { defineConfig, transformWithEsbuild } from &quot;vite&quot;;<br>import react from &quot;@vitejs/plugin-react-swc&quot;;<br>import path from &quot;path&quot;;<br><br><br>export default defineConfig(({ mode }) =&gt; ({<br> optimizeDeps: {<br>  esbuildOptions: {<br>   loader: {<br>    &#39;.js&#39;: &#39;jsx&#39;<br>   }<br>  }<br> },<br> server: {<br>  port: 8080,<br> },<br> plugins: [<br>  {<br>   name: &#39;treat-js-files-as-jsx&#39;,<br>   async transform(code, id) {<br>    if (!id.match(/src\/.*\.js$/)) return null; // include ts or tsx for TypeScript support <br>    // Use the exposed transform from vite, instead of directly<br>    // transforming with esbuild<br>    return transformWithEsbuild(code, id, {<br>     loader: &#39;jsx&#39;,<br>     jsx: &#39;automatic&#39;,<br>    });<br>   },<br>  },<br>  react()<br> ].filter(Boolean),<br> resolve: {<br>  alias: {<br>   &quot;@&quot;: path.resolve(__dirname, &quot;./src&quot;),<br>  },<br> },<br>}));</pre><blockquote>update custom path for resolve.alias, if any</blockquote><p><strong>Step 3: Create vite-env.d.ts file</strong></p><pre>// vite-env.d.ts<br>/// &lt;reference types=&quot;vite/client&quot; /&gt;</pre><p><strong>Step 4: Modify index.html</strong></p><p>Move index html from public folder to the root folder and modify the references with %PUBLIC_URL%.</p><p>Add script tag to refer to the main file.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>    &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt;<br>    &lt;meta<br>      name=&quot;description&quot;<br>      content=&quot;Web site created using create-react-app&quot;<br>    /&gt;<br>    &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;/logo192.png&quot; /&gt;<br>    <br>    &lt;link rel=&quot;manifest&quot; href=&quot;/manifest.json&quot; /&gt;<br>   <br>    &lt;title&gt;React App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>    <br>    &lt;script type=&quot;module&quot; src=&quot;/src/index.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Step 5: Uninstall react-scripts</strong></p><pre>npm uninstall react-scripts</pre><p>Update scripts in package.json</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;vite&quot;,<br>  &quot;build&quot;: &quot;vite build&quot;,<br>  &quot;serve&quot;: &quot;vite preview&quot;<br>},</pre><p><strong>Step 6: Run the application</strong></p><pre>npm start</pre><p>I found improvement in the development and build process and in the phone battery as well :)</p><p><strong>Following are list of issue and their fixes that could help,</strong></p><blockquote>if you see white screen after running the app, make sure index.html has the script tag for src/index.js (the root file)</blockquote><blockquote><em>Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.</em></blockquote><pre>import { defineConfig, transformWithEsbuild } from &quot;vite&quot;;<br>import react from &quot;@vitejs/plugin-react-swc&quot;;<br>import path from &quot;path&quot;;<br><br><br>export default defineConfig(({ mode }) =&gt; ({<br> optimizeDeps: {<br>  esbuildOptions: {<br>   loader: {<br>    &#39;.js&#39;: &#39;jsx&#39;<br>   }<br>  }<br> },<br> server: {<br>  port: 8080,<br> },<br> plugins: [<br>  {<br>   name: &#39;treat-js-files-as-jsx&#39;,<br>   async transform(code, id) {<br>    if (!id.match(/src\/.*\.js$/)) return null;// include ts or tsx for TypeScript support <br><br>    // Use the exposed transform from vite, instead of directly<br>    // transforming with esbuild<br>    return transformWithEsbuild(code, id, {<br>     loader: &#39;jsx&#39;,<br>     jsx: &#39;automatic&#39;,<br>    });<br>   },<br>  },<br>  react()<br> ].filter(Boolean),<br> resolve: {<br>  alias: {<br>   &quot;@&quot;: path.resolve(__dirname, &quot;./src&quot;),<br>  },<br> },<br>}));</pre><blockquote>Uncaught ReferenceError: global is not defined</blockquote><pre>export default defineConfig({<br>  <br>  define: {<br>    // By default, Vite doesn&#39;t include shims for NodeJS/<br>    // necessary for segment analytics lib to work<br>    global: {},<br>  },<br>})</pre><blockquote>Uncaught ReferenceError: process is not defined</blockquote><pre>import { defineConfig } from &#39;vite&#39;<br>// ...<br>export default defineConfig({<br>  // ...<br>  define: {<br>    &#39;process.env&#39;: {}<br>  }<br>})</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0967c9bd7c68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>