Leonard  Paucek

Leonard Paucek

1675071360

Overengineered todo List with Vue3, Vite, Pinia and Typescript

todo - Overengineered todo list with Vue3, Vite, Pinia and Typescript

Live Demo: https://todo-ar363.vercel.app/

demo.gif

Features

  • CI/CD Pipeline configured
  • End to End testing with Cypress
  • Fully type safe stores with Pinia
  • Works offline with localStorage
  • Looks nice

Recommended IDE Setup

VSCode + Volar (and disable Vetur) + TypeScript Vue Plugin (Volar).

Project Setup

npm install

Compile and Hot-Reload for Development

npm run dev

Type-Check, Compile and Minify for Production

npm run build

Run End-to-End Tests with Cypress

npm run test:e2e:dev

This runs the end-to-end tests against the Vite development server. It is much faster than the production build.

But it's still recommended to test the production build with test:e2e before deploying (e.g. in CI environments):

npm run build
npm run test:e2e

Lint with ESLint

npm run lint

Download details:

Author: ar363
Source code: https://github.com/ar363/todolist-vue-ts

#vue #typescript #vite 

Overengineered todo List with Vue3, Vite, Pinia and Typescript
Leonard  Paucek

Leonard Paucek

1674537300

Localization Example Web Application using Vite and React

Localization Example

Introduction

Localization Example web application is created by using Vite & React.

This is a simple example of how to localize a single website into multiple languages. A user can select between English, Spanish, and Japanese by clicking a corresponding button.

It is designed and structured in a way it's easy to scale up as needed. Please read the how to use section to add more languages and/or texts.

This example was created to accompany my Tech Talk sponsored by JEENEY and Bractlet on Software Localization as an example project.

Please visit this URL to view the website: https://localization-example.netlify.app

Features

This web application lets a user click a button to change all the texts and flag image into English, Spanish, or Japanese. The file structure is setup with scalability in mind. It is simple to add more texts and more languages to expand the page.

Localization-Eng

Localization-SP

Localization-Jp

Files

  • media
    • Localization-End.png
    • Localization-Jp.png
    • Localization-SP.png
  • src
    • assets
      • earth-lg.png
    • languages
      • Eng.jsx
      • Es.jsx
      • Jp.jsx
    • App.css
    • App.jsx
    • index.css
    • main.jsx
    • Translation.jsx
  • .gitignore
  • index.html
  • pacakge-lock.json
  • pacakge.json
  • vite.congig.js
  • README.md

How to use

  • Clone or download this repo
  • npm install to download all the node modules
  • npm run dev to start the application

To add more languages, follow these steps:

  1. Create a new jsx file in languages folder and create an object with matching key/value pairs with existing languages.
  2. The new language file needs to be imported into Translation.jsx file.
  3. Inside of getTranslations function, add a conditional statement as seen for other languages
  4. In App.jsx, create another button for the added language

References


Download details:

Author: cheesehero112
Source code: https://github.com/cheesehero112/Localization-Example

#react-native #react #vite 

Localization Example Web Application using Vite and React

Using Vitest to Effectively Test Your Vite Applications

How to test Vite projects using Vitest

Learn all about how you can use Vitest to effectively test your Vite applications. You will learn how Vitest can:

- Bring testing APIs you’re already familiar with
- Turn a leaning tower of Jest config into a single Vite plugin
- Give near-instant development feedback with the power of ES modules


Testing Vite with minimal config using Vitest 

Vitest is simplifying developer tooling. Why Vitest, and how does it compare to tools like Jest? Let's see why people are talking about it.

Vite’s been taking the world by storm since early 2021. It dramatically simplified developer tooling and became the underpinning of several popular metaframeworks. Now, it’s ready to take over our test suites via Vitest. 

Let’s discuss how Vitest works, compare it with a popular test suite configuration (Jest and Babel), explore the ways Vitest can simplify your test suite config, and examine how the performance gains can speed up your watch mode. 

Table of contents

  • What is Vite?
  • What is Vitest?
  • Vitest’s holistic approach to testing suites: Jest, Babel, and webpack all at once
  • Getting started with Vitest: How does it compare to Jest?
  • Building an example project for Vitest
  • Minimal config with Vitest
  • Testing Vitest’s speed

What is Vite?

Vite’s value proposition has become so broad that it’s hard to pin down. To summarize: Vite is a website bundler that can handle your JavaScript, your CSS, your static assets, and just about anything you load into an HTML document.

Remember Apple’s original value proposition for the iPhone, “An iPod, a phone, an Internet communicator…”? I see Vite as a similar proposition, as it bundles three related tools into one:

How does Vite pull this off? Well, instead of targeting a single main.js file as our website’s entry point, it crawls HTML files to track all JavaScript, styles, and miscellaneous assets you use. This enables Vite to manage the entire build pipeline, including a lightning-quick dev server. 

In development, Vite can intelligently decide what assets actually need to refresh when saving changes to a file. Edit a React component only used on your homepage, for example?

Instead of re-bundling your entire site as webpack might, Vite will send just the single React component over to your browser. It’ll even avoid refreshing the page and keep your state variables intact.

This hot module reloading is Vite’s secret sauce to a positive developer experience, which brings us to Vitest’s core value propositions.

What is Vitest?

Note: Vitest is still not recommended for production use as of February 2022. Check Vitest’s homepage for up-to-date suggestions before using it.

Vitest is a a Vi-testing framework built on top of Vite with an eye for both speed and minimal config. We’ll explore each of these in the following sections.

Vitest’s holistic approach to testing suites: Jest, Babel, and webpack all at once

Vitest’s approach to the testing space is similar to Vite’s approach on the bundling space: let the tool control your entire environment, top to bottom. Vitest is a replacement for a suite of tools:

  • Jest, Mocha, or Chai for test utilities
  • Babel for transpiling ESM, TypeScript, and more
  • webpack or Rollup for bundling test dependencies (if needed)

This means far less config, dependency mismatching, and performance monitoring for you to manage. Just install vitest and let the magic happen. 

Getting started with Vitest: How does it compare to Jest?

Despite Vitest’s sweeping value propositions, its test runner APIs are nearly identical to Jest across the board: describe, expect, it.each, mock functions, spies, concurrent flags for parallel tests… the gang’s all here (full list of APIs)!

In fact, Vitest and Jest are so similar that it’s hardly worth the code sample here. I suggest heading to Vitest’s playground to see the test runner in action. But for completeness, here’s a simple unit test written with Vitest’s APIs:

// example.test.js
import { expect, test } from 'vitest';

test('Math.sqrt()', () => {
  expect(Math.sqrt(4)).toBe(2);
  expect(Math.sqrt(144)).toBe(12);
  expect(Math.sqrt(2)).toBe(Math.SQRT2);
});

If you’re wondering, “Wait, why aren’t those test helpers globally available?” This is just the default. You can make the Vitest package globally available from a configuration file. See the Vitest docs for more information.

If you create this file locally, you can spin up Vitest’s watch mode by running npx vitest. You should see a single Math.sqrt() test with three passing assertions.

Building an example project for Vitest

Simple test cases are fine, but let’s explore some more complex use cases.

I created a full-stack web app using React for the frontend and a Netlify serverless function to handle form requests. I then wrote two test files:

You can explore the full GitHub repo here 

Note these each use a combination of not-so-stock tools: TypeScript, ESM for server and client-side logic, and JSX for the integration test. This should cover a spectrum of popular JavaScript use cases in a single project.

Let’s discuss the speed and config improvements using Jest + Babel as a baseline.

Minimal config with Vitest — from a Babel bonanza to one dependency

TL;DR: Vitest is much easier to configure from scratch than Jest and Babel. Using Vitest is almost a no-brainer if you use Vite already. Even if you don’t, there’s a minimal upfront cost to replicate your Babel build process in a Vite config. Still, if you want your config to be 100% identical to your web app’s, you might lean toward using Jest to piggyback on config.

Alright, let’s talk config. I tried to use the most popular test suite recommendations as a frame of reference: Jest for test utilities and Babel plugins to transpile what Jest doesn’t understand. I also avoided using Jest’s “experimental” flag for ESM because it’s rockier to use at this moment and may have performance implications.

Also, we’re configuring our test suite without considering the app itself. You might have a better time configuring Jest if your website already has a Babel and webpack config (say, CRA). Let’s ignore this for the sake of comparison, though.

Here are all the dev dependencies needed to get our tests running from absolute zero:

{
  "devDependencies": {
    // babel presets for ESM, typescript, and React
    "babel-jest": "^27.5.0",
    "@babel/core": "^7.17.0",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-react": "^7.16.7",
    "@babel/preset-typescript": "^7.16.7",
    // Jest types for global "describe," "it," etc
    "@types/jest": "^27.4.0",
    // Helper to stub out CSS modules when present
    // per Jest docs recommendation
    // https://jestjs.io/docs/webpack#mocking-css-modules
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.5.0",
    "typescript": "^4.4.4"
  }
}

That’s nine dependencies total. Despite using this combo of tools for years, it took nearly an hour of sifting through out-of-date packages and Stack Overflow posts to get here!

Stubbing out CSS modules was particularly thorny. Yes, your mileage will vary here, but I want to note this sticking point for newer devs, especially.

Now, let’s see our dependencies for Vitest:

{
  "devDependencies": {
    "@testing-library/react": "^12.1.2",
    "typescript": "^4.4.4",
    "vitest": "^0.2.7",
    // optional plugin - auto-inject "React" import when it's missing
    "@vitejs/plugin-react": "^1.0.7",
  }
}

We just went from using nine dependencies to four — three, excluding the optional React plugin. We also got it working on the first try from reading Vitest’s docs.

Now, if you’re thinking, “Well sure, but how much config did you have to write,” don’t worry. It gets better.

First, let’s see the necessary config for Jest plus Babel. We’ll need some Jest config to stub out CSS module imports:

// jest.config.js
module.exports = {
  coverageProvider: "v8",
  moduleNameMapper: {
    // stub out CSS imports per Jest's recommendation
    "\\.(css)$": "identity-obj-proxy",
  },
};

As well as a few Babel presets for React and TypeScript:

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}],
    ['@babel/preset-react', {
      "runtime": "automatic"
    }],
    '@babel/preset-typescript',
  ],
};

Now, let’s see the Vitest config. Because Vitest rolls up the testing and code bundling into a single tool, we only need one config file:

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})

Look, there’s no config for TypeScript, CSS modules, environment presets, or the like! That’s because Vite handles this out of the box with sensible defaults that we don’t need to tweak. What’s more, because Vitest simply extends Vite’s capabilities, there’s zero necessary config for existing Vite projects.

Testing Vitest’s speed

I’ll add a disclaimer to this section before we begin: Vitest is still in its early days right now, so there are few benchmarks to speak of beyond this initial exploration from Matti Bar-Zeev. To summarize the findings:

  1. Running in watch mode is much faster than the Jest equivalent
  2. One-off runs, as you might use with automated test runners, were about the same speed

My findings were pretty dang similar.

Results from the example project

I will say this is purely anecdotal evidence. These results are based on my local machine’s performance and will likely vary for those cloning the repo and trying at home. I recommend skeptical early adopters try for themselves, but here are my findings:

  1. Vitest’s live reloading is just plain faster — about 39ms to rerun the suite on a file change versus Jest’s 250ms. The CLI’s console logs do lag a bit, though, making the performance boost more negligible at this smaller scale.
  2. Jest was nearly twice as fast running outside of watch mode — about 1s per run versus Vitest’s 1.88s using vitest run.

Let’s explore why this might be the case.

How is Vitest’s watch mode so quick?

I think Anthony Fu’s Twitter post says it best:

Just like how Vite works in the browser, Vitest also knows the graph of your modules, which makes it able to do smart detection and only rerun the related tests. Feels almost like HMR but for tests

This is the greatest advantage of bundling your dev environment into a single tool. Because Vitest knows every module your app depends on, it can smartly decide which tests should rerun on a file change. This is especially useful in our integration test example.

Whenever we edit our Form.tsx, Vitest can quickly discover which tests rely on this file, re-process it in a flash, and only rerun the related tests. By comparison, I couldn’t get Jest to rerun at all while editing test file dependencies like this.

What work remains to speed up Vitest?

Okay, let’s address that performance hit outside of watch mode. This is a known issue in the Vitest community that stems from a core difference over Jest: Vitest is ESM-first, while Jest is based on the older CommonJS standard you may know from Node.

In other words, you can use import x from 'path' instead of const x = require('path') out of the box.

This is a huge win for modern developer tooling. As more and more modules are dropping CommonJS support, it’s crucial that our dev tools stay with the times.

However, this new ESM mindset forces Vitest to use a different test running strategy. To summarize:

  • Jest creates a “global context” for each test suite
  • Vitest can’t use a global module in the same way due to ESM support, so it creates isolated “workers” for each test file by default

This isolation means more time spent spinning up your test suites. Sadly, this has performance implications on small projects and at scale.

But remember, Vitest is still in its early days. So, I’d avoid using Vitest for production apps right now, per their recommendation. Well, unless minimal config and fast dev servers are enough for you already. 

Conclusion

I hope this post gets you excited for Vitest’s future! It’s still in the development phase, so I highly encourage you to check out the Discord community to ask questions, contribute PRs, and watch the performance discussions over time. “Simplifying developer tooling” is a major trend to look out for, and I expect Vitest to only push this vision further.

Original article source at https://blog.logrocket.com

#vite vitest #vue #testing 

Using Vitest to Effectively Test Your Vite Applications
Dylan North

Dylan North

1670488766

Install Vue 3 in Laravel 9 with Vite Step by Step

In this tutorial, we will learn how to install Vue 3 in Laravel 9 with Vite. This post shows you how to install vue 3 in laravel 9 with the latest upgrades. If you want to see an example of installing vue 3 in laravel-vite then you are in the right place.

Use the following steps to install Vue 3 in the laravel 9 application.

  • Install laravel 9 App
  • Install NPM Dependencies
  • Install Vue 3
  • Update vite.config.js
  • Compile the assets
  • Create Vue 3 App
  • Create Vue 3 Component
  • Connect Vue 3 Component with Laravel blade file and use vite directive to add assets.
  • Update Laravel Routes
  • Start The Local Server

Step 1. Install laravel 9 App

First, open Terminal and run the following command to create a fresh laravel project:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-vue3-vite

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-vue3-vite

Step 2. Install NPM Dependencies

Run the following command to install frontend dependencies:

npm install

Step 3: Install Vue 3

Now after installing node modules we need to install vue 3 in our application, for that execute the following command in the terminal npm install vue@next vue-loader@next. vue-loader is a loader for webpack that allows you to author Vue components in a format called Single-File Components. vue-loader@next is a loader that is for webpack to author Vue components in single-file components called SFCs.

npm install vue@next vue-loader@next

Step 4: Install vitejs/plugin-vue plugin

In laravel 9 latest release install vitejs/plugin-vue plugin for installing vue3 or vue in laravel. This plugin provides required dependencies to run the vuejs application on vite. Vite is a  build command that bundles your code with Rollup and runs of localhost:3000 port to give hot refresh feature.

npm i @vitejs/plugin-vue

Step 4: Update vite.config.js file

Vite is a module bundler for modern JavaScript applications. Open vite.config.js and copy-paste the following code. First invoice defineConfig from vite at the top of the file and also import laravel-vite-plugin. Here plugins() take the path of the js and CSS file and create bundles for your application. you need to add vue() in the plugins array.

// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'


export default defineConfig({
    plugins: [
        vue(),
        laravel([
            'resources/css/app.css',
            'resources/js/app.js',
        ]),
    ],
});

Step 4: Vite Dev Server Start

Now after installing the vue 3, we need to start the dev server for vite for that run the following command and it will watch your resources/js/app.js file and resources/css/app.css file. It also starts a vite server on http://localhost:3000. you can not open it in the browser as it is for vite hot reload and it runs in the background and watches the assets of your application like js and CSS.

npm run dev

Step 5: Create Vue 3 App

In resources/js/app.js create an instance of the vue 3 firstly you import { createApp } from 'vue' and createApp It takes a parameter here we have passed App. Before that, you can create a vue file which is the main file responsible for the vuejs content name is App.vue.

// app.js
require('./bootstrap');

import {createApp} from 'vue'

import App from './App.vue'

createApp(App).mount("#app")

Step 6: Create Vue 3 Component

Under the js folder create a file name 'App.vue' and write content for this example let’s write simple "How To Install Vue 3 in Laravel 9 with Vite - TechvBlogs" you can change it according to your requirement.

<template>
    How To Install Vue 3 in Laravel 9 with Vite - TechvBlogs
</template>

Step 7: Connect Vue 3 Component with Laravel blade file

In this step, go-to resource / views  directory, create the  app.blade.php  file, and add the following code to app.blade.php  as follow:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>How To Install Vue 3 in Laravel 9 with Vite</title>

	@vite('resources/css/app.css')
</head>
<body>
	<div id="app"></div>

	@vite('resources/js/app.js')
</body>
</html>

Step 8: Update Laravel Routes

Open routes/web.php and replace welcome.blade.php with vue.blade.php file to load the vue.blade.php file where our vuejs code will execute.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('app');
});

Step 9: Update .env file

Open .env file and update APP_URL and set APP_URL=http://localhost:8000. It will help vite to check the js and CSS updates and changes them in the browser instantly.

APP_URL=http://localhost:8000

Step 10: Start the Local server

Now open a new terminal and execute the following command from your terminal to run the development server. It runs the project on localhost 8000 port by default but you can change it also. Run npm run dev server also so that site will watch the changes in the vuejs templates and will update automatically to the browser. if you are running another project on the same port number.

php artisan serve

and navigate to the following link http://localhost:8000/

Happy coding !!!

#laravel #vue #vite 

Install Vue 3 in Laravel 9 with Vite Step by Step
Dylan North

Dylan North

1670487635

Install React in Laravel 9 with Vite Step by Step

In this tutorial, we will learn how to install React in Laravel 9 with Vite. This post shows you how to install React in laravel 9 with the latest upgrades. If you want to see an example of installing react 3 in laravel-vite then you are in the right place.

Use the following steps to install React in the laravel 9 application.

  • 1: Install laravel 9 App
  • 2: Install NPM Dependencies
  • 3: Install React
  • 4: Install vitejs/plugin-react plugin
  • 5: Update vite.config.js
  • 6: Vite Dev Server Start
  • 7: Create Reactjs Component
  • 8: Update app.js file in resources folder
  • 9: Create Custom Helper For Vite Assets
  • 10: Connect Reactjs Component with Laravel blade file
  • 11: Update .env file
  • 12: Start The Local Server

Step 1: Install laravel 9 App

First, open Terminal and run the following command to create a fresh laravel project:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-react-vite

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-react-vite

Step 2: Install NPM Dependencies

Run the following command to install frontend dependencies:

npm install

Step 3: Install React

Now after installing node modules we need to install reactjs in our application, for that execute the following command in the terminal npm install react@latest react-dom@latest. It will install latest version of reactjs and react-dom also. we’ll use it in jsx file.

npm install react@latest react-dom@latest

Step 4: Install vitejs/plugin-react plugin

In laravel 9 latest release install vitejs/plugin-react plugin for installing reactjs in laravel. This plugin provides required dependencies to run the reactjs application on vite. Vite is a  build command that bundles your code with Rollup and it runs on localhost:3000 port to give hot refresh feature.

npm i @vitejs/plugin-react --force
npm i @vitejs/plugin-react-refresh --force

Step 5: Update vite.config.js file

The latest 9.19 Provides a vite.config.js file in the root of the application to configure front-end assets preset import plugin-react and add react() to the plugins array in the defineConfig() function.

import reactRefresh from '@vitejs/plugin-react-refresh';


export default ({ command }) => ({
    base: command === 'serve' ? '' : '/build/',
    publicDir: 'fake_dir_so_nothing_gets_copied',
    build: {
        manifest: true,
        outDir: 'public/build',
        rollupOptions: {
            input: 'resources/js/app.js',
        },
    },
    plugins: [
        reactRefresh(),
    ],
});

Step 6: Vite Dev Server Start

Now after installing the reactjs, we need to start the dev server for vite for that run the following command and it will watch your resources/js/app.js file and resources/css/app.css file. It also starts a vite server on http://localhost:3000. you can not open it in the browser as it is for vite hot reload and it runs in the background and watches the assets of your application like js and CSS.

npm run dev

Step 7: Create Reactjs Component

Under the resources/js folder create a file name App.jsx and write content for this example let’s write simple “Reactjs With Laravel Vite” you can change it according to your requirement.

// resources/js/App.jsx
import React from 'react';
import { createRoot } from 'react-dom/client'

export default function App(){
    return(
        <h1>How To Install React in Laravel 9 with Vite</h1>
    );
}

if(document.getElementById('root')){
    createRoot(document.getElementById('root')).render(<App />)
}

Step 8: Update app.js file in resources folder

In resources/js/app.js Import App.jsx component

// resources/js/app.js
import './bootstrap';

import './App.jsx'

Step 9: Create Custom Helper For Vite Assets

To work around this, we can ping localhost:3000. If it connects, we know the dev server is running and we can render the hot scripts.

This could go in a helpers.php file, learn how to set one up here.

First, let’s extract the code we had written in our Blade template to a helper function. Next, we’ll use Laravel Http facade to ping localhost:3000. If it connects, we know the dev server is running.

<?php

use Illuminate\Support\Facades\Http;
use Illuminate\Support\HtmlString;

function vite_assets(): HtmlString
{
    $devServerIsRunning = false;
    
    if (app()->environment('local')) {
        try {
            Http::get("http://localhost:3000");
            $devServerIsRunning = true;
        } catch (Exception) {
        }
    }
    
    if ($devServerIsRunning) {
        return new HtmlString(<<<HTML
            <script type="module" src="http://localhost:3000/@vite/client"></script>
            <script type="module" src="http://localhost:3000/resources/js/app.js"></script>
        HTML);
    }
    
    $manifest = json_decode(file_get_contents(
        public_path('build/manifest.json')
    ), true);
    
    return new HtmlString(<<<HTML
        <script type="module" src="/build/{$manifest['resources/js/app.js']['file']}"></script>
        <link rel="stylesheet" href="/build/{$manifest['resources/js/app.js']['css'][0]}">
    HTML);
}

Step 10: Connect Reactjs Component with Laravel blade file

Now we need to create a blade file where the reactjs app will load. In the resources/views folder open a file name  welcome.blade.php. Add @vite(‘resources/js/app.js’) at the bottom of the file in the react.blade.php file It will load all the js you need to run the Reactjs code.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>How To Install React in Laravel 9 with Vite</title>

    {{ vite_assets() }}
</head>
<body>
	<div id="root"></div>
</body>
</html>

Step 11: Update .env file

Open .env file and update APP_URL and set APP_URL=http://localhost:8000. It will help vite to check the js and CSS updates and changes them in the browser instantly.

APP_URL=http://localhost:8000

Step 12: Start the Local server

Start the development server

php artisan serve

and navigate to the following link http://localhost:8000/

Happy Coding !!!

#laravel #react #vite 

Install React in Laravel 9 with Vite Step by Step
Kevin  Simon

Kevin Simon

1669969525

Install Bootstrap 5 in Laravel 9 with Vite

Laravel has just released “laravel 9.19” with a major change. There is no more webpack.mix.js file in the laravel root in the place of the webpack.mix.js file vite.config.js file is introduced

In this tutorial, We will learn how to install Bootstrap 5 in Laravel 9 with Vite. In laravel 9.19 come with vite tool, we will install bootstrap 5 in laravel 9 with larave ui.


How to Install Bootstrap 5 in Laravel 9 With Vite

Use the following steps to install Bootstrap 5 in the laravel 9 with Vite.

  1. Install Laravel Project
  2. Install Laravel UI For Bootstrap 5
  3. Setup Auth Scaffolding with Bootstrap 5
  4. Install NPM Dependencies
  5. Import vite.config.js Bootstrap 5 Path
  6. Update bootstrap.js
  7. Import Bootstrap 5 SCSS in JS Folder
  8. Replace mix() with @vite Blade directive
  9. Running Vite Command to build Asset File
  10. Start the Local server

Step 1: Install Laravel Project

Installing a fresh new laravel application, so head over to the terminal, type the command, and create a new laravel app.

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-bootstrap5-vite

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-bootstrap5-vite

Step 2: Install Laravel UI For Bootstrap 5

Next, you need to run the below command in your terminal

composer require laravel/ui

Step 3: Setup Auth Scaffolding with Bootstrap 5

php artisan ui bootstrap --auth

 Step 4: Install NPM Dependencies

Run the following command to install frontend dependencies:

npm install

Step 5: Import vite.config.js Bootstrap 5 Path

First, you need to change vite.config.js and add the bootstrap 5 path & remove resources/css/app.css

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import path from 'path'

export default defineConfig({
    plugins: [
        laravel([
            'resources/js/app.js',
        ]),
    ],
    resolve: {
        alias: {
            '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),
        }
    },
});

Step 6: Update bootstrap.js

We need to use import instead of require.

import loadash from 'lodash'
window._ = loadash


import * as Popper from '@popperjs/core'
window.Popper = Popper

import 'bootstrap'


/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios'
window.axios = axios

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });

Step 7: Import Bootstrap 5 SCSS in JS Folder

Now you need to import bootstrap 5 SCSS path in you resources/js/app.js or resources/js/bootstrap.js

resources/js/app.js

import './bootstrap';

import '../sass/app.scss'

Step 8: Replace mix() with @vite Blade directive

When using Vite, you will need to use the @vite Blade directive instead of the mix() helper. remove mix helper and add @vite directive.

<link rel="stylesheet" href="{{ mix('css/app.css') }}">
<script src="{{ mix('js/app.js') }}" defer></script>

use @vite directive

@vite(['resources/js/app.js'])

views/layouts/app.blade

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    @vite(['resources/js/app.js'])

</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

Step 9: Running Vite Command to build Asset File

You need to npm run build command to create asset bootstrap 5.

npm run build

Step 10: Start the Local server

Now open a new terminal and execute the following command from your terminal to run the development server.

php artisan serve

and navigate to the following link http://localhost:8000/

Originally published by https://techvblogs.com/ 

#laravel #vite #bootstrap 

Install Bootstrap 5 in Laravel 9 with Vite
Shubham Ankit

Shubham Ankit

1669619042

Install Tailwind CSS 3 in Laravel 9 With Vite 3

In this tutorial, You will learn how to install Tailwind CSS 3 in Laravel 9 with Vite 3. To install Tailwind CSS 3 in Laravel 9 with Vite 3 we follow these steps

  • Step 1: Install Laravel Project
  • Step 2: Setup Tailwind CSS
  • Step 3: Add Tailwind CSS to app.css
  • Step 4: Import Vite Assets to Laravel Blade
  • Step 5: Run Vite Development Server
  • Step 6: Run Laravel Development Server

Step 1: Install Laravel Project

Installing a fresh new laravel application, so head over to the terminal, type the command, and create a new laravel app.

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-tailwind3-vite3

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-tailwind3-vite3

Step 2: Setup Tailwind CSS

Next, we’d need to install tailwind and its dependencies (PostCSS & auto-prefixer).

npm install -D tailwindcss postcss autoprefixer

Generate the Tailwind and post CSS configuration files.

npx tailwindcss init -p

This will create two files in your root directory: tailwind.config.js and postcss.config.js. The Tailwind config file is where you add customization and theming for your app. It is also where you tell Tailwind what paths to search for your pages and components. It looks something like this:

// tailwind.config.js
module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
}

Next, you need to add a template path in tailwind.config.js.

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./resources/**/*.blade.php",
    "./resources/**/*.js",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Step 3: Add Tailwind CSS to app.css

resources/css/app.css

@tailwind base;
@tailwind components;
@tailwind utilities;

Remove resources/css/app.css in vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/js/app.js'],
            refresh: true,
        }),
    ],
});

Next,  you need to import your CSS via JavaScript. Typically, this would be done in your application's resources/js/app.js file:

resources/js/app.js

import './bootstrap';
import '../css/app.css'

Step 4: Import Vite Assets to Laravel Blade

resources/views/welcome.blade.php

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>How to Install Tailwind CSS 3 in Laravel 9 With Vite 3 - TechvBlogs</title>

        @vite('resources/js/app.js')
    </head>

    <body class="antialiased">
        <div class="flex justify-center items-center h-screen">
            <h1 class="text-3xl text-purple-600 font-bold">How to Install Tailwind CSS 3 in Laravel 9 With Vite 3 - TechvBlogs</h1>
        </div>
    </body>

</html>

Step 5: Run Vite Development Server

Run the following command to start the Vite Development server:

npm run dev

Step 6: Run Laravel Development Server

php artisan serve

#laravel #php #tailwindcss #vite 

 

Install Tailwind CSS 3 in Laravel 9 With Vite 3
React Tutorial

React Tutorial

1669174572

Why You Should Stop Using Create React App

This tutorial shows why you should stop using Create React App (CRA). All the alternatives to CRA that you should consider using instead: Vite, Astro/Gatsby, Next.js, Full Stack Frameworks, and more

Create React App is an incredible tool that made it easy to setup and work with React, but as the years have gone by CRA has become less and less useful to the point that you should pretty much never use it. In this video I talk about all the alternatives to CRA that you should consider using instead.


⏱️ Timestamps:

00:00 - Introduction
00:27 - CRA Cons
01:14 - Vite
02:27 - Astro/Gatsby
04:43 - Next.js
06:54 - Full Stack Frameworks


Let us look at the alternatives of CRA; what can you use, and why should you bother?

NextJS

NextJS is probably the most popular toolchain besides CRA. It comes with its own routing and styling solutions (styling can be tricky when working with SSR). Vercel, the maintainer of NextJS, is also responsible for other packages that can be used in any React project (e.g., swr). Therefore they are somewhat actively contributing to the React universe, which I like.

A NextJS app can be deployed to Vercel’s very own platform (free for non-commercial websites). The last time I tried it, it was a simple process that allowed anybody to deploy their app in no time.

Besides everything you know and love from React, NextJS uses its own API to make SSR and backend development easy — even for frontend devs.

With React18 and HTTP3, I look forward to websites using streaming a lot more, so this will be an exciting candidate for the future.

If a robust and future-proof library is what you’re looking for: Look no further. Learn NextJS now: https://nextjs.org/learn

If you’ve already tried NextJS and it was too far away from React to understand, or you simply didn’t like the API, read on! It’s going to be interesting.

Remix

Remix has everything that NextJS has. They’re contributing to Reacts ecosystem (the makers of React-Router), making developing SSR apps with React a breeze, but there’s a huge difference: They are much more open to extensions and closer to Reacts’ API. At least, this was my impression when I had to work with Remix and NextJS. I also had the feeling that Remix is faster and I felt more “at home” when writing React in Remix’s environment.

I think Remix is the better NextJS, and I will use it in my next project. If you consider using it, then you should be aware of its downsides, too:

  • The community is not as big as NextJS’ community.
  • Remix might not be a good name; it will be hard to google for advice (you might have success with “RemixJS,” though).
  • There are not many projects out there currently using Remix.

Some of the ups and downs might only be my experience with it, yours may differ. Be aware of that.

To learn about Remix and how to create your next React app using it, start here: https://remix.run/docs/en/v1

Other React Toolchains and Creating your own

There are many other React toolchains out there that I didn’t mention. Mainly because I didn’t use them as much. For beginners, the React documentation might be a good starting point, as it leads to some of the alternatives https://reactjs.org/docs/create-a-new-react-app.html. You’ll notice that the current documentation doesn’t even mention Remix. However, the upcoming doc will do so: https://beta.reactjs.org/learn/start-a-new-react-project#popular-alternatives.

Also, I don’t want to lose many words on custom toolchains; let me just say this: Don’t! It requires a lot of work to create a suitable toolchain. There are tutorials out there on how to add anything to existing toolchains like Remix, NextJS, and even CRA. It’s relatively simple to add things like Tailwind, Jest, or Storybook to them, whereas it can be a nightmare to set this up manually (especially in combination with TypeScript). Instead, find a toolchain that suits you the best — which I believe would mean to stop using Create React App.

#react #nextjs #vite #astro #gatsby

Why You Should Stop Using Create React App

Build a Modern Documentation Site with CSS and VitePress

In this tutorial, you'll learn how to build a modern documentation site and customized it using CSS and VitePress built-in components. Build a complete docs site quickly by utilizing a modern tool called VitePress.

Documentation is a crucial aspect of software development. But developers often neglect it because it can be a hassle to maintain. This is why it's important to use tools that help simplify this process.


What is VitePress?

VitePress is a simple and performant static site generator built on top of Vite that lets you create docs in a matter of minutes. It is powered by Vuejs and Vite with built-in customizable components.

VitePress powers some popular documentation sites like Vuejs, Vitest, faker.js, and Vite itself.

Prerequisites

To follow along with this tutorial, you need to have a basic understanding of the following:

  • Markdown syntax
  • Basic understanding of NPM and Vite

Here's a screenshot of what you'll build by the end of this tutorial:

final-works-2

Want to play around with it? Check out the live demo. Also, the source code for this can be found on GitHub.

Step 1: Create a New Project

If you already have a folder created, you can skip this step and go on to the next one. If not, use the following command to create a project folder and move into the folder.

mkdir project-name
cd project-name

Next you need to initialize the project with your preferred package manager. I'll be using NPM for the rest of this guide.

npm init
// or use this command if you want to skip all the questions
npm init -y

If you used the first command, you'll be prompted with certain questions, so just complete them as appropriate.

After a successful operation, you should have a package.json file in your root directory. This is where the VitePress dev dependency will be installed.

Step 2: Install VitePress

The next step is to add VitePress and Vue as dev dependencies to your project, like this:

npm install --dev vitepress vue

You've successfully installed VitePress and Vue and added them as dev dependencies. Now you can start creating creating your respective doc files.

But before you do that, I believe it's essential to explain how VitePress works.

How Does VitePress Vork?

VitePress makes use of Markdown .md files for its markup which is automatically converted into static HTML. In other for this to work, a special folder called docs gets created in the root directory.

This folder behaves similarly to the pages folder in NextJS, where any .js file created in the directory is automatically treated as a web page. In this case a file called index.md will be the treated as index.html and serve as the root of your docs template.

Now that you understand how that works, you can create your respective doc files.

Step 3: Create the Respective Doc Files

You can create the docs folder and the index.md file manually, or you can do it with the terminal like a hacker.

mkdir docs && echo '# Hello VitePress' > docs/index.md

This command simply creates a folder called docs and adds an index.md file containing a h1 element that says "Hello World".

create-respective-files

With this, you can boot up your dev environment to see what has been created so far.

Step 4: Boot Up Your Dev Environment

In order to run your docs locally, you need to add the following scripts inside the package.json file. Simply copy the code below and replace the "script" object with it:

// package.json
"scripts": {
    "docs:dev": "vitepress dev docs",
    "docs:build": "vitepress build docs",
    "docs:serve": "vitepress serve docs"
  },

Finally, the documentation site can be served on a local server by running the command below:

npm run docs:dev

This will start a hot-reloading development server at http://localhost:5173, and you can visit it to see your docs site.

Here's the output:

boot-dev-server

All you had to do was add the markup and VitePress handled the appearance from its template engine. In the next session, you'll learn how you can customize the docs to fit your needs.

How to Customize Your Docs with VitePress

First create a .vitepress folder inside the docs directory you created earlier on. This is where all VitePress-specific files will be placed.

Inside this new directory, you need a config.js file. Again, you can use the terminal command like so:

mkdir .vitepress && touch .vitepress/config.js

To test this config file, you can start by changing the meta title and description of your docs site. Copy this markup and paste into the config.js file:

// .vitepress/config.js
export default {
  title: 'Adocs',
  description: 'An awesome docs template built by me'
}

If you check the dev tools, you should see the changes in the meta title and description.

title-and-description

How to Update the Title and Logo

In order to change the logo title and add an image, copy the markup below and paste it into a new object called themeConfig inside the same config.js file. This will overwrite the current title and add a logo to your docs site.

// config.js
export default {
  themeConfig: {
    logo: "/logo.svg",
    siteTitle: "Adocs",
  },
};

For the image source, you can pass in an image URL or specify the path to a local image. To do it locally, make sure you place the image within the public directory.

Here's the output:

logo-and-title

Note that files in the public directory are served at the root path. So instead of ../public/logo.svg, just use /logo.svg.

How to Customize the Navbar

Customizing the Navbar is a pretty straightforward process as well. Inside your themeConfig file, paste the markup below. Here we have an object that contains two properties: the anchor text text, and the path link defines the URL path.

// .vitepress/config.js
{  
  // ...
   nav: [
    { text: "About", link: "/about" },
    { text: "Contact", link: "/contact" },
    { text: "Guide", link: "/guide" },
    { text: "Configs", link: "/configs" },
    { text: "Changelog", link: "https://github.com/..." },
  ],
  // ...     
}

Essentially navigating to localhost:5173/about should take you to an about page (though we haven't created that yet).

Here's the output:

navigaiton-menu

Navigation links can also be dropdown menus, too. To add one, simply replace any of the links property with the items object which contains an array of links.

// .vitepress/config.js
{
  text: "Changelog",
  items: [
   { text: "v0.0.1", link: "/item-1" },
   { text: "v0.0.2", link: "/item-2" },
   { text: "v0.0.3", link: "/item-3" },
  ],
},

Now the changelog will become a dropdown menu with the respective links you pass inside.

Here's the output:

dropdown-menu

How to Add Social Icons

Navigation menus usually have social icons that visitors can use to visit your social platforms. To add them, define a new object called socialLinks inside themeConfig and simply pass in the social icon and the link you want it to navigate to.

// .vitepress/config.js
socialLinks: [
  { icon: "github", link: "https://github.com/Evavic44/adocs" },
  { icon: "twitter", link: "https://twitter.com/victorekea" },
  { icon: "discord", link: "..." },
]

By default, only 8 icons (Discord, Facebook, GitHub, Instagram, LinkedIn, Slack, Twitter, and YouTube) are provided. If you want to add a custom icon, use the SVG property to define an svg image. You can get free icons from icones.js.org.

For example, here's a snippet of the apple icon.

{
  icon: {
    svg: '<svg role="img" width="26.01" height="32" viewBox="0 0 256 315"><path d="M213.803 167.03c.442 47.58 41.74 63.413 42.197 63.615c-.35 1.116-6.599 22.563-21.757 44.716c-13.104 19.153-26.705 38.235-48.13 38.63c-21.05.388-27.82-12.483-51.888-12.483c-24.061 0-31.582 12.088-51.51 12.871c-20.68.783-36.428-20.71-49.64-39.793c-27-39.033-47.633-110.3-19.928-158.406c13.763-23.89 38.36-39.017 65.056-39.405c20.307-.387 39.475 13.662 51.889 13.662c12.406 0 35.699-16.895 60.186-14.414c10.25.427 39.026 4.14 57.503 31.186c-1.49.923-34.335 20.044-33.978 59.822M174.24 50.199c10.98-13.29 18.369-31.79 16.353-50.199c-15.826.636-34.962 10.546-46.314 23.828c-10.173 11.763-19.082 30.589-16.678 48.633c17.64 1.365 35.66-8.964 46.64-22.262"/></svg>',
    },
  link: "https://www.apple.com/",
},

For custom SVG icons, make sure you add the role="img" property to the svg tag, as this allows the string convert it properly.

Here's the output:

social-icons

How to Add a Sidebar

VitePress also comes with built-in components like sidebar menus. To add a sidebar, create an object called sidebar and inside it, add nested objects that take in three values: the nested title, collapsible functionality (default is set to true), and the nested links.

// .vitepress/config.js
sidebar: [
    {
      text: "Section A",
      collapsible: true,
      items: [
        { text: "Introduction", link: "/introduction" },
        { text: "Getting Started", link: "/getting-started" },
      ],
    },
    {
      text: "Section B",
      collapsible: false,
      items: [
        { text: "Introduction", link: "/introduction" },
        { text: "Getting Started", link: "/getting-started" },
      ],
    },
    {
      text: "Section C",
      collapsible: true,
      items: [
        { text: "Introduction", link: "/introduction" },
        { text: "Getting Started", link: "/getting-started" },
      ],
    },
  ],

By adding collapsible: "true" to the sidebar object, it shows a toggle button to hide/show each section. You can create as many sections as you want.

Here's the output:

sidebar-2

You can see section B is not collapsible, and we have that nice next page button on the bottom of the page.

How to Set Up Page Routing

As explained earlier, VitePress automatically converts every .md file inside the root of the docs directory to static HTML that can be accessed in the address bar. For instance the index.md is converted to index.html, and about.md, about.html and so on.

Since you've created your nav links and pointed them to their respective URLs, you can access these pages easily by creating them.

docs/
├── .vitepress/
│   └── config.js
├── public/
│   └── logo.svg
├── about.md
├── contact.md
├── guide.md
├── configs.md
└── get-started.md

Create these files inside your docs folder and add a simple markup inside them just to see how this works. This page is basic markdown so all your markdown syntax like links, code blocks, headings, and so on works here.

Just for testing purposes, copy this markdown content and paste it inside any of the .md files you just created:

# About

Welcome to the about page.

This markdown supports html elements like the `p` tag coupled with inline styles

<p style="color: #ff7340; border: 1px solid rgba(255, 135, 23, 0.25); border-radius:5px; padding: 1rem;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>

Even satire code snippets with syntax highlighting are also supported. 😅

```js
const lang = prompt("What is your favorite programming language?");

(lang === "JavaScript") | (lang === "javascript") | (lang === "js")
  ? alert("JavaScript to the world! 🚀🟡")
  : alert(`We don't permit such languages here 💩`);
```

Of course, images are not left out.

<img src="/logo.svg" alt="adocs logo">

Here's the output:

page-routing-2

Great! You've set-up the docs, added a navigation menu with a dropdown feature, added a sidebar, and customized the links to navigate to different pages. Next up, let's work on the home page.

How to Customize the Homepage

Just like every other component, VitePress provides us with markup for building the homepage. I've broken it down into three parts: Hero, features, and footer section.

The Hero Section

First, we'll start with the hero section. Replace the Hello World text in the index.md page with the following markup:

# docs/index.md
---
layout: home

hero:
  name: Adocs
  text: Static docs template built with VitePress.
  image:
    src: /logo-big.svg
    alt: Adocs logo
  tagline: A free to use template for creating docs for your projects
  actions:
    - theme: brand
      text: Get Started
      link: /get-started
    - theme: alt
      text: View on GitHub
      link: https://github.com/evavic44/adocs-template
---

The Features Section

Additionally, you can add a features section after the hero section. Simply paste the code below under the hero objects:

# /docs/index.md
---
link: https://github.com/evavic44/adocs-template

features:
  - icon: ⚡️
    title: Adocs, The DX that can't be beat
    details: Lorem ipsum...
  - icon: 🎉
    title: Power of Vue meets Markdown
    details: Lorem ipsum...
  - icon: 🔥
    title: Simple and minimal, always
    details: Lorem ipsum...
  - icon: 🎀
    title: Stylish and cool
    details: Lorem ipsum...
---

Here's the output:

hero-redesign

The Footer Section

You can add a footer message on the bottom of the page, but this will only show up in the home page.

According to the VitePress docs:

Note that the footer will not be displayed when the SideBar is visible.

To add the footer component, go to the config.js file and paste the markup inside the themeConfig object:

// .vitepress/config.js
 footer: {
   message: "Released under the MIT License.",
   copyright: "Copyright © 2022-present Adocs",
 },

Here's the output:

footer-2

Aside from the markup, you can also customize the components using custom CSS to change things like fonts family, colors, layout, ETC.

How to Add Custom CSS

The default theme CSS is customized by overriding root level CSS variables. If you want, you can check out the full list of CSS variables that are customizable.

To do get started, create a .vitepress/theme directory, and inside this theme folder, add an index.js and custom.css file. If you've been following along, you can use the terminal command below to do this quickly:

mkdir docs/.vitepress/theme && touch docs/.vitepress/theme/index.js && touch docs/.vitepress/theme/custom.css

If you run into any issues with the terminal command, just create the files manually and move on to the next step.

Here's an overview of the folder structure:

docs/
├── .vitepress/
│   ├── config.js
│   └── theme/
│       ├── index.js
│       └── custom.css
├── public/
│   └── logo.svg
├── about.md
├── contact.md
├── guide.md
├── configs.md
└── get-started.md

After creating these files, inside the .vitepress/theme/index.js file, paste the import commands:

// .vitepress/theme/index.js
import DefaultTheme from "vitepress/theme";
import "./custom.css";

export default DefaultTheme;

Color Theme

The colors are controlled by the CSS variables. You can simply replace them with any colors you want.

Note that this color has a provision for both light and dark mode. So make sure you change them accordingly.

Here's an example of my custom colors:

/* .vitepress/theme/custom.css */

:root {
  --vp-c-brand: rgb(255, 115, 64);
  --vp-c-brand-light: rgb(255, 87, 25);
  --vp-c-brand-lighter: rgb(255, 115, 64);
  --vp-c-brand-dark: #FF622D;
  --vp-c-brand-darker: rgb(226, 60, 0);

  --vp-c-sponsor: #fd1d7c;
}

If you don't see the effects immediately, try stopping the server and starting it again.

Aside from the color themes, you can also override other things like font family, typography, layout, breakpoints, and so on.

How to Use Custom Fonts

You can import Google fonts inside the CSS file to override the default font family.

@import url(https://fonts.googleapis.com/css?family=Space+Mono:regular,italic,700,700italic);
@import url(https://fonts.googleapis.com/css?family=Space+Grotesk:regular,italic,700,700italic);

:root {
  --vp-c-brand: #ff7340;
  --vp-c-brand-light: #ff5719;
  --vp-c-brand-lighter: #ff7340;
  --vp-c-brand-lighter: rgba(255, 135, 23, 0.25);
  --vp-c-brand-dark: #ff622d;
  --vp-c-brand-darker: #e23c00;

  --vp-c-sponsor: #fd1d7c;

  /* Typography */
  --vp-font-family-base: "Space Grotesk", "Inter var experimental", "Inter var",
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
    Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;

  /* Code Snippet font */
  --vp-font-family-mono: "Space Mono", Menlo, Monaco, Consolas, "Courier New",
    monospace;
}

With the --vp-font-family-base variable you can change the main font and --vp-font-family-mono, the font for code snippets.

Here's the output:

final-works

You've successfully customized the theme and changed the font family using CSS. Though there's more you can do in regards to styling, but at this point, I hope it's clear how you can customize your docs with CSS.

Let's discuss hosting in the next section.

How to Host Your Doc Site

You can publish or host your docs site when you're done to different platforms like Netlify, Vercel, AWS Amplify, and so on.

First, run the build command:

npm run docs:build

This should create a new dist folder that contains all the static files of your docs.

In deciding on what hosting service to use, you can pick any of the options I mentioned earlier but we'll be using Vercel in this guide. Also, feel free to look at other alternatives of your choice.

If you don't have a Vercel account, follow this guide to create one and configure your Git provider before you move on to the next step.

Assuming you've successfully set-up your account and uploaded your docs site to Vercel, navigate to the project > settings > build and deploy settings, and paste the following commands to their respective fields:

  • Build command: npm run docs:build
  • Output directory:  docs/.vitepress/dist

deploy-settings-vercel

After editing the settings, save them and deploy your site!

Conclusion

In this tutorial, you've set-up a full-fledged documentation site and customized it using CSS and VitePress built-in components.

Just keep in mind that this tutorial only covers a fragment of what is possible with VitePress. To learn more, check out the VitePress docs.

Additional Reading

Here are a few things not covered in this article that I think is also worth looking into:

Resources

If you are an open source fan like myself or you enjoy hearing about such cool projects, do follow me on my socials so you don't miss my next post. Cheers. 🍷

Original article source at https://www.freecodecamp.org

#vue #vite #javascript #vitepress #css #programming #developer #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment 

Build a Modern Documentation Site with CSS and VitePress
Justen  Hintz

Justen Hintz

1668415674

How to Build an Astro Blog with Vite and MDX

Learn how to build an Astro blog with interactive text-based content with Vite and MDX. Creating interactive text-based content using Markdown syntax has never been easier. By following this tutorial, you’re on your way to creating a blog using Astro and MDX. 

Astro recently announced support for MDX and Vite 3.0 in their release of Astro 1.0, two important integrations that put them at the top of their game for building static sites. Vite is an upgrade to their internal engine, providing fast builds and a better development experience, and MDX for extending Markdown capabilities that cater to interactive, text-based content.

In this article, you’ll learn how to build a blog using Astro and MDX. We’ll cover:

  • What is Astro?
  • What is Vite?
  • What is MDX?
  • Astro app setup
  • Writing MDX code into our Astro app
  • Creating a blog with MDX and Astro
    • Creating the blog post layout
    • Creating a Markdown blog post
    • Adding interactive components to our Astro blog
    • Create a page in our Astro blog

Prerequisites

  • Working knowledge of JavaScript and/or JavaScript frameworks
  • Knowledge of Markdown syntax

What is Astro?

Astro is a powerful static site generator that lets you create highly performant websites using the JavaScript frameworks you know and love. Astro is static-first, with progressive enhancement, meaning that, by default, it ships zero JavaScript to the browser until required.

What is Vite?

Vite is a next-gen JavaScript build tool that simplifies how frontend web applications are built and developed. Other popular JavaScript build tools, such as Webpack and Rollup, solve the problem of asset bundling and serving code locally during development.

However, Vite approaches the problem differently by leveraging native browser ES modules to load JavaScript code instantly in the browser. This way, no matter the number of dependencies or code added to your project, you still get instant builds.

What is MDX?

MDX is a tool that lets you extend the capabilities of Markdown by leveraging the power of JSX. You can import and use interactive components such as charts, alerts, and more. You can even create reusable MDX components. MDX opens up new possibilities for creating written content.

Astro app setup

Create a project using the Astro CLI by first running the following command in your terminal:

npm create astro@latest

Follow the step-by-step terminal prompts to finish the setup according to your preferences.

Once that’s done, cd into the project directory and run the command below to start an Astro dev server at http://localhost:3000:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see the following on your screen:

Astro Homepage In The Localhost Browser

Now, install MDX using the command below, depending on your package manager:

# Using NPM
npx astro add mdx
# Using Yarn
yarn astro add mdx
# Using PNPM
pnpm astro add mdx

Accept all the prompts to complete the integration within your Astro application and restart your development server.

By default, Astro has support for Markdown files and can build routes/pages from Markdown files (.md) in the src/pages folder. But by adding the MDX integration, you can use .mdx files in the folder to generate pages in your app.

Writing MDX code into our Astro app

MDX doesn’t have any special syntax because it is just a combination of Markdown and JSX. You can write JSX, Markdown, JavaScript expressions, and import and export statements.

To get a feel for what writing MDX code is like, create a file in your project’s src/pages directory, give it whatever name you want, and end the file extension with .mdx. Then paste in the following block of code:

export const continents = ['Africa', 'South America', 'Asia', 'Europe']
I think 2 + 2 is {2+2}

# Math operations Test in MDX, Astro and Vite
### There are 7 continents in the world, below are a few of them listed:
<ul>
  {continents.map((continent) => (
    <li>{continent}</li>
  ))}
</ul>
## HTMl-JSX-Markdown Mix
<div>
  > Some *notable* things in a block quote!
</div>

When you navigate to the name of your page, you should see the following output in your browser:

Math Operations Test In MDX, Astro And Vite

Creating a blog with MDX and Astro

In this tutorial, we’re building a blog using MDX and Astro.

While creating the blog, you’ll:

  • Use MDX to create text-based content
  • Create a layout for the blog and post pages
  • Add interactive components to MDX
  • Use frontmatter in Astro to pass data to Astro layouts
  • Fetch all Markdown files locally using the Astro.glob() method for display

Creating the blog post layout

Navigate to the src/layouts folder and create a new layout called PostLayout.astro and paste in the following code:

---
import BaseHead from "../components/BaseHead.astro";
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";

const {
  frontmatter: { title, description, pubDate, image, author },
} = Astro.props;
---
<html lang="en">
  <head>
    <BaseHead title={title} description={description} />
    <style>
      .title {
        font-size: 2em;
        margin: 0.25em 0 0;
      }
      hr {
        border-top: 1px solid #ddd;
        margin: 1rem 0;
      }
    </style>
  </head>
  <body>
    <Header />
    <main>
      <article>
        <div class="article-head">
          <h1 class="title">{title}</h1>
          <em>Written by: {author}</em>
        </div>
        <div class="article-body">
          {image && <img width={720} height={360} src={image} alt="" />}
          Published on: {pubDate && <time>{pubDate}</time>}
          <hr />
          <slot />
        </div>
      </article>
    </main>
    <div class="footer-container">
      <Footer />
    </div>
    <style>
      html {
        min-height: 100vh;
        height: 100%;
      }
      body {
        height: 100%;
      }
      time {
        display: inline-block;
        margin-top: 10px;
      }
    </style>
  </body>
</html>

Let’s analyze the contents of the code block above.

First, there are a few component imports at the top of the file that don’t exist yet. We’ll get to create them soon:

  • The BaseHead component is going to contain all the HTML <head></head> properties for the layout
  • The Header component will contain the navigation links at the top of the page for going between routes
  • The Footer component will contain the footer for the layout
  • The <slot/> component on line 37 is used to inject the rest of the text content from the Markdown file into the layout

Astro provides Markdown and MDX pages with a frontmatter property that can be used to define “metadata” that can describe the file.

In the PostLayout.astro file, the frontmatter prop passed by each Markdown/MDX file can be accessed to extract the metadata defined in the file. On line 8, the frontmatter property provided by Astro.props is then destructured to expose the variables for the template.

Now, let’s add the code for the missing imported components.

For each of the code blocks below, create the corresponding file in the components folder and paste in the code from the corresponding code block:

For Header.astro :

<header>
  <nav>
    <a href="/">Home</a>
    <a href="/blog">Blog</a>
  </nav>
</header>
<style>
  header {
    margin: 2em 4em 2em;
  }
  h2 {
    margin: 0.5em 0;
  }
</style>

For Footer.astro :

---
const today = new Date();
---
<footer>
    &copy; {today.getFullYear()} YOUR NAME HERE. All rights reserved.
</footer>
<style>
    footer {
        padding: 25px;
        text-align: center;
    }
</style>

And finally, for BaseHead.astro:

---
// Import the global.css file here so that it is included on
// all pages through the use of the <BaseHead /> component.
import "../styles/global.css";

const { title, description } = Astro.props;
---
<!-- Global Metadata -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<!-- Primary Meta Tags -->
<title>{title}</title>
<meta name="title" content={title} />
<meta name="description" content={description} />

There’s also a missing import: ../styles/global.css. Let’s quickly create the file and add styles to it.

In the src folder, create a styles folder with a file named global.css and add the following code:

/*
  The CSS in this style tag is based off of Bear Blog's default CSS. https://github.com/HermanMartinus/bearblog/blob/297026a877bc2ab2b3bdfbd6b9f7961c350917dd/templates/styles/blog/default.css
  License MIT: https://github.com/HermanMartinus/bearblog/blob/master/LICENSE.md
 */
body {
  font-family: Verdana, sans-serif;
  margin: auto;
  padding: 20px;
  text-align: left;
  background-color: #fff;
  word-wrap: break-word;
  overflow-wrap: break-word;
  line-height: 1.5;
  color: #444;
  width: 100%;
}
.article-head {
  margin-left: 4em;
  margin-bottom: 50px;
}
.article-body {
  max-width: 65ch;
  margin: 0 auto;
}
h1,
h2,
h3,
h4,
h5,
h6,
strong,
b {
  color: #222;
}
a {
  color: #222;
}
nav a {
  margin-right: 10px;
}
textarea {
  width: 100%;
  font-size: 16px;
}
input {
  font-size: 16px;
}
content {
  line-height: 1.6;
}
table {
  width: 100%;
}
img {
  max-width: 100%;
  height: auto;
}
code {
  padding: 2px 5px;
  background-color: #f2f2f2;
}
pre {
  padding: 1rem;
}
pre > code {
  all: unset;
}
blockquote {
  border: 1px solid #999;
  color: #222;
  padding: 2px 0px 2px 20px;
  margin: 0px;
  font-style: italic;
}

Creating a Markdown blog post

To test the layout, create a .mdx file and add some content. To do this, navigate to the pages folder, create a post folder, add the first blog post named first-post.mdx, and then paste in the code below. Feel free to tweak it and change the property values:

---
layout: ../../layouts/PostLayout.astro
title: "Astro, Vite and MDX test"
description: "Lorem ipsum dolor sit amet"
author: "Iniubong Obonguko"
pubDate: "20 Aug, 2022"
image: "https://images.unsplash.com/photo-1664380619395-a25d867b5fb9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=1080"
slug: "first-post"
---
## Story about Old days
In the olden days, Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Vitae ultricies leo integer malesuada nunc vel risus commodo viverra. Adipiscing enim eu turpis egestas pretium. Euismod elementum nisi quis eleifend quam adipiscing. In hac habitasse platea dictumst vestibulum. Sagittis purus sit amet volutpat. Netus et malesuada fames ac turpis egestas. Eget magna fermentum iaculis eu non diam phasellus vestibulum lorem. Varius sit amet mattis vulputate enim. Habitasse platea dictumst quisque sagittis. Integer quis auctor elit sed vulputate mi. Dictumst quisque sagittis purus sit amet.

## Conclusion
Morbi tristique senectus et netus. Id semper risus in hendrerit gravida rutrum quisque non tellus. Habitasse platea dictumst quisque sagittis purus sit amet. Tellus molestie nunc non blandit massa. Cursus vitae congue mauris rhoncus. Accumsan tortor posuere ac ut. Fringilla urna porttitor rhoncus dolor. Elit ullamcorper dignissim cras tincidunt lobortis. In cursus turpis massa tincidunt dui ut ornare lectus. Integer feugiat scelerisque varius morbi enim nunc. Bibendum neque egestas congue quisque egestas diam. Cras ornare arcu dui vivamus arcu felis bibendum. Dignissim suspendisse in est ante in nibh mauris. Sed tempus urna et pharetra pharetra massa massa ultricies mi.

The frontmatter is all the metadata property and values defined between
the triple dashes (—).

At the top of the .mdx file is where all the frontmatter data is defined:

  • The layout property defines the layout of choice, which was created earlier in PostLayout.astro
  • All other properties in the frontmatter contain “metadata” that’ll be used by the layout to populate the page
  • The rest of the content below the frontmatter is treated as text content for the blog and is passed into the <slot/> placeholder in the layout

On your browser, go to https://localhost:3000/post/first-post and you should get a page similar to the one below:

Example Gif Of Markdown Blog Post

Adding interactive components to our Astro blog

Now, we’ll see how we can add interactive JavaScript-enabled components to our blog post.

For this, we’ll use an Astro components library called accessible-astro-components. To proceed, we first need to install the library. Do this by running the code below in your terminal under the projects folder.

npm i accessible-astro-components

Next, in the first-post.mdx file below the frontmatter definitions, import the Accordion and AccordionItem components:

import { Accordion, AccordionItem } from "accessible-astro-components";

Now, you can use Accordion anywhere in the file:

{/* first-post.mdx */}
{/* Rest of content at top */}
...
<Accordion>
  <AccordionItem header="First Item">
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto quasi
      nobis optio? Qui in quo accusantium debitis sapiente obcaecati magnam
      incidunt sit. Molestiae exercitationem quibusdam quod veritatis laboriosam
      est tenetur.
    </p>
    <a href="#">Tab to me!</a>
  </AccordionItem>
  <AccordionItem header="Second Item">
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto quasi
      nobis optio? Qui in quo accusantium debitis sapiente obcaecati magnam
      incidunt sit. Molestiae exercitationem quibusdam quod veritatis laboriosam
      est tenetur.
    </p>
  </AccordionItem>
</Accordion> 
...
{/* Rest of content at bottom */}

The result is:

Result Of Interactive Components In Our Astro Blog

You can also use components that are specifically made for other JavaScript frameworks, such as VueJS, React, and Svelte. You just need to set up the framework in your Astro app first and then import the desired component.

Refer to the official documentation here for how it’s done.

Create a page in our Astro blog

We need a blog page that will display all the blog posts in a grid.

But before we get to that, let’s first create a layout for the blog page under the /Layout folder and name it BlogLayout.astro. Then paste the following code into it:

---
import Header from "../components/Header.astro";
import BaseHead from "../components/BaseHead.astro";
const { title } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
  <BaseHead
    title="Blog Page"
    description="A page to display all our blog posts"
  />
  <body>
    <div class="layout">
      <h1>{title}</h1>
      <Header />
      <main>
        <slot />
      </main>
    </div>
    <style>
      body {
        margin: 0;
        background-color: #fff;
        width: 100%;
      }
      .layout {
        max-width: 1280px;
        margin: 0 auto;
      }
    </style>
  </body>
</html>

Next, go to the src/pages folder and create a blog.astro file and paste in the following code:

---
import BlogLayout from "../layouts/BlogLayout.astro";
import { Card } from "accessible-astro-components";
const posts = await Astro.glob("../pages/post/**/*.mdx");
---
<BlogLayout title="Blog">
  <section>
    <div class="container">
      <ul>
        {
          posts.map((post) => (
            <li>
              <Card
                url={"/post/" + post.frontmatter.slug}
                img={post.frontmatter.image}
                title={post.frontmatter.title}
                footer={post.frontmatter.author}
              >
                {post.frontmatter.description}
              </Card>
            </li>
          ))
        }
      </ul>
    </div>
  </section>
</BlogLayout>
<style lang="scss">
  ul {
    display: grid;
    grid-gap: 2rem;
    grid-template-columns: repeat(3, 1fr);
    list-style-type: none;
  }
</style>

Let’s analyze what’s happening in the code block above:

  • First, BlogLayout is being imported to be used as the layout for the page
  • The Card component from the accessible-astro-components package is imported
  • Astro has an Astro global context and has the .glob() method, which can be used to load many local files into the static site setup. In this case, all the .mdx files contained in the /pages/post directory are being loaded and assigned to the posts variable
  • A .map method then loops through the values in the posts variable, renders a list, and assigns the necessary props to the Card component
  • The slug property defined on the frontmatter property of the blog file is then used to build the URL for the card component

Add one or two or more blog posts in the pages/post directory to populate the blog page.

Once done, the blog page should look like this:

Final Result Of Astro Blog

Voila! The blog is now complete.

Conclusion

Creating interactive text-based content using Markdown syntax has never been easier. By following this tutorial, you’re on your way to creating a blog using Astro and MDX. Feel free to update the code from this tutorial with your own custom styling and extra features.

You can also learn more about all the cool features that Astro provides with their MDX integration from the official documentation site.

Namaste.

Original article source at https://blog.logrocket.com

#astro #vite #mdx #webdev #webdeveloper #webdevelopment 

How to Build an Astro Blog with Vite and MDX

Install Vue 3 on Laravel 9 with Vite

In this tutorial, you'll learn how to install Vue 3 in Laravel 9 with Vite. There is two way you can install Vue 3 in Laravel 9. First you can install Vue 3 from scratch or you can use Laravel Breeze inertia Vue. 


How to Install Vue 3 in Laravel 9 with Vite

In this section we will install vue 3 in laravel 9 with vite. In laravel 9.19 come with vite tool. There is two way you can install vue 3 in laravel 9. first you can install vue 3 from scratch or you can use laravel breeze inertia vue. We will see both.

1. Install Vue 3 in Laravel With Vite From Scratch

Create Laravel Project

composer create-project laravel/laravel laravel-vite-vue

Install vue 3 with vue-loader.

 npm install vue@next vue-loader@next

Install @vitejs/plugin-vue.

npm i @vitejs/plugin-vue

Install npm.

npm install && npm run dev 

Import @vitejs/plugin-vue in vite.config.js.

vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'


export default defineConfig({
    plugins: [
        vue(),
        laravel([
            'resources/css/app.css',
            'resources/js/app.js',
        ]),
    ],
});

import and mount vue 3 in resources/js/app.js.

resources/js/app.js

import './bootstrap';

import { createApp } from 'vue';

import app from './Page/app.vue'

createApp(app).mount("#app")

Create Page Folder and app.vue file.

resources/js/Page/app.vue

<template>
    <h1>
        Laravel 9 vite with vue 3
    </h1>
</template>

Next, you need define root in blade file and @vite directive

resources/views/welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel 9 with vue 3 vite</title>

    </head>
    <body>
        <div id="app"></div>
        @vite('resources/js/app.js')
    </body>
</html>

You need to npm run build or npm run dev command to create asset vue file.

npm run dev

and

php artisan serve

laravel 9 vite vue 3

2. Install Vue 3 in Inertia Using Laravel Breeze

Create Laravel Project

composer create-project laravel/laravel laravel-inertia-vue

Next, you need to run below command in your terminal

composer require laravel/breeze --dev

Run below command to Install Inertia vue 3.

php artisan breeze:install vue
 // and...
npm install
npm run dev
php artisan migrate

You need to npm run build or npm run dev command to create asset vue file.

npm run dev

and

php artisan serve

How To Install Vue 3 in Laravel 9 with Vite

In this short blog, You will learn How to Install Vue 3 in Laravel 9 with Vite.

Laravel has just released "laravel 9.19" with a major change. There is no more webpack.mix.js file in the laravel root in the place of the webpack.mix.js file vite.config.js file is introduced.

In this post, we will learn how to install Vue js 3 in laravel 9.19 with vite. This post shows you how to install vue 3 in laravel 9 with the latest upgrades. If you want to see an example of installing vue 3 in laravel-vite then you are in the right place. Laravel 9.19 with vite is the latest version of the laravel framework at the writing of this article. As you know Laravel is the most popular PHP framework and it’s easy to use scale, and flexible. Vue js is a progressive framework for building user interfaces and it is lightweight and easy to use and learn. Vue 3 is the latest version of the Vuejs Framework and growing rapidly.

By the end of this post, you’ll be able to create a Vue 3 and Laravel 9.19 application powered by vite. We’ll also learn how to create a vue3 component and connect it with laravel 9 blade file.

How To Install Vue 3 in Laravel 9 with Vite

Use the following steps to install Vue 3 in the laravel 9 application.

  • Install laravel 9 App
  • Install NPM Dependencies
  • Install Vue 3
  • Update vite.config.js
  • Compile the assets
  • Create Vue 3 App
  • Create Vue 3 Component
  • Connect Vue 3 Component with Laravel blade file and use vite directive to add assets.
  • Update Laravel Routes
  • Start The Local Server

1. Install laravel 9 App

First, open Terminal and run the following command to create a fresh laravel project:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-vue3-vite

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel9-vue3-vite

2. Install NPM Dependencies

Run the following command to install frontend dependencies:

npm install

Step 3: Install Vue 3

Now after installing node modules we need to install vue 3 in our application, for that execute the following command in the terminal npm install vue@next vue-loader@next. vue-loader is a loader for webpack that allows you to author Vue components in a format called Single-File Components. vue-loader@next is a loader that is for webpack to author Vue components in single-file components called SFCs.

npm install vue@next vue-loader@next

Step 4: Install vitejs/plugin-vue plugin

In laravel 9 latest release install vitejs/plugin-vue plugin for installing vue3 or vue in laravel. This plugin provides required dependencies to run the vuejs application on vite. Vite is a  build command that bundles your code with Rollup and runs of localhost:3000 port to give hot refresh feature.

npm i @vitejs/plugin-vue

Step 4: Update vite.config.js file

Vite is a module bundler for modern JavaScript applications. Open vite.config.js and copy-paste the following code. First invoice defineConfig from vite at the top of the file and also import laravel-vite-plugin. Here plugins() take the path of the js and CSS file and create bundles for your application. you need to add vue() in the plugins array.

// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'


export default defineConfig({
    plugins: [
        vue(),
        laravel([
            'resources/css/app.css',
            'resources/js/app.js',
        ]),
    ],
});

Step 4: Vite Dev Server Start

Now after installing the vue 3, we need to start the dev server for vite for that run the following command and it will watch your resources/js/app.js file and resources/css/app.css file. It also starts a vite server on http://localhost:3000. you can not open it in the browser as it is for vite hot reload and it runs in the background and watches the assets of your application like js and CSS.

npm run dev

Step 5: Create Vue 3 App

In resources/js/app.js create an instance of the vue 3 firstly you import { createApp } from 'vue' and createApp It takes a parameter here we have passed App. Before that, you can create a vue file which is the main file responsible for the vuejs content name is App.vue.

// app.js
require('./bootstrap');

import {createApp} from 'vue'

import App from './App.vue'

createApp(App).mount("#app")

Step 6: Create Vue 3 Component

Under the js folder create a file name 'App.vue' and write content for this example let’s write simple "How To Install Vue 3 in Laravel 9 with Vite - TechvBlogs" you can change it according to your requirement.

<template>
    How To Install Vue 3 in Laravel 9 with Vite - TechvBlogs
</template>

Step 7: Connect Vue 3 Component with Laravel blade file

In this step, go-to resource / views  directory, create the  app.blade.php  file, and add the following code to app.blade.php  as follow:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>How To Install Vue 3 in Laravel 9 with Vite</title>

	@vite('resources/css/app.css')
</head>
<body>
	<div id="app"></div>

	@vite('resources/js/app.js')
</body>
</html>

Step 8: Update Laravel Routes

Open routes/web.php and replace welcome.blade.php with vue.blade.php file to load the vue.blade.php file where our vuejs code will execute.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('app');
});

Step 9: Update .env file

Open .env file and update APP_URL and set APP_URL=http://localhost:8000. It will help vite to check the js and CSS updates and changes them in the browser instantly.

APP_URL=http://localhost:8000

Step 10: Start the Local server

Now open a new terminal and execute the following command from your terminal to run the development server. It runs the project on localhost 8000 port by default but you can change it also. Run npm run dev server also so that site will watch the changes in the vuejs templates and will update automatically to the browser. if you are running another project on the same port number.

php artisan serve

and navigate to the following link http://localhost:8000/

Thank you for reading this blog.

You can find the GitHub repository here suresh-ramani/laravel-vue3-vite.

#laravel #vue #vite

Install Vue 3 on Laravel 9 with Vite
Keith  Evans

Keith Evans

1667065080

How to Use Markdown in Vite & React

vite-plugin-react-markdown

Compile Markdown to React component.

  • Use Markdown as React components
  • Use React components in Markdown

🐱‍🚀 Install

Install

ni @pity/vite-plugin-react-markdown -D 
# yarn/npm/pnpm add @pity/vite-plugin-react-markdown -D

Add it to vite.config.js

/** .... */
import Markdown from '@pity/vite-plugin-react-markdown'
export default defineConfig({
  plugins: [
    react(),
    Markdown({
      wrapperComponentName: 'ReactMarkdown',
      wrapperComponentPath: './src/components/page',
      // if you want use components in md file, please add it in this
      // [ComponentName]: `componentPath`
      // 🐱‍🚀: the `ComponentName` must be `CamelCase`
      importComponentsPath: {
        ReactTest: './src/components/pages/mdtest',
      },
      // markdownItUses: [
      //   prism,
      // ],
    }),
  ],
})

the default importComponentsPath is ~/src/components/pages/*.tsx if you don't provide importComponentsPath

And import it as a normal React component

import Hello from './README.md'
function  App() {
  return (
    <div className="App">
      <Hello />
    </div>
  )
}

🐱‍🐉 Use React components in Markdown

You can even use React components inside your markdown, for example

<ReactTest />

👾 Frontmatter

Frontmatter will be parsed,

For example:

---
name: My Cool App
---

# Hello World

Will be rendered as

<h1>Hello World</h1>

And you can use frontmatter in other and import it from this markdown file.

import {attributes} from './README.md'
// attributes = {name: 'My Cool App'}

Options

@pity/vite-plugin-react-markdown uses markdown-it under the hood, see markdown-it's docs for more details

// vite.config.js
import Markdown from '@pity/vite-plugin-react-markdown'

export default {
  plugins: [
    Markdown({
      // default options passed to markdown-it
      // see: https://markdown-it.github.io/markdown-it/
      markdownItOptions: {
        html: true,
        linkify: true,
        typographer: true,
      },
      // A function providing the Markdown It instance gets the ability to apply custom settings/plugins
      markdownItSetup(md) {
        // for example
        md.use(require('markdown-it-anchor'))
        md.use(require('markdown-it-prism'))
      },
      // Class names for the wrapper div
      wrapperClasses: 'markdown-body'
    })
  ],
}

See the tsdoc for more advanced options

🤷‍♂️ Example

See the /example.

🤷‍♀️ TypeScript Shim

declare module '*.md' {
  import type React from 'react'
  const ReactComponent: React.VFC
  export default ReactComponent
}

👏 Credits

This project is inspired by vite-plugin-vue-markdown and mosts of code is from geekris1/vite-plugin-react-markdown

Compare with it:

geekris1/vite-plugin-react-markdown is does'n work in wrapperComponent, and some style is not good.


Download Details:

Author: priority3
Source Code: https://github.com/priority3/vite-plugin-react-markdown

License: MIT license

#react #vite 

How to Use Markdown in Vite & React
Keith  Evans

Keith Evans

1667050260

Youtube Clone App using React js , Rapid Api, Axios, Vite.js

Youtube-Clone

Youtube clone app using react js , rapid api, axios, vite.js

Steps To Generate PR(Pull Request)

  • (Star ⭐ & Fork 🍽️) this repository.
  • Follow brijesh get it merged fast.

Fork this repository

Fork this repository by clicking on the fork button on the top of this page. This will create a copy of this repository in your account.

Clone the repository

Now clone the forked repository to your system. Go to your GitHub account, open the forked repository, click on the code button and then clone the repository.

if you want to use the terminal, use the following command:

git clone https://github.com/segfault-00/Youtube-Clone

Steps To start project

npm install 
npm run dev

use React.js to add something in this project

Create a branch

Then create a branch on your local repository to solve a problem.

terminal command

git checkout -b your_new_branch_name

Add & commit

Add your changes(folder) to that branch. 
 

Make necessary changes and commit those changes.

terminal commands

git add .
git commit -m "your-commit-message"

Push changes to GitHub

Finally push your local repository to remote repository Compare & Submit a Pull Request

terminal commands

git push origin <branch-name>

Then go to your repository on GitHub, you'll see a Compare & Pull request button. By clicking on that button you can submit your PR.

Have a great time.


.env

API_KEY=806e8e51fbmshd10d124bfd1947fp1c8d12jsn044e04d49402

.gitignore

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

Download Details:

Author: segfault-00
Source Code: https://github.com/segfault-00/Youtube-Clone

#react #vite 

Youtube Clone App using React js , Rapid Api, Axios, Vite.js
Keith  Evans

Keith Evans

1666884746

Minimal Starter Template For Vite with React, TypeScript and Tailwind

Starter Kit for Vite, React, TypeScript, Tailwind and Node.js ESM

Minimal, sensible defaults, fast.

Read the blog post about this template.

Technologies

screenshot of App.tsx

Setup

  • Press the "Use this template" on the top of this repository's GitHub page.
  • Run pnpm install (or npm install if you don't use pnpm).
  • pnpm dev for development.
  • Use pnpm test to run tests.
  • pnpm build for production builds.

Note: You can install pnpm via homebrew on macOS: brew install pnpm.

Protips for the fastest Developer Experience

  • Use npm-run-all to parallelize local test runs.
  • Prettier and eslint have --cache flags. Use them!
  • Do not run prettier inside of eslint. It commonly takes 50% of the eslint runtime!
  • Automatically sort imports when running prettier/saving the document via @trivago/prettier-plugin-sort-imports.
  • Use swc with ts-node for fast node scripts with ESM. See below ↓

Run node scripts with ESM and TypeScript, fast.

Create a script.ts file, run chmod x script.ts and execute it via ./script.ts.

#!/usr/bin/env node --no-warnings --experimental-specifier-resolution=node --loader ts-node/esm

console.log('Your code goes here.');

Use this to restart your scripts instantly when a file changes:

#!/usr/bin/env NODE_ENV=development node --watch --no-warnings --experimental-specifier-resolution=node --loader ts-node/esm

console.log('This processes instantly restarts when a file changes.');

Download Details:

Author: cpojer
Source Code: https://github.com/cpojer/vite-ts-react-tailwind-template

License: MIT license

#react #typescript #vite #tailwindcss 

Minimal Starter Template For Vite with React, TypeScript and Tailwind

How to Install React JS in Laravel 9 with Vite

In this section we will install React JS in Laravel 9 with Vite. In Laravel 9.19 come with Vite tool. There is two way you can install React in Laravel 9. First you can install React JS from scratch or you can use Laravel breeze inertia React. We will see both.

Source: https://larainfo.com

#laravel #reactjs #vite 

How to Install React JS in Laravel 9 with Vite