Hongkiat https://www.hongkiat.com/blog/category/coding/ Tech and Design Tips Tue, 10 Sep 2024 13:05:00 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 1070734 Getting Started with Flask https://www.hongkiat.com/blog/getting-started-with-flask/ Tue, 10 Sep 2024 15:00:55 +0000 https://www.hongkiat.com/blog/?p=72853 Flask is a lightweight and flexible micro-framework for Python that makes it easy to get started with web development. It’s designed to be simple and minimalistic, offering essential tools and features needed for building a web application, while allowing developers to have full control over how to implement additional features. It is a “micro-framework,” which…

The post Getting Started with Flask appeared first on Hongkiat.

]]>
Flask is a lightweight and flexible micro-framework for Python that makes it easy to get started with web development. It’s designed to be simple and minimalistic, offering essential tools and features needed for building a web application, while allowing developers to have full control over how to implement additional features.

Flask logo

It is a “micro-framework,” which means it doesn’t require specific tools or libraries. This gives developers the freedom to decide how they want to extend their application, making Flask a good choice for those who prefer flexibility and customization. If you’re coming from PHP, this could be an alternative to using other micro-frameworks like Slim. If you’re coming from Ruby, you might find Flask similar to Sinatra.

Let’s see how we can get started with Flask and build a simple web page.

Install Flask

First, we need to install Flask. We can do this by running:

pip install flask

Create the App File

Next, we need to create a Python file, for example, app.py. To get started, we add the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello Flask!"

The Flask class is used to create an instance of the app. The @app.route('/') decorator maps the homepage URL, /, to the home function, which returns the message “Hello Flask!”.

Run the App

Now, run the app using the following command:

flask run --debug

When we visit http://127.0.0.1:5000/ in the web browser, we’ll see the message “Hello Flask!”.

In this case, we also run the app in debug mode, which automatically reloads the server when you make changes to the code. This is useful for development, as you can see the changes immediately without having to restart the server. Keep in mind that you’d want to disable debug mode when deploying your application to a production server.

Routing

One of the main features provided by Flask is routing. Routing is the process of mapping URLs to functions that handle requests. In the example above, we defined a route for the homepage using the @app.route('/') decorator. This tells Flask to call the home function when the user visits the homepage URL, /.

We can define routes for other pages as well. For example, to create an About page, we can add the following code:

@app.route('/about')
def about():
    return "This is the About page."

Now, if we load http://127.0.0.1:5000/about, we’ll see the message “This is the About page.”.

Wrapping up

Flask is a great choice for both beginners and experienced developers, especially when you want flexibility without the complexity of larger frameworks like Django.

In this article, we’ve covered the basics of how Flask works with some simple examples such as how to spin up the development server, and we learned a bit about routing in Flask to create static pages. In future articles, we’ll explore more advanced topics like rendering templates, working with forms, handling requests, and connecting to databases.

So stay tuned!

The post Getting Started with Flask appeared first on Hongkiat.

]]>
72853
Getting Started with CSS @property Rule https://www.hongkiat.com/blog/css-property-rule/ Mon, 02 Sep 2024 10:00:09 +0000 https://www.hongkiat.com/blog/?p=72701 The CSS @property is a powerful feature that brings more control and flexibility to custom properties, also known as CSS variables. It is introduced as part of the CSS Houdini project, which is designed to provide developers with deeper access to the browser’s rendering engine. The @property rule allows you to define custom properties with…

The post Getting Started with CSS @property Rule appeared first on Hongkiat.

]]>
The CSS @property is a powerful feature that brings more control and flexibility to custom properties, also known as CSS variables.

It is introduced as part of the CSS Houdini project, which is designed to provide developers with deeper access to the browser’s rendering engine. The @property rule allows you to define custom properties with specific types, default values, and even the capability to animate CSS properties.

In this article, we’ll explore what the @property rule is, why it’s useful, and how you can leverage it in your web projects.

What is @property for?

CSS custom properties, also known as CSS variables, have made styles more reusable. It allows you to define a value once and use it throughout your stylesheet.

However, one limitation has been the inability to specify a property’s type or set default values directly in CSS. This means any value can be assigned to a custom property, which can lead to unexpected results and make it harder to maintain your styles in some situations.

This is where the @property rule comes in. It allows you to set a default value, provides a fallback value that will be used if the custom property is not explicitly set, enables custom property animation, and defines a type for a custom property.

This ensures that a variable can only accept a specific data type, such as a length, color, or number.

The type of the property is defined with the syntax property. It accepts a string value defining the CSS type value, as follows:

Type Description
<length> Any valid <length> values e.g., 10px, 2em, 50%, 3rem
<number> Any valid <number> values e.g., 1, 0.5, -3, 100
<percentage> Any valid <percentage> values e.g., 50%, 100%, 25%
<length-percentage> Any valid <length-percentage> values e.g., 10px, 50%, 2em, 75%
<color> Any valid <color> values e.g., #ff0000, rgb(255, 0, 0), rgba(255, 0, 0, 0.5), blue
<image> Any valid <image> values e.g., url(image.jpg), linear-gradient(to right, red, blue)
<url> Any valid url() values e.g., url(‘https://example.com/image.jpg’)
<integer> Any valid <integer> values e.g., 1, -10, 42
<angle> Any valid <angle> values e.g., 45deg, 0.5turn, 1rad
<time> Any valid <time> values e.g., 1s, 500ms, 0.75s
<resolution> Any valid <resolution> values e.g., 300dpi, 2dppx
<transform-function> Any valid <transform-function> values e.g., rotate(45deg), scale(1.5), translateX(100px)
<custom-ident> Any valid <custom-ident> values e.g., –my-variable, custom-identifier
<transform-list> A list of valid <transform-function> values e.g., rotate(45deg) scale(1.5) translateX(100px)

Example

Let’s say we have a button component. We’d like to define some defaults on this component. Traditionally, we could use custom properties to define the background color and border radius of the button component, like so:

.button {
  background-color: #fff;
  border-radius: 8px;
}

Or, use CSS variables to define the values once and reuse them throughout the stylesheet:

:root {
  --button-bg: #fff;
  --button-rounded: 8px;
}

But, what if we want to ensure that the background color is always a valid color value, and the border radius is always a valid length value?

We can use the @property rule to define the type of these custom properties and set default values.

To do so, we could create a couple of custom properties defined with the following options in the @property rule:

@property --button-bg {
  syntax: '<color>';
  initial-value: #0D74CE;
  inherits: false;
}
@property --button-rounded {
  syntax: '<length>';
  initial-value: 8px;
  inherits: false;
}

In this example, we have two custom properties defining the background color and border radius of the button component.

We use the syntax property to define the type of the custom property, while the initial-value property sets the default value.

We also use the inherits property to specify whether the custom property inherits its value from its parent element, in which case we set them all to false to avoid inheritance.

Once they are set, we can now use these custom properties in our styles, like so:

.button {
  background-color: var(--button-bg);
  border-radius: var(--button-rounded);
}

See the Pen CSS @property by HONGKIAT (@hkdc) on CodePen.

Wrapping up

The CSS @property rule brings a significant step forward to CSS custom properties, or CSS variables. All major and latest browsers already support the CSS @property rule.

Browser Desktop Version Mobile Version
Google Chrome 85 and later 85 and later
Mozilla Firefox 128 and later Not supported
Safari 15.4 and later 15.4 and later (iOS)
Microsoft Edge 85 and later 85 and later
Opera 71 and later 71 and later
Samsung Internet 14.0 and later 14.0 and later

To sum up, the CSS @property rule is a powerful feature and a great addition to the CSS language that can help you write more maintainable and type-safe stylesheets. If you haven’t already, give it a try in your next project!

The post Getting Started with CSS @property Rule appeared first on Hongkiat.

]]>
72701
A Look Into: CSS “:is” Selector https://www.hongkiat.com/blog/css-is-selector/ Fri, 26 Jul 2024 10:00:08 +0000 https://www.hongkiat.com/blog/?p=72377 The CSS :is selector is a handy pseudo-selector that simplifies complex selector queries. It allows you to group multiple selectors into a single, more readable form, which can help reduce redundancy and make your CSS more maintainable. Before the :is selector, you’d need to repeat the same styles for multiple selectors, leading to long and…

The post A Look Into: CSS “:is” Selector appeared first on Hongkiat.

]]>
The CSS :is selector is a handy pseudo-selector that simplifies complex selector queries. It allows you to group multiple selectors into a single, more readable form, which can help reduce redundancy and make your CSS more maintainable.

Before the :is selector, you’d need to repeat the same styles for multiple selectors, leading to long and repetitive code. For example, if you wanted to apply the same styles under the main element to the a and the button elements, you would write:

main a,
main button {
  color: blue;
}

With the :is selector, you can group the selectors into a single line:

main :is(a, button) {
  color: blue;
}

You can also combine it with other pseudo-selector, for example, the :hover, which in this example we will make the color to orange.

main :is(a, button):hover {
  color: orange;
}

As you can see, the :is selector simplifies the code and makes it easier to read. It’s especially useful when you have a long list of selectors that share the same styles.

Specificity

One important thing to note about the :is selector is that it doesn’t affect the specificity of the selector. The specificity of the :is selector is the same as the most specific selector within the group. For example, in the following code:

main :is(a, button) {
  color: green;
}

main a,
main button {
  color: red;
}

The specificity of the :is(a, button) selector is the same as the a selector, which means that if there are conflicting styles, which ever style is defined last will be applied. In this case, we are going to see the color of the button and the anchor will turn red.

See the Pen CSS :is selector by HONGKIAT (@hkdc) on CodePen.

But keep in mind that if there’s a more specific selector within the group, the specificity of the :is selector will be the same as that selector. For example, in the following code…

main :is(a, .btn) {
  color: green;
}

main a,
main button {
  color: red;
}  

…we have class selector, .button, to select the button element so the specificity of the :is(a, .btn) selector is the same as the .btn selector, which means that the color of both the button and the link will turn green.

See the Pen CSS :is selector by HONGKIAT (@hkdc) on CodePen.

Conclusion

The :is selector simplifies complex selector queries. It allows you to group multiple selectors into a single, more readable form, which can help reduce redundancy and make your code easier to read. However, keep in mind the specificity of the :is selector is the same as the most specific selector within the group, so be careful when using it in your stylesheets.

Browser Compatibility

Browser Desktop Version Desktop Support Mobile Version Mobile Support
Google Chrome 88 and later Supported 88 and later Supported
Mozilla Firefox 78 and later Supported 78 and later Supported
Safari 14.1 and later Supported 14.5 and later (iOS) Supported
Microsoft Edge 88 and later Supported N/A N/A
Opera 75 and later Supported 61 and later Supported
Internet Explorer Not supported Not supported N/A N/A
Samsung Internet N/A N/A 14.0 and later Supported

The post A Look Into: CSS “:is” Selector appeared first on Hongkiat.

]]>
72377
10 Alternative Frameworks to Laravel https://www.hongkiat.com/blog/laravel-alternatives/ Tue, 09 Jul 2024 13:00:54 +0000 https://www.hongkiat.com/blog/?p=72287 While Laravel is popular for its rich features and ease of use, there are many other PHP frameworks that might better suit your needs. In this article, we will explore 10 great alternatives to Laravel, each with its own unique strengths and features. Whether you’re looking for something lightweight, highly customizable, or built for high…

The post 10 Alternative Frameworks to Laravel appeared first on Hongkiat.

]]>
While Laravel is popular for its rich features and ease of use, there are many other PHP frameworks that might better suit your needs.

In this article, we will explore 10 great alternatives to Laravel, each with its own unique strengths and features. Whether you’re looking for something lightweight, highly customizable, or built for high performance, I believe there’s an option here for you.

Without further ado, let’s jump in to see the full list.

FrameworkX

FrameworkX logo

FrameworkX is a lightweight PHP microframework created by Christian Luck, designed for building high-performance, real-time applications. It uses an event-driven, non-blocking architecture based on ReactPHP components, making it ideal for high-concurrency and real-time updates such as chat apps and live notifications.

Unlike Laravel, FrameworkX is minimalistic and doesn’t include built-in features like an ORM, templating engine, or expressive helper functions. This minimalism provides flexibility, allowing you to choose and integrate your own preferred libraries for templating, database abstraction, and other functionalities.

Check out our post on how to get started with FrameworkX.

PHP Minimum Requirement: 7.1

PROS

  • High-performance and real-time capabilities
  • Lightweight and minimalistic
  • Event-driven architecture based on ReactPHP components

CONS

  • Requires more manual integration to incorporate other features
  • Less expressive syntax compared to Laravel
  • Requires some getting used to if you are not familiar with event-driven architecture

Visit FrameworkX

CodeIgniter

CodeIgniter logo

CodeIgniter is a lightweight PHP framework originally developed by EllisLab and now maintained by the CodeIgniter Foundation. Similar to Laravel, it follows a more structured architecture and offers many essential features for an MVC framework.

However, it lacks some of Laravel's expressive syntax, like the Eloquent ORM and built-in front-end integrations. Despite this, its simplicity makes it easy to pick up for developers with fair experience in PHP, object-oriented programming, and MVC concepts.

PHP Minimum Requirement: 8.1

PROS

CONS

  • Smaller ecosystem compared to Laravel
  • No built-in ORM
  • No built-in templating engine like Blade
  • Lack of expressive syntax
  • Lack of built-in front-end integration

Visit CodeIgniter

Laminas

Laminas logo

Laminas, formerly known as Zend Framework, is a PHP framework designed for enterprise-grade applications. It offers a collection of professional PHP packages for developing web applications and services. These components are framework-agnostic and comply with PSR (PHP Standard Recommendations), so they can be used outside Laminas.

Laminas differs significantly from Laravel. While Laravel focuses on developer experience, rapid development, and includes full-stack features built-in like Eloquent ORM and Blade, Laminas offers a more modular approach. It provides more flexibility but may require more configuration and setup time compared to Laravel.

PHP Minimum Requirement: 8.1.0

PROS

  • Highly modular and customizable
  • Strong focus on security and enterprise-level features
  • Scalable and suitable for large-scale applications
  • First-party ecosystem: Mezzio, API Tools, and MVC framework

CONS

  • Less expressive syntax
  • No built-in CLI, ORM, and templating engine
  • May require more manual integration for some of its components

Visit Laminas

Slim

Slim framework logo

Slim is a PHP micro-framework developed by Josh Lockhart that focuses on essentials like routing, middleware, and HTTP request handling.

Unlike Laravel's full-stack approach, Slim does not include a full MVC layer, a native template engine, or a database abstraction layer, so you'll need to use your own preferred libraries and components if you need one.

This minimal footprint, however, makes Slim a great choice if you're looking to create lightweight RESTful APIs or microservices.

PHP Minimum Requirement: 8.1

PROS

  • Lightweight and fast
  • Simple and easy to use
  • Ideal for small to medium-sized projects and APIs
  • Extensible with middleware and third-party components

CONS

  • Limited built-in features compared to full-stack frameworks
  • Requires additional libraries for ORM and templating engine

Visit Slim

Nette

Nette framework logo

Nette is a mature and feature-rich PHP framework created by David Grudl. It offers a comprehensive set of tools and components for building web applications, including a powerful templating engine called Latte, forms handling, database abstraction, and many other components.

Nette differs from Laravel in its focus. While Laravel prioritizes developer experience with features like Eloquent ORM, Blade, and the Artisan CLI included and pre-configured, Nette provides its first-party components separately. This allows you to choose which tools and libraries you'd need to include in your project. Despite its modularity, it provides a base application or skeleton to help you quickly start your projects.

PHP Minimum Requirement: 8.1

PROS

  • Matured and battle-tested framework, built since 2004
  • Comprehensive set of tools and components for building websites
  • Provides base or skeleton with flexible structure
  • Powerful templating engine: Latte
  • Good documentation and community support

CONS

  • Less opinionated than Laravel
  • Requires more manual configuration and setup
  • Smaller ecosystem compared to Laravel

Visit Nette

Phalcon

Phalcon framework logo

Phalcon is a unique PHP framework. Unlike the others, it is delivered as a C extension. Designed to optimize speed by bypassing PHP's interpreter and leveraging lower-level system resources directly, it includes full-stack features like a first-party ORM library, router, caching, and more.

Phalcon sets itself apart from Laravel with its architecture as a C extension. Unlike Laravel, which is implemented purely in PHP, Phalcon requires installing a PHP extension, so you need to be comfortable with commands like apt and PHP .ini configuration files to enable the extension. I think Phalcon is ideal for projects where performance is critical and can handle heavy workloads with minimal overhead.

PHP Minimum Requirement: 8.0

PROS

  • High performance due to its nature as a C extension
  • Full-stack features included like ORM, caching, dependency injection, i18n, templating engine, and router

CONS

  • Requires installing a PHP extension, which can be overwhelming for beginners
  • Much smaller ecosystem compared to Laravel

Visit Phalcon

Yii2

Yii2 framework logo

Yii2 is a PHP framework created by Qiang Xue, offering extensive features like an ORM, RESTful API, debugging tools, a boilerplate generator, and much more.

Yii2, I think, is quite similar to Laravel in its approach and principles. Unlike some frameworks where features are in separate modules, Yii2 has them built-in and pre-configured with MVC architecture. It also provides a starter kit with basic interfaces and functionality, similar to Laravel Breeze. Additionally, Yii2 also provides solid first-party modules like the Mailing module, i18n module, Docker for localhost, a first-party templating engine, and front-end integration with Bootstrap.

PHP Minimum Requirement: 7.3

PROS

  • Support for PHP 7.3, if you still need it
  • One of the earliest frameworks in PHP. It’s solid and battle-tested
  • First-party modules and tools included and pre-configured
  • Gii, one of its unique features to generate codes
  • Great documentation and community support

CONS

  • Smaller ecosystem compared to Laravel
  • Less expressive syntax compared to Laravel
  • Has a somewhat unusual namespacing pattern

Visit Yii2

Spiral

Spiral framework logo

Spiral is a high-performance PHP framework developed by the team at Spiral Scout. It is built around RoadRunner, a PHP application server written in Go, which enables it to handle heavy workloads efficiently and reduce the overhead that may commonly occur in traditional PHP applications.

Spiral uses a classic MVC approach and features a routing system similar to Laravel. However, it exclusively runs with RoadRunner, offering twice the performance out of the box compared to typical PHP MVC frameworks. It also includes components like JOBS, Worker, and BirdDog, specifically optimized for RoadRunner, leading to more optimized and faster applications.

PHP Minimum Requirement: 8.1

PROS

  • High performance due to its integration with RoadRunner
  • General-purpose framework that allows you to build MVC, CQRS, Event-Driven, and CLI apps
  • First-party ORM library, CycleORM, which I think looks neat!

CONS

  • Some learning curves, probably requires learning RoadRunner and how it works
  • Smaller ecosystem compared to Laravel

Visit Spiral

Neutomic

Neutomic framework logo

Neutomic is a lightweight PHP framework designed for environments that require long-running processes. Built on top of RevoltPHP, Neutomic supports event-driven, non-blocking I/O operations, making it efficient for handling concurrent tasks.

Neutomic differs from Laravel in its use of an event-driven, non-blocking architecture, while Laravel uses a traditional synchronous design by default. Neutomic requires third-party libraries for features like ORM and templating, whereas Laravel includes these features built-in. To get started with an example of a Neutomic application, you can check out the skeleton repository at neutomic/skeleton.

PHP Minimum Requirement: 8.3

PROS

  • Lightweight and minimalistic
  • High-performance and efficient for handling concurrent tasks
  • Event-driven architecture based on RevoltPHP and Amp components

CONS

  • Requires more manual integration to incorporate other features, but it provides a skeleton to help you get started
  • Less expressive syntax compared to Laravel
  • Requires some getting used to if you are not familiar with event-driven architecture

Visit Neutomic

The post 10 Alternative Frameworks to Laravel appeared first on Hongkiat.

]]>
72287
Introduction to FrameworkX https://www.hongkiat.com/blog/frameworkx/ Mon, 01 Jul 2024 13:00:07 +0000 https://www.hongkiat.com/blog/?p=72250 PHP has come a long way and continues to improve with new features, syntax, and speed. The ecosystem is also expanding, with many developers creating frameworks to simplify the lives of other developers. Popular, full-featured frameworks like Laravel and Symfony exist, as do lightweight microframeworks like FrameworkX. It is a lightweight microframework for PHP that…

The post Introduction to FrameworkX appeared first on Hongkiat.

]]>
PHP has come a long way and continues to improve with new features, syntax, and speed. The ecosystem is also expanding, with many developers creating frameworks to simplify the lives of other developers. Popular, full-featured frameworks like Laravel and Symfony exist, as do lightweight microframeworks like FrameworkX.

It is a lightweight microframework for PHP that uses an event-driven, non-blocking architecture, similar to Node.js which is perfect for high-concurrency and real-time applications like chat apps or live notifications.

In this article, we will explore what FrameworkX is and how it differs from traditional PHP frameworks. Let’s get started!

Getting Started

First, make sure you have PHP and Composer set up on your computer. Once installed, you can add FrameworkX to your project with this command:

composer require clue/framework-x

FrameworkX doesn’t require a complex setup. All you need is a public/index.php file. Here’s a basic example to display “Hello World!” on the homepage:

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$app = new FrameworkX\App();
$app->get('/', fn () => \React\Http\Message\Response::plaintext("Hello world!\n"));
$app->run();

To run your application, type:

php public/index.php

This command starts a local server using PHP’s built-in server, backed by the ReactPHP Socket component. No need for Nginx or Apache. Your server will run at http://127.0.0.1:8080, and it should display “Hello World!”.

Localhost server setup

Besides plain text, you can also return JSON data. For example:

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$users = [['name' => 'Jon Doe'], ['name' => 'Jane Doe']];

$app = new FrameworkX\App();
$app->get('/', fn () => \React\Http\Message\Response::json($users));
$app->run();

Async Operations

PHP operations are usually blocking and synchronous, meaning each task must finish before the next one starts. FrameworkX is built on the ReactPHP library.

ReactPHP is a library that provides components such as the EventLoop, Stream, Promise, Async, and HTTP components, which enable asynchronous operations. Thus, tasks can run concurrently without waiting for others to finish. This is ideal for handling multiple connections, HTTP requests, or I/O operations simultaneously.

In this example, we’ve updated our index.php to fetch an API. Instead of using the curl_* functions, we will use the HTTP component to make an asynchronous request.

$app = new FrameworkX\App();
$app->get('/', function () {
    echo "Start\n";
    (new \React\Http\Browser())
        ->get('https://www.hongkiat.com/blog/wp-json/wp/v2/posts')
        ->then(function () {
            echo "End (API)\n";
        });
    echo "End\n";

    return \React\Http\Message\Response::plaintext("Hello world!\n");
});
$app->run();

Normally, an external API request would block the page from rendering until the request completes. However, with the asynchronous operations that the ReactPHP HTTP component handles, the page loads instantly, as evidenced by the log.

Async operations log

This makes FrameworkX capable of handling many more concurrent requests than traditional PHP setups, significantly speeding up page load times. But how fast is it?

Speed

I tested FrameworkX on a basic, inexpensive DigitalOcean droplet with 1 vCPU and 1GB of RAM. It handled around 4,000 requests per second effortlessly.

Concurrency Level:      50
Time taken for tests:   22.636 seconds
Complete requests:      100000
Failed requests:        0
Keep-Alive requests:    100000
Total transferred:      17400000 bytes
HTML transferred:       1300000 bytes
Requests per second:    4417.69 [#/sec] (mean)
Time per request:       11.318 [ms] (mean)
Time per request:       0.226 [ms] (mean, across all concurrent requests)
Transfer rate:          750.66 [Kbytes/sec] received

Even with additional workload, like disk read operations and rendering 100 lists from a JSON file, it still managed around 2700 requests per second.

Concurrency Level:      50
Time taken for tests:   36.381 seconds
Complete requests:      100000
Failed requests:        0
Keep-Alive requests:    100000
Total transferred:      296700000 bytes
HTML transferred:       280500000 bytes
Requests per second:    2748.72 [#/sec] (mean)
Time per request:       18.190 [ms] (mean)
Time per request:       0.364 [ms] (mean, across all concurrent requests)
Transfer rate:          7964.31 [Kbytes/sec] received

I’m pretty sure it could be much faster with better server specifications.

Wrapping Up

FrameworkX is a powerful, lightweight microframework for PHP. It runs asynchronously and is capable of handling multiple tasks efficiently, similar to Node.js. It’s the perfect framework whether you’re building a simple app or complex high-concurrency or real-time applications.

The post Introduction to FrameworkX appeared first on Hongkiat.

]]>
72250
Introduction to FrankenPHP https://www.hongkiat.com/blog/frankenphp/ Thu, 13 Jun 2024 13:00:53 +0000 https://www.hongkiat.com/blog/?p=72086 FrankenPHP is a new PHP runtime designed to modernize PHP architecture. It is built on top of Caddy, and it includes Caddy’s built-in features such as automatic SSL, native support for HTTP3, and Early Hints. It also supports compression methods like Gzip, Brotli, and Zstd. Additionally, it features a built-in Mercure hub, enabling real-time push…

The post Introduction to FrankenPHP appeared first on Hongkiat.

]]>
FrankenPHP is a new PHP runtime designed to modernize PHP architecture. It is built on top of Caddy, and it includes Caddy’s built-in features such as automatic SSL, native support for HTTP3, and Early Hints. It also supports compression methods like Gzip, Brotli, and Zstd. Additionally, it features a built-in Mercure hub, enabling real-time push events without the need for additional libraries or SDKs.

With all these features, FrankenPHP promises faster performance out-of-the-box, simpler configuration, and an improved Developer Experience (DX) compared to traditional PHP setups like PHP-FPM.

Here is how it compares:

Feature FrankenPHP PHP-FPM
Performance Great performance with worker mode and direct communication with the web server, reducing latency. Good performance, but it requires FastCGI communication which may introduce some overhead.
Scalability Excellent scalability. It can be compiled into a single binary, making it easy to run on serverless architectures. Good scalability, but often requires manual tuning of process pools on both the PHP-FPM and the web server side (usually Nginx).
Complexity Generally simple with minimal configuration overhead, thanks to Caddy’s configuration. Somewhat complex, involving separate configurations for PHP-FPM and the web server (usually Nginx).

Getting Started

Running FrankenPHP requires Docker. It is pre-packaged in a single Docker image, so you don’t need to install PHP binaries and modules yourself. Once you have Docker installed, you need to create the index.php file, which will serve as the homepage.

In this example, let’s keep it simple. I will just print the PHP info table.

<?php 
    phpinfo();

You can now run the following Docker command to start the site:

docker run -v $PWD:/app/public -p 80:80 -p 443:443 -p 443:443/udp dunglas/frankenphp

This command mounts the current directory to the /app/public directory in the Docker container and maps ports 80 and 443 from the container to the host machine, as well as 443/udp to enable HTTP3.

Caddy also generates SSL certificates and loads the site over HTTPS. However, your browser won’t recognize the SSL certificate for localhost, so you will receive an error when you load the site.

SSL error message

There are a few ways we can create a workaround to let HTTPS load on localhost. The easiest and quickest method that works in different scenarios is to enable the flag in Chrome at chrome://flags/#allow-insecure-localhost. Restart Chrome, and then reload the page.

Loaded localhost site

Now, your localhost runs on the FrankenPHP server API. If you inspect the response in Chrome, you’ll see that it’s compressed with zstd and served through HTTP3.

It’s impressive that we can have it running with just a single command.

Running a Framework

FrankenPHP is not limited to just running a simple PHP file. It is compatible and can run a full-fledged PHP framework such as Symfony, Laravel, or any other PHP framework. The only thing you need to do is mount the framework directory to the /app/public directory in the Docker container. For example, to run a Laravel application, you can run the following command:

docker run -v $PWD:/app -p 80:80 -p 443:443 -p 443:443/udp dunglas/frankenphp

It’s that simple. FrankenPHP will automatically detect the files and serve the Laravel application.

Laravel app running

Wrapping Up

All these features like automatic SSL, HTTP3, and modern compression make developing and running PHP applications much easier and faster. If you’re coming from nginx or Apache, like me, the only thing you need to get used to is the Caddyfile configuration. But once you get accustomed to it, you’ll find it much simpler and more powerful than traditional web server configurations.

I think FrankenPHP is a great choice for modern PHP applications. It’s fast, scalable, and easy to use. I highly recommend it for any PHP developers looking to give it a try.

The post Introduction to FrankenPHP appeared first on Hongkiat.

]]>
72086
How to Create a Personalized AI Assistant with OpenAI https://www.hongkiat.com/blog/create-chatbot-with-openai/ Wed, 24 Apr 2024 13:00:50 +0000 https://www.hongkiat.com/blog/?p=71735 We've created an AI assistant to help answer basic queries about our blog posts. Here's how we did it.

The post How to Create a Personalized AI Assistant with OpenAI appeared first on Hongkiat.

]]>
Imagine having your own virtual assistant, kind of like J.A.R.V.I.S from the Iron Man movie, but personalized for your needs. This AI assistant is designed to help you tackle routine tasks or anything else you teach it to handle.

In this article, we’ll show you an example of what our trained AI assistant can achieve. We’re going to create an AI that can provide basic insights into our site’s content, assisting us in managing both the site and its content more effectively.

To build this, we’ll use three main stacks: OpenAI, LangChain, and Next.js.

OpenAI

OpenAI, if you don’t already know, is an AI research organization known for their ChatGPT, which can generate human-like responses. They also provide an API that allows developers to access these AI capabilities to build their own applications.

To get your API key, you can sign up on the OpenAI Platform. After signing up, you can create a key from the API keys section of your dashboard.

A white dashboard showing the list of menu and a button to generate the API key
API keys section on the OpenAI platform dashboard.

Once you’ve generated an API key, you have to put it in your computer as an environment variable and name it OPENAI_API_KEY. This is a standard name that libraries like OpenAI and LangChain look for, so you don’t need to pass it manually later on.

Do note that Windows, macOS, and Linux each have their own way to set an environment variable.

Windows
  1. Right-click on “This PC” or “My Computer” and select “Properties“.
  2. Click on “Advanced system settings” on the left sidebar.
  3. In the System Properties window, click on the “Environment Variables” button.
  4. Under “System variables” or “User variables“, click “New” and enter the name, OPENAI_API_KEY, and value of the environment variable.
macOS and Linux

To set a permanent variable, add the following to your shell configuration file such as ~/.bash_profile, ~/.bashrc, ~/.zshrc.

export OPENAI_API_KEY=value

LangChain

LangChain is a system that helps computers understand and work with human language. In our case, it provides tools that will help us convert text documents into numbers.

You might wonder, why do we need to do this?

Basically, AI, machines, or computers are good at working with numbers but not with words, sentences, and their meanings. So we need to convert words into numbers.

This process is called embedding.

It makes it easier for computers to analyze and find patterns in language data, as well as helps to understand the semantics of the information they are given from a human language.

A diagram showing the process of embedding words 'fancy cars' into numbers from left to right

For example, let’s say a user sends a query about “fancy cars“. Rather than trying to find the exact words from the information source, it would probably understand that you are trying to search for Ferrari, Maserati, Aston Martin, Mercedes Benz, etc.

Next.js

We need a framework to create a user interface so users can interact with our chatbot.

In our case, Next.js has everything we need to get our chatbot up and running for the end-users. We will build the interface using a React.js UI library, shadcn/ui. It has a route system for creating an API endpoint.

It also provides an SDK that will make it easier and quicker to build chat user interfaces.

Data and Other Prerequisites

Ideally, we’ll also need to prepare some data ready. These will be processed, stored in a Vector storage and sent to OpenAI to give more info for the prompt.

In this example, to make it simpler, I’ve made a JSON file with a list of title of a blog post. You can find them in the repository. Ideally, you’d want to retrieve this information directly from the database.

I assume you have a fair understanding of working with JavaScript, React.js, and NPM because we’ll use them to build our chatbot.

Also, make sure you have Node.js installed on your computer. You can check if it’s installed by typing:

node -v

If you don’t have Node.js installed, you can follow the instructions on the official website.

How’s Everything Going to Work?

To make it easy to understand, here’s a high-level overview of how everything is going to work:

  1. The user will input a question or query into the chatbot.
  2. LangChain will retrieve related documents of the user’s query.
  3. Send the prompt, the query, and the related documents to the OpenAI API to get a response.
  4. Display the response to the user.

Now that we have a high-level overview of how everything is going to work, let’s get started!

Installing Dependencies

Let’s start by installing the necessary packages to build the user interface for our chatbot. Type the following command:

npx create-next-app@latest ai-assistant --typescript --tailwind --eslint

This command will install and set up Next.js with shadcn/ui, TypeScript, Tailwind CSS, and ESLint. It may ask you a few questions; in this case, it’s best to select the default options.

Once the installation is complete, navigate to the project directory:

cd ai-assistant

Next, we need to install a few additional dependencies, such as ai, openai, and langchain, which were not included in the previous command.

npm i ai openai langchain @langchain/openai remark-gfm

Building the Chat Interface

To create the chat interface, we’ll use some pre-built components from shadcn/ui like the button, avatar, and input. Fortunately, adding these components is easy with shadcn/ui. Just type:

npx shadcn-ui@latest add scroll-area button avatar card input

This command will automatically pull and add the components to the ui directory.

Next, let’s make a new file named Chat.tsx in the src/components directory. This file will hold our chat interface.

We’ll use the ai package to manage tasks such as capturing user input, sending queries to the API, and receiving responses from the AI.

The OpenAI’s response can be plain text, HTML, or Markdown. To format it into proper HTML, we’ll use the remark-gfm package.

We’ll also need to display avatars within the Chat interface. For this tutorial, I’m using Avatartion to generate avatars for both the AI and the user. These avatars are stored in the public directory.

Below is the code we’ll add to this file.

'use client';

import { Avatar, AvatarFallback, AvatarImage } from '@/ui/avatar';
import { Button } from '@/ui/button';
import {
    Card,
    CardContent,
    CardFooter,
    CardHeader,
    CardTitle,
} from '@/ui/card';
import { Input } from '@/ui/input';
import { ScrollArea } from '@/ui/scroll-area';
import { useChat } from 'ai/react';
import { Send } from 'lucide-react';
import { FunctionComponent, memo } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import ReactMarkdown, { Options } from 'react-markdown';
import remarkGfm from 'remark-gfm';

/**
 * Memoized ReactMarkdown component.
 * The component is memoized to prevent unnecessary re-renders.
 */
const MemoizedReactMarkdown: FunctionComponent<Options> = memo(
    ReactMarkdown,
    (prevProps, nextProps) =>
        prevProps.children === nextProps.children &&
        prevProps.className === nextProps.className
);

/**
 * Represents a chat component that allows users to interact with a chatbot.
 * The component displays a chat interface with messages exchanged between the user and the chatbot.
 * Users can input their questions and receive responses from the chatbot.
 */
export const Chat = () => {
    const { handleInputChange, handleSubmit, input, messages } = useChat({
        api: '/api/chat',
    });

    return (
        <Card className="w-full max-w-3xl min-h-[640px] grid gap-3 grid-rows-[max-content,1fr,max-content]">
            <CardHeader className="row-span-1">
                <CardTitle>AI Assistant</CardTitle>
            </CardHeader>
            <CardContent className="h-full row-span-2">
                <ScrollArea className="h-full w-full">
                    {messages.map((message) => {
                        return (
                            <div
                                className="flex gap-3 text-slate-600 text-sm mb-4"
                                key={message.id}
                            >
                                {message.role === 'user' && (
                                    <Avatar>
                                        <AvatarFallback>U</AvatarFallback>
                                        <AvatarImage src="/user.png" />
                                    </Avatar>
                                )}
                                {message.role === 'assistant' && (
                                    <Avatar>
                                        <AvatarImage src="/kovi.png" />
                                    </Avatar>
                                )}
                                <p className="leading-relaxed">
                                    <span className="block font-bold text-slate-700">
                                        {message.role === 'user' ? 'User' : 'AI'}
                                    </span>
                                    <ErrorBoundary
                                        fallback={
                                            <div className="prose prose-neutral">
                                                {message.content}
                                            </div>
                                        }
                                    >
                                        <MemoizedReactMarkdown
                                            className="prose prose-neutral prose-sm"
                                            remarkPlugins={[remarkGfm]}
                                        >
                                            {message.content}
                                        </MemoizedReactMarkdown>
                                    </ErrorBoundary>
                                </p>
                            </div>
                        );
                    })}
                </ScrollArea>
            </CardContent>
            <CardFooter className="h-max row-span-3">
                <form className="w-full flex gap-2" onSubmit={handleSubmit}>
                    <Input
                        maxLength={1000}
                        onChange={handleInputChange}
                        placeholder="Your question..."
                        value={input}
                    />
                    <Button aria-label="Send" type="submit">
                        <Send size={16} />
                    </Button>
                </form>
            </CardFooter>
        </Card>
    );
};

Let’s check out the UI. First, we need to enter the following command to start the Next.js localhost environment:

npm run dev

By default, the Next.js localhost environment runs at localhost:3000. Here’s how our chatbot interface will appear in the browser:

Setting up the API endpoint

Next, we need to set up the API endpoint that the UI will use when the user submits their query. To do this, we create a new file named route.ts in the src/app/api/chat directory. Below is the code that goes into the file.

import { readData } from '@/lib/data';
import { OpenAIEmbeddings } from '@langchain/openai';
import { OpenAIStream, StreamingTextResponse } from 'ai';
import { Document } from 'langchain/document';
import { MemoryVectorStore } from 'langchain/vectorstores/memory';
import OpenAI from 'openai';

/**
    * Create a vector store from a list of documents using OpenAI embedding.
    */
const createStore = () => {
    const data = readData();

    return MemoryVectorStore.fromDocuments(
        data.map((title) => {
            return new Document({
                pageContent: `Title: ${title}`,
            });
        }),
        new OpenAIEmbeddings()
    );
};
const openai = new OpenAI();

export async function POST(req: Request) {
    const { messages } = (await req.json()) as {
        messages: { content: string; role: 'assistant' | 'user' }[];
    };
    const store = await createStore();
    const results = await store.similaritySearch(messages[0].content, 100);
    const questions = messages
        .filter((m) => m.role === 'user')
        .map((m) => m.content);
    const latestQuestion = questions[questions.length - 1] || '';
    const response = await openai.chat.completions.create({
        messages: [
            {
                content: `You're a helpful assistant. You're here to help me with my questions.`,
                role: 'assistant',
            },
            {
                content: `
                Please answer the following question using the provided context.
                If the context is not provided, please simply say that you're not able to answer
                the question.

            Question:
                ${latestQuestion}

            Context:
                ${results.map((r) => r.pageContent).join('\n')}
                `,
                role: 'user',
            },
        ],
        model: 'gpt-4',
        stream: true,
        temperature: 0,
    });
    const stream = OpenAIStream(response);

    return new StreamingTextResponse(stream);
}

Let’s break down some important parts of the code to understand what’s happening, as this code is crucial for making our chatbot work.

First, the following code enables the endpoint to receive a POST request. It takes the messages argument, which is automatically constructed by the ai package running on the front-end.

export async function POST(req: Request) {
    const { messages } = (await req.json()) as {
        messages: { content: string; role: 'assistant' | 'user' }[];
    };
}

In this section of the code, we process the JSON file, and store them in a vector store.

const createStore = () => {
    const data = readData();

    return MemoryVectorStore.fromDocuments(
        data.map((title) => {
            return new Document({
                pageContent: `Title: ${title}`,
            });
        }),
        new OpenAIEmbeddings()
    );
};

For the sake of simplicity in this tutorial, we store the vector in memory. Ideally, you would need to store it in a Vector database. There are several options to choose from, such as:

Then we retrieve of the relevant piece from the document based on the user query from it.

const store = await createStore();
const results = await store.similaritySearch(messages[0].content, 100);

Finally, we send the user’s query and the related documents to the OpenAI API to get a response, and then return the response to the user. In this tutorial, we use the GPT-4 model, which is currently the latest and most powerful model in OpenAI.

const latestQuestion = questions[questions.length - 1] || '';
const response = await openai.chat.completions.create({
    messages: [
        {
            content: `You're a helpful assistant. You're here to help me with my questions.`,
            role: 'assistant',
        },
        {
            content: `
            Please answer the following question using the provided context.
            If the context is not provided, please simply say that you're not able to answer
            the question.

        Question:
            ${latestQuestion}

        Context:
            ${results.map((r) => r.pageContent).join('\n')}
            `,
            role: 'user',
        },
    ],
    model: 'gpt-4',
    stream: true,
    temperature: 0,
});

We use a simple very prompt. We first tell OpenAI to evaluate the user’s query and respond to user with the provided context. We also set the latest model available in OpenAI, gpt-4 and set the temperature to 0. Our goal is to ensure that the AI only responds within the scope of the context, instead of being creative which can often lead to hallucination.

And that’s it. Now, we can try to chat with the chatbot; our virtual personal assistant.

Wrapping Up

We’ve just built a simple chatbot! There’s room to make it more advanced, certainly. As mentioned in this tutorial, if you plan to use it in production, you should store your vector data in a proper database instead of in memory. You might also want to add more data to provide better context for answering user queries. You may also try tweaking the prompt to improve the AI’s response.

Overall, I hope this helps you get started with building your next AI-powered application.

The post How to Create a Personalized AI Assistant with OpenAI appeared first on Hongkiat.

]]>
71735
How to Install Python on Mac for Beginners https://www.hongkiat.com/blog/install-python-mac/ Wed, 13 Mar 2024 15:00:14 +0000 https://www.hongkiat.com/blog/?p=71482 Python isn’t just another programming language; it’s a gateway to creating amazing things, from simple scripts that automate your boring tasks to complex systems that can analyze heaps of data or even build the next big social media platform. By default, Mac comes with Python already installed. However, chances are it might not be the…

The post How to Install Python on Mac for Beginners appeared first on Hongkiat.

]]>
Python isn’t just another programming language; it’s a gateway to creating amazing things, from simple scripts that automate your boring tasks to complex systems that can analyze heaps of data or even build the next big social media platform.

By default, Mac comes with Python already installed. However, chances are it might not be the latest version. So, whether you’re looking to update your Mac’s Python to the latest version, or for some reason it’s not installed on your Mac and you want it to be, this article is for you.

Why bother updating or installing a new Python, you ask?

Well, with every new release, Python gets a little bit smarter, faster, and safer, thanks to new features and important security patches. So, whether you’re coding for fun, for work, or something in between, having the latest version of Python at your fingertips can really amp up your game.

In this guide, I’m going to walk you through the steps to check which Python version is currently installed on your Mac, how to update it, and how to install Python on your Mac should it not come with it.

Checking the Current Version of Python on Your Mac

Before going into the installation process, it’s wise to check the version of Python that’s currently installed on your Mac. This step is crucial as it helps determine whether an update is necessary.

To do this:

  1. Open the Terminal application. You can find Terminal in the Utilities folder within your Applications folder or search for it using Spotlight.
  2. Type python --version or python3 --version in the Terminal and press Enter. The system will display the version of Python currently installed.
1. If Python is Installed

The Terminal will display a message like Python 3.11.3. This indicates that Python is indeed installed on your Mac, and the version is 3.11.3.

Example:

hongkiat@hongkiat ~ % python
Python 3.11.3 (main, Apr  7 2023, 19:25:52) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

The version number might vary depending on the latest version you have installed. Now, you might want to hop over to python.org and check if this is the latest version of Python. If it’s not, you’ll want to update it to the latest version.

latest version of Python

Why Update Python?

Keeping Python updated on your Mac ensures that you have access to the latest features, security patches, and performance improvements.

Newer versions also tend to have better compatibility with third-party libraries and tools, making your development work smoother and more efficient.

2. If Python Doesn’t Exist

If Python is not installed, or if there’s an issue with the PATH configuration that prevents the Terminal from recognizing the Python command, you might encounter a message such as command not found: python or No such file or directory.

This response means that the Terminal cannot find Python installed in the usual directories where it looks for installed applications and commands. In the case of such an output, it’s a clear signal that Python might need to be installed or there’s a need to fix the PATH environment variable to ensure the Terminal can locate the Python executable.

Therefore, you might want to proceed with installing a new copy of Python on your Mac.

Preparing Your Mac for Python Installation

Before installing Python, make sure your Mac is ready.

This includes:

  • Updating macOS to the latest version through the Settings > General > Software Update
  • Installing Xcode Command Line Tools by running xcode-select --install in Terminal. These tools are required for compiling some of Python’s packages.

How to Install Python on Mac (2 Ways)

There are two easy ways to install Python on your Mac: either using Homebrew or directly from Python.org. In this article, we are going to cover both of them.

1. Installing Python Using Homebrew

Homebrew is a popular package manager for macOS that simplifies the installation of software. If you haven’t installed Homebrew yet, you can do so by pasting the installation command (available on the Homebrew website) into the Terminal.

homebrew installation instructions

Alternatively, check out this section of one of our articles on how to install Homebrew on your Mac.

Once Homebrew is installed, you can install Python by following these steps:

  1. Open Terminal.
  2. Type brew install python and press Enter.

Homebrew will download and install the latest Python version.

2. Installing Python Directly from Python.org

Another method to install Python is by downloading it directly from the official Python website:

  1. Visit Python.org and navigate to the Downloads section.
  2. Select macOS and download the latest Python installer.
  3. Open the downloaded file and follow the on-screen instructions to install Python.

Setting Up Your Python Environment

After successfully installing Python on your Mac, setting up your Python environment is the next crucial step. Properly setting up your environment ensures that you can run Python scripts from the Terminal and manage libraries or packages efficiently.

Configuring the PATH Environment Variable

The PATH environment variable is a critical part of your system’s configuration. It tells the Terminal where to find the executable files for the commands you issue. In environments where both Python 2 and Python 3 are installed, it’s important to map python to python 3 to ensure that the python command targets Python 3 specifically.

For Python, ensuring that your system knows where to find the Python interpreter is essential.

If Python was installed via Homebrew or directly from Python.org and you’re still unable to execute Python commands in the Terminal, you might need to add Python to your PATH manually.

To add Python to your PATH:

  1. Open the Terminal.
  2. Type nano ~/.zshrc or nano ~/.bash_profile, depending on your shell (macOS Catalina and newer uses zsh by default).
  3. Add the line export PATH="/usr/local/bin/python3:$PATH" to the file. Adjust the path /usr/local/bin/python3 according to where Python is installed on your system. This is typically the default location for Python installations via Homebrew.
  4. Press Control + O to save the file, then Control + X to exit nano.
  5. Type source ~/.zshrc or source ~/.bash_profile to reload your profile and apply the changes.

Verifying the Installation

To verify that Python and pip are correctly installed:

  1. Open Terminal.
  2. Type python --version or python3 --version to check the Python version.

Updating Python on Your Mac

Now, if your Mac already has Python installed and all you need is just to update it to the latest version, here’s what you can do.

  • If you used Homebrew, simply run brew update and then brew upgrade python.
  • If you installed Python from Python.org, download and install the latest version from their website following the same process as a new installation.

FAQ

Last but not least, I’ll leave you with some common questions, answers, and essential python tips related to installing and utilizing Python on your Mac more effectively.

How do I switch between multiple Python versions on my Mac?

To switch between multiple Python versions, you can use a version management tool like pyenv. It allows you to install multiple versions of Python and easily switch between them by setting the global or local (per-project) Python version.

Can I have both Python 2 and Python 3 installed on my Mac at the same time?

Yes, you can have both Python 2 and Python 3 installed on your Mac simultaneously. macOS typically comes with Python 2.7 pre-installed, and you can install Python 3 alongside it. Use python or python2 to run Python 2 and python3 for Python 3.

How can I uninstall Python from my Mac?

Uninstalling Python from your Mac depends on how it was installed. If you installed it using Homebrew, you could uninstall it with brew uninstall python.

For Python installations from python.org, you’ll need to manually remove the Python frameworks from your system directories. Exercise caution and ensure you’re not uninstalling the system’s default Python interpreter.

Why is it recommended to use Homebrew to install Python on Mac?

Using Homebrew to install Python on Mac is recommended because it simplifies the installation process and makes it easy to manage Python versions and dependencies.

Homebrew ensures that you install Python in a separate directory from the macOS system Python, preventing potential conflicts.

The post How to Install Python on Mac for Beginners appeared first on Hongkiat.

]]>
71482
Essential Command Line Skills for Web Designers https://www.hongkiat.com/blog/web-designers-essential-command-lines/ https://www.hongkiat.com/blog/web-designers-essential-command-lines/#comments Fri, 23 Feb 2024 10:00:29 +0000 https://www.hongkiat.com/blog/?p=21759 If you’ve ever followed a web design or development tutorial, you might have seen instructions asking you to use commands like npm install or git clone. These instructions are for the Command Line Interface (CLI), a tool we use to instruct the computer to carry out specific actions, typically by entering commands in Terminal or…

The post Essential Command Line Skills for Web Designers appeared first on Hongkiat.

]]>
If you’ve ever followed a web design or development tutorial, you might have seen instructions asking you to use commands like npm install or git clone. These instructions are for the Command Line Interface (CLI), a tool we use to instruct the computer to carry out specific actions, typically by entering commands in Terminal or Command Prompt.

For web designers, using Terminal or Command Prompt might not seem the easiest, especially if you’re more accustomed to graphical interfaces. However, command line tools such as Yeoman, Bower, and Google Web Starter Kit rely on command line inputs.

If the thought of typing commands seems daunting, this article will introduce you to a few simple command lines to get you started and make you more comfortable with using them.

Before We Begin…

Let’s discuss Terminal and Command Prompt first. These applications grant you access to the operating system’s heart. It’s crucial to understand that once you make a change here, it cannot be undone. Therefore, any actions taken in these environments must be approached with care – only proceed if you’re confident in what you’re doing.

Another key point is the inability to use the mouse within Terminal or Command Prompt. This means you can’t search or select text using the mouse. All interactions are through the keyboard, making keyboard shortcuts invaluable.

For Windows users, it’s important to note that some commands might not be available. In such cases, I recommend using tools like Cygwin, UnxUtils, or Windows Services for UNIX Version 3.5 to bring UNIX utilities to Windows. Now, get ready to dive in with enthusiasm.

Changing Directories

Navigating through directories is a common task. Both Terminal and Command Prompt utilize the cd command for changing your current directory to a specified destination. For example, to move to a folder named foo, you would type:

cd foo

The current directory is displayed before the blinking cursor, as shown below.

Example of cd command in Terminal

To dive into a sub-directory of foo, you can do it in one step:

cd foo/sub-folder

If you need to go back to the previous directory or move up one level from your current directory, simply type:

cd ..

Creating a New Folder

The mkdir command is handy when you need to create a new directory. To make a directory named foo, you would use the following command:

mkdir foo

Creating multiple directories simultaneously is also straightforward. The next command will create three directories named foo, hello, and world in one go:

mkdir foo hello world

This mkdir command works in both Terminal and Command Prompt.

Creating a New File

To create an empty file, the touch command is what you need. For instance, to create a file named filename.html, you would type:

touch filename.html

If you want to create several files at once, just list them all in the command like so:

touch file.html style.css

Moving Files

To move a file to a specific folder, use the mv command. For instance, to move style.css into a folder named /css, the command is:

mv style.css /css

The mv command can also be used to rename files and folders. To rename index.html to about.html, you would use:

mv index.html about.html

Copying Files

To copy a file, the cp command (or copy on Windows) is used. For example, copying index.html and naming the duplicate as about.html can be done with:

cp index.html about.html

Remember, on Windows platforms, you should use the copy command.

Listing Directory Contents

One of my most frequently used commands is the List Directory command, also known as ls. This command allows you to view all the contents within a directory.

Example of ls command output

By specifying a folder name before the ls command, you can list the contents of that particular folder, as shown below:

Listing contents of a specific folder with ls command

To get more details about the contents, such as creation date, permissions, and owners, use ls -l or ll.

Detailed listing with ls -l command

Note that the ls command works in UNIX shells, meaning it’s suitable for Ubuntu and OS X but not for Windows. For Windows, you’ll need to use the dir command instead.

Using dir command in Windows

Opening Files

To open files or folders in their default applications, use the open command. For example, to open the Desktop folder in Finder:

open ~/Desktop

To open a .txt file in TextEdit (the default plain text editor in OS X), you would use:

open readme.txt

Windows users should opt for the edit command for a similar effect. To open a text file in the default editor, the command is:

edit readme.txt

Creating Symbolic Links

Symbolic links, or Symlinks, function like shortcut folders, yet the system recognizes them as actual folders. A favorite use case of mine for Symlinks is to sync folders from /Dropbox to my /Sites directory, where I store all my web development projects.

Here’s how you specify the command:

ln -s /source /destination

To link your /Dropbox to the /Sites folder, execute:

ln -s ~/Dropbox/project ~/Sites/project

For Windows, the equivalent command is mklink /d.

Using the Nano Editor

If you need to set up a new VirtualHost with a new domain name, you’ll likely need to edit the hosts file that maps domain names to IP addresses. The fastest way to do this is by using the following command:

sudo nano /etc/hosts

Sublime Text Command Line Interface

Sublime Text includes a command line interface (CLI), subl, allowing operation through Terminal and Command Prompt. Initially, the Terminal won’t recognize the subl command.

To integrate Sublime Text CLI, execute this command:

ln -s "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" ~/bin/subl

With this setup, you can open files directly, such as style.css, using:

subl style.css

Adding --add to your command opens files or folders in the existing Sublime Text window:

subl --add foo

For additional options, subl --help will guide you.

Mastering these command lines and starting with the basics will reveal that commands can be more efficient than graphical interfaces for certain tasks. Hopefully, this guide helps you begin your journey.

Further Reading: Command Line Mastery

Explore more through these posts, which teach you various tasks using command lines:

The post Essential Command Line Skills for Web Designers appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/web-designers-essential-command-lines/feed/ 20 21759
A Comprehensive Guide on Date Formatting for Global Websites https://www.hongkiat.com/blog/date-internationalization-api/ https://www.hongkiat.com/blog/date-internationalization-api/#comments Fri, 02 Feb 2024 10:00:36 +0000 https://www.hongkiat.com/blog/?p=23910 Mastering date formats is essential for websites with a global audience. Different regions prefer distinct date formats, and aligning with these preferences is key to user engagement and international success. This guide dives into the effective use of JavaScript’s Internationalization API, as defined by ECMA, for customizing date displays in various languages and cultural norms.…

The post A Comprehensive Guide on Date Formatting for Global Websites appeared first on Hongkiat.

]]>
Mastering date formats is essential for websites with a global audience. Different regions prefer distinct date formats, and aligning with these preferences is key to user engagement and international success. This guide dives into the effective use of JavaScript’s Internationalization API, as defined by ECMA, for customizing date displays in various languages and cultural norms. Learn how to handle different date formats, currencies, and time zones with ease.

Our focus: leveraging the Internationalization API for seamless and efficient date formatting across different languages and regions.

Display Date and Time: How to Do It Right

Display Date and Time: How to Do It Right

We come across them dates and time... well, every day. When it comes to the Web, you can... Read more

Determining the User’s Locale

To display the date in the user’s preferred local format, it’s important to first identify their locale. The most straightforward method is to allow users to choose their language and regional preferences on your webpage.

If direct user selection isn’t viable, other approaches include interpreting the Accept-Language header from user requests or utilizing the navigator.language (for Chrome and Firefox) or navigator.browserLanguage (for Internet Explorer) properties in JavaScript.

However, it’s important to note that these methods may not always accurately reflect the user’s browser UI language preference.

 var language_tag = window.navigator.browserLanguage || window.navigator.language || "en";
 // returns language tags like 'en-GB'
 

Verifying Internationalization API Support

To determine if a browser supports the Internationalization API, we can check for the presence of the global Intl object.

 if(window.hasOwnProperty("Intl") && typeof Intl === "object"){
 // The Internationalization API is available for use
 } 

Exploring the Intl Object

The Intl object in JavaScript serves as a gateway to the Internationalization API. It contains three constructor properties: Collator for string comparison, NumberFormat for number formatting, and DateTimeFormat for date and time formatting. Our focus will be on DateTimeFormat, which is instrumental in adapting date and time presentation to different languages.

Capabilities of the DateTimeFormat Object

The DateTimeFormat constructor in JavaScript takes two optional arguments:

  • locales – This can be a string or an array of strings indicating language tags, such as “de” for German or “en-GB” for English as used in the United Kingdom. In the absence of a specific language tag, the default locale of the runtime environment is used.
  • options – An object whose properties allow customization of the date formatter. It includes properties such as:
Property Description Possible values
day Day of the month “2-digit”, “numeric”
era Era in which the date falls, e.g., AD or BC “narrow”, “short”, “long”
formatMatcher Algorithm used for format matching “basic”, “best fit” [Default]
hour Hour of the day “2-digit”, “numeric”
hour12 Whether to use 12-hour format (true) or 24-hour format (false) true, false
localeMatcher Algorithm used for matching locales “lookup”, “best fit” [Default]
minute Minute of the hour “2-digit”, “numeric”
month Month of the year “2-digit”, “numeric”, “narrow”, “short”, “long”
second Second of the minute “2-digit”, “numeric”
timeZone Time zone to use for formatting “UTC”, default to the runtime’s time zone
timeZoneName Name of the time zone “short”, “long”
weekday Day of the week “narrow”, “short”, “long”
year Year “2-digit”, “numeric”

Example:

 var formatter = new Intl.DateTimeFormat('en-GB');
 // Returns a formatter for UK English date format
 var options = {weekday: 'short'};
 var formatter = new Intl.DateTimeFormat('en-GB', options);
 // Returns a formatter for UK English date format with weekday

Utilizing the format Function

The DateTimeFormat object includes a property accessor named format. This function is designed to format a Date object according to the specified locales and options within the DateTimeFormat instance.

It accepts either a Date object or undefined as an optional argument, returning a formatted date string.

Note: If no argument is provided, or if it’s undefined, the function defaults to formatting the current date using Date.now().

Here’s how it works:

 new Intl.DateTimeFormat().format()
 // Returns the current date in the format specific to the runtime's locale

Let’s explore some simple date formatting examples:

Now, let’s see how changing the language affects the output:

Next, let’s delve into the versatility of the formatting options:

Using the toLocaleDateString Method

As an alternative to the formatter approach, you can use Date.prototype.toLocaleDateString for similar functionality. This method also utilizes the locales and options arguments. While it’s similar to using the DateTimeFormat object, the latter is recommended for applications handling a large number of dates.

 var mydate = new Date('2015/04/22');
 var options = {
   weekday: "short", 
   year: "numeric", 
   month: "long", 
   day: "numeric"
 };

 console.log(mydate.toLocaleDateString('en-GB', options));
 // Outputs "Wed, 22 April 2015"

Checking Supported locales

To determine which locales are supported, the DateTimeFormat object’s supportedLocalesOf method can be used. This method returns an array of all supported locales or an empty array if none are supported. For example, to test, we can include a fictitious locale “blah” among the locales being checked.

 console.log(Intl.DateTimeFormat.supportedLocalesOf(["zh", "blah", "fa-pes"]));
 // Outputs Array [ "zh", "fa-pes" ]

References

The post A Comprehensive Guide on Date Formatting for Global Websites appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/date-internationalization-api/feed/ 5 23910
Creating a Next.js Dashboard for SQL Data Visualization https://www.hongkiat.com/blog/nextjs-dashboard-sql-visualization/ Thu, 25 Jan 2024 13:00:49 +0000 https://www.hongkiat.com/blog/?p=71096 Creating dashboards for visualizing SQL data has been a relevant demand for a long time. In contrast, technologies for building web apps change quite frequently, so developers meet this unchangeable demand differently every year. In this article, I’ve decided to share my latest professional experience developing a web app for visualizing data from a database.…

The post Creating a Next.js Dashboard for SQL Data Visualization appeared first on Hongkiat.

]]>
Creating dashboards for visualizing SQL data has been a relevant demand for a long time. In contrast, technologies for building web apps change quite frequently, so developers meet this unchangeable demand differently every year.

In this article, I’ve decided to share my latest professional experience developing a web app for visualizing data from a database.

Choosing technologies

One of the requirements I had was to use MySQL. However, I could freely choose the rest of my toolkit, including a framework.

React has always been popular among web developers for building rich user interfaces. I’ve also had a great experience using React in my previous projects and decided to refresh my skills with it.

But React is not actually a framework anymore. Reading through the React documentation, I’ve found out that from now on, projects should be created using one of the following React-based frameworks:

According to the React team, using a framework from the start ensures that the features used by most web applications are built-in, such as routing, HTML generation, data fetching, etc.

In this way, when your project reaches the point when such features are needed, you do not need to look for additional libraries and configure them for your project. Instead, all features are already available for you, making development much smoother. You can see more details on the React website.

This left me with one question…

Which framework should I use?

As with everything in this world, there is no universal React framework that suits every need.

I’ve decided to stop on Next.js for my project, and here is why:

The framework is chosen, but it’s not enough. We also need tools for connecting to MySQL and visualizing its data.

Choosing data visualization tools

You should carefully consider which third-party tools to use in your project since there are so many options and not every one of them might suit your needs. For me, the perfect choices were Flexmonster and Recharts.

Both of these tools are flexible, powerful, and easy to use.

  • Flexmonster is primarily a pivot table and allows working with different datasets, such as MySQL. It can also be integrated with various frameworks, including Next.js! Flexmonster’s documentation even provides a dedicated tutorial for integrating this tool with Next.js. Flexmonster is a paid tool, but it offers a 30-day trial, which was more than enough for me to get acquainted with the product and determine if it suits my use cases.
  • Recharts is a charting library with a wide selection of built-in charts and customization options. The library pairs especially well with Next.js applications since it uses React’s component-based architecture. Recharts is a free tool released under the MIT license, which is worth considering.

My deciding factor was the easy setup of Flexmonster, Recharts, and their communication. While Flexmonster connects to the MySQL dataset, processes its data, and visualizes the data in the pivot table, Recharts can use the processed data to visualize it in charts.

If you are wondering whether these tools fit your project, check out the best tools for data visualization in React article. It covers in great detail the different options on the market, their pros and cons, as well as their use cases.

Now that the preparations are complete let’s create the actual app!

Create a Next.js project

First, a basic Next.js app must be created with the following command:

npx create-next-app next-sql --ts --app && cd next-sql

Notice the --ts and --app arguments. They enable TypeScript and the new App Router feature, which this tutorial assumes in further instructions.

You will also be given prompts to enable other features, such as ESLint or Tailwind CSS. For simplicity, answer No. But if you know what you’re doing and these features are necessary for your project – feel free to enable them.

Also, it’s best to remove unnecessary data from the newly created project. For the purposes of this tutorial, we won’t need the public/ folder so you may delete it. If you think you might need this folder for other reasons, feel free to leave it where it is.

In addition, change the app/page.tsx file, so it has the following contents:

"use client"
import styles from './page.module.css'

export default function Home() {
  return (
    <main className={styles.main}>
    </main>
  );
}

It’s important that the page is marked as a Client Component because we will add features that can be used only when the page is rendered on the client side.

Finally, the unnecessary styles should be deleted from the app/page.module.css file so it has the following content:

.main {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 6rem;
  min-height: 100vh;
}

Embed data visualization tools

Next, we need to add Flexmonster and Recharts to our newly created project. Let’s start with Flexmonster.

Embedding Flexmonster

First, install the Flexmonster CLI:

npm install -g flexmonster-cli

Next, download the Flexmonster wrapper for React:

flexmonster add react-flexmonster

Now let’s add Flexmonster to our page:

  1. Import Flexmonster styles into the app/global.css file in your project:
    @import "flexmonster/flexmonster.css";
  2. Create the PivotWrapper Client Component (e.g., app/PivotWrapper.tsx) that will wrap FlexmonsterReact.Pivot:
      "use client"
      import * as React from "react";
      import * as FlexmonsterReact from "react-flexmonster";
      import Flexmonster from "flexmonster";
    
      type PivotProps = Flexmonster.Params & {
        pivotRef?: React.ForwardedRef<FlexmonsterReact.Pivot>;
      };
    
      const PivotWrapper: React.FC<PivotProps> = ({ pivotRef, ...params }) => {
        return (
          <FlexmonsterReact.Pivot
            {...params}
            ref={pivotRef}
          />
        );
      };
    
      export default PivotWrapper;
    
  3. Import the PivotWrapper into your Next.js page (e.g., app/page.tsx) as a dynamic component without SSR:
      import dynamic from "next/dynamic";
    
      const PivotWrapper = dynamic(() => import("@/app/PivotWrapper"), {
        ssr: false,
        loading: () => <p>Loading Flexmonster...</p>
      });
    

    The SSR is disabled because Flexmonster uses the window object, so it cannot be rendered on a server.

  4. In the same page file, create an additional component for ref forwarding (e.g., ForwardRefPivot):
      import * as React from "react";
      import { Pivot } from "react-flexmonster";
    
      const ForwardRefPivot = React.forwardRef<Pivot, Flexmonster.Params>(
        (props, ref?: React.ForwardedRef<Pivot>) => <PivotWrapper {...props} pivotRef={ref}/>
      );
    
  5. Inside the page component (e.g., Home), create an empty ref object (e.g., pivotRef):
      export default function Home() {
        const pivotRef: React.RefObject<Pivot> = React.useRef<Pivot>(null);
      }
    
  6. Then insert the ForwardRefPivot component from step 4 and pass the ref object as its prop:
      export default function Home() {
        const pivotRef: React.RefObject<Pivot> = React.useRef<Pivot>(null);
    
        return (
          <main className={styles.main}>
            <ForwardRefPivot
              ref={pivotRef}
              toolbar={true}
            />
          </main>
        );
      }
    

Now Flexmonster is ready to be used. Let’s move to Recharts.

Embedding Recharts

Start by installing Recharts with the following command:

npm install recharts

Then, import the LineChart component with its child components and insert them after the pivot table:

import { LineChart, Line, CartesianGrid, YAxis, XAxis } from "recharts";

export default function Home() {
  const pivotRef: React.RefObject<Pivot> = React.useRef<Pivot>(null);

  return (
    <main className={styles.main}>
      <ForwardRefPivot
        ref={pivotRef}
        toolbar={true}
      />

      <LineChart width={1000} height={300}>
        <Line type="monotone" stroke="#8884d8" />
        <CartesianGrid stroke="#ccc" />
        <XAxis />
        <YAxis />
      </LineChart>
    </main>
  );
}

Technically, we’ve added Recharts to our page, but we need to fill it with data. Let’s first create interfaces that will describe data for Recharts:

interface RechartsDataObject { [key: string]: any; }
interface RechartsData {
  data: RechartsDataObject[];
  xName: string;
  lineName: string;
}

Then, we need to create a variable that will hold the Recharts data. But remember, our data will come from Flexmonster, which can change at runtime. So we need some way of tracking changes to this data. That’s where React states come in handy. Add the following code to your page component:

export default function Home() {
  // Flexmonster instance ref
  const pivotRef: React.RefObject<Pivot> = React.useRef<Pivot>(null);
  // Recharts data
  const [chartsData, setChartsData] = React.useState<RechartsData>({ data: [], xName: "", lineName: "" });

  // Subscribe on Recharts data changes
  React.useEffect(() => {
    console.log("Charts data changed!");
  }, [chartsData]);
  // The rest of the code
}

Now, the data for Recharts will be stored in the chartsData variable, and thanks to the useState and useEffects React Hooks, we will know when it’s changed.

Lastly, we need to tell Recharts to use chartsData as its source of data by adding the following props:

<LineChart width={1000} height={300} data={chartsData.data}>
  <Line dataKey={chartsData.lineName} type="monotone" stroke="#8884d8" />
  <CartesianGrid stroke="#ccc" />
  <XAxis dataKey={chartsData.xName} />
  <YAxis />
</LineChart>

In the next section, let’s fill the chartsData with the data from Flexmonster so our pivot table and charts are synced.

Connecting Flexmonster and Recharts

In the app/page.tsx file, let’s create a function that transforms the data from Flexmonster so it can be accepted by Recharts:

import { GetDataValueObject } from "flexmonster";

function prepareDataFunction(rawData: Flexmonster.GetDataValueObject): RechartsData | null {
  // If there is no data, return null
  if (!rawData.data.length)
    return null;
  
  // Initialize chartsData object
  const chartsData: RechartsData = {
    data: [],
    xName: rawData.meta["r0Name" as keyof typeof rawData.meta],
    lineName: rawData.meta["v0Name" as keyof typeof rawData.meta]
  };
  
  // Transform Flexmonster data so it can be processed by Recharts
  // The first rawData element is skipped because it contains a grand total value, not needed for our charts
  for (let i = 1, dataObj, chartDataObj: RechartsDataObject; i < rawData.data.length; i++) {
    dataObj = rawData.data[i];
    chartDataObj = {};
    chartDataObj[chartsData.xName] = dataObj["r0" as keyof typeof dataObj];
    chartDataObj[chartsData.lineName] = dataObj["v0" as keyof typeof dataObj];
    chartsData.data.push(chartDataObj);
  }
  
  return chartsData;
}

To keep the tutorial simple, prepareFunction returns only data for the first row and measure. If you want to display data for another field or measure, move this field or measure to the first position using the Field List in Flexmonster.

Watch this video to see how it works:

Now, let’s add a function for chart drawing in the page component itself (e.g., Home). The function will call the previously created prepareFunction and update the chartsData state to trigger re-rendering:

export default function Home() {
  // Flexmonster instance ref
  const pivotRef: React.RefObject<Pivot> = React.useRef<Pivot>(null);
  
  // Recharts data
  const [chartsData, setChartsData] = React.useState<RechartsData>({ data: [], xName: "", lineName: "" });
  
  // Subscribe on Recharts data changes
  React.useEffect(() => {
    console.log("Charts data changed!");
  }, [chartsData]);
  
  // Function for chart drawing
  const drawChart = (rawData: GetDataValueObject) => {
    const chartsData = prepareDataFunction(rawData);
    if (chartsData) {
      setChartsData(chartsData);
    }
  }
  
  // The rest of the code
}

All that’s left is to tell Flexmonster to use this function when its data is changed. Add the following props to the ForwardRefPivot component:

<ForwardRefPivot
  ref={pivotRef}
  toolbar={true}
  // Connecting Flexmonster and Recharts
  reportcomplete={() => {
    pivotRef.current?.flexmonster.off("reportcomplete");
    pivotRef.current?.flexmonster.getData({}, drawChart, drawChart);
  }}
  licenseKey="XXXX-XXXX-XXXX-XXXX-XXXX"
/>

Here, we’ve subscribed to the reportcomplete event to know when Flexmonster is ready to provide data. When the event is triggered, we immediately unsubscribe from it and use the getData method to tell Flexmonster where to pass the data and what to do when it’s updated. In our case, we can use the drawChart function for both purposes.

Also, notice the licenseKey prop. It must contain a special trial key that will allow us to connect to Recharts. You can get such a key by contacting the Flexmonster team. Once you have the key, paste it in place of XXXX-XXXX-XXXX-XXXX-XXXX.

Flexmonster and Recharts are now connected, but they are still empty! Let’s fix it by connecting to a database!

Connecting to MySQL

Since Recharts gets data from Flexmonster, only the latter should be connected to the database. Fortunately, Flexmonster provides a ready-to-use solution – Flexmonster Data Server. This is a server application, so all aggregations are performed on the server side, which saves the browser’s resources and results in faster data visualization. This fits perfectly into the Next.js philosophy of putting heavy work on the server (see the SSG and SSR features).

We can install the Data Server using the previously installed Flexmonster CLI:

flexmonster add fds -r

Once the command is finished – Flexmonster Admin Panel will open. This is a tool for configuring the Data Server and its connections, also called indexes. Let’s configure one for our MySQL database.

  1. Open the Indexes tab and click Add New Index:
  2. Add New Index Screen
  3. Under the Name and Type fields, enter the connection’s name (e.g., next-sql) and select the Database type:
  4. Index Configuration Fields
  5. The Database type should be set to MySQL by default. Enter the Connection string and the Query for your database under the respective fields. For this tutorial, I have hosted a sample database on the freedb.tech service. Feel free to use this connection string and query:

    Connection string:

    Server=sql.freedb.tech;Port=3306;Uid=freedb_dkflbvbh;pwd=NpkyU?jYv!2Zn&B;Database=freedb_next_fm

    Query:

    SELECT CONCAT(first_name,' ',last_name) AS full_name,salary,TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS age FROM users

    The Refresh time indicates how often the data should be refreshed (0 means the data is not refreshed).

    When all the configurations are set, hit Create to establish the connection to the database:

  6. Database Connection Setup

Now, all that’s left is to visualize the data.

Visualize the data in the pivot table and charts

To visualize data prepared by the Data Server, we need to create a Flexmonster report.

A report is used to predefine configurations for Flexmonster Pivot. Our interest lies in the data source configuration for SQL databases.

We will represent our report as an object (e.g., report) that contains the following data:

const report = {
  dataSource: {
    type: "api",
    url: "http://localhost:9500",
    index: "next-sql"
  }
};

Let’s cover what each property stands for:

  • dataSource contains data source configurations for the pivot table component.

    For simplicity, I’ve specified only the required properties to visualize our data. There are many more options described in Flexmonster docs.

  • dataSource.type specifies the type of the data source.

    In our case, it must be set to “api“.

  • dataSource.url contains the Data Server’s URL where the client will send requests for data.

    Since the client and the server run on the same machine, we can use the localhost address. The port is set to 9500 because the Data Server uses it by default. You can run the Data Server on another port.

  • dataSource.index identifies the dataset created in the Data Server.

    We’ve named it “next-sql” in the Connecting to MySQL part of this tutorial, so let’s specify it here.

Now, let’s pass the previously created report as a ForwardRefPivot prop:

<ForwardRefPivot
  ref={pivotRef}
  toolbar={true}
  //Setting report
  report={report}
  //Connecting Flexmonster and Recharts
  reportcomplete={() => {
    pivotRef.current?.flexmonster.off("reportcomplete");
    pivotRef.current?.flexmonster.getData({}, drawChart, drawChart);
  }}
  licenseKey="XXXX-XXXX-XXXX-XXXX-XXXX"
/>

Conclusion

Hooray, our Next.js data visualization app is ready and can be started with this command:

npm run build && npm start

You can also get this tutorial project on GitHub. Feel free to use it as a starting point when developing your NEXT app (pun intended)!

The post Creating a Next.js Dashboard for SQL Data Visualization appeared first on Hongkiat.

]]>
71096
20 Powerful VS Code Extensions for Front-End Developers https://www.hongkiat.com/blog/visual-studio-code-extensions/ https://www.hongkiat.com/blog/visual-studio-code-extensions/#comments Tue, 26 Dec 2023 15:01:21 +0000 https://www.hongkiat.com/blog/?p=26494 Visual Studio Code, Microsoft’s powerful code editor, has quickly become a favorite in the developer community. The editor’s versatility is significantly enhanced by a wide array of extensions available in the Visual Studio Code Marketplace. These extensions are particularly beneficial for web developers, offering tools and features that streamline various aspects of coding and development.…

The post 20 Powerful VS Code Extensions for Front-End Developers appeared first on Hongkiat.

]]>
Visual Studio Code, Microsoft’s powerful code editor, has quickly become a favorite in the developer community. The editor’s versatility is significantly enhanced by a wide array of extensions available in the Visual Studio Code Marketplace. These extensions are particularly beneficial for web developers, offering tools and features that streamline various aspects of coding and development.

In this post, we delve into the world of VS Code extensions, specifically focusing on front-end development. After exploring numerous extensions, I’ve curated a list of those that stand out for their intuitiveness, ease of use, and convenience. While this list is informative, the marketplace is constantly evolving with new and improved extensions, so I encourage you to explore it further and discover the tools that best suit your development needs.

How to Install VS Code Extensions?

Installing an extension is pretty straightforward in Visual Studio Code, as you can do it within the code editor. In the VS Code Marketplace every extension has its own page, and you can find the command you can install the given extension with on top of this page.

The command always begins with the ext install term. To install an extension, just press CTRL+P inside VS Code to start the Quick Open panel, copy-paste this command into it, and finally restart the code editor to make the new extension work.

Useful VS Code Extensions for Developers

HTML Snippets

If you want to frequently write HTML in Visual Studio Code, the HTML Snippets extension can come as a handy tool, as it adds elaborate support for HTML. Although VS Code has basic support for HTML, such as syntax colouring, the HTML Snippets extension knows much more.

HTML Snippets

Probably the most useful feature of this extension is that when you begin to type the name of an HTML tag (without the starting angle bracket), HTML Snippets quickly displays a list of the available options with a short information about each.

HTML Snippets Anchor Tag

When you click on the element you need, HTML Snippets adds the full HTML5 tag with its most common properties. For instance, if you want to add a link (anchor tag) to your document, just type an a into VS Code, choose the right option in the popup box, and HTML Snippets will insert the necessary <a href=""></a> snippet into your editor without any hassle.

The author of this extension also pays attention to remove deprecated elements, so if you want to use an HTML tag that you can’t find in the popup list, it’s worth to check out whether it’s still valid or not.

turbo-console-log

Ever found logging messages a bit tedious? The turbo-console-log extension is here to help. It makes creating log messages a breeze. Just choose the variable you want to check and hit Control + Alt + L.

Turbo Console Log Demo

Voila! A detailed log message appears right after. It’s not just about adding messages; you can quickly comment, uncomment, or delete all logs in your document, making your coding smoother and more productive.

Prettier

Meet Prettier, the code formatter that cares about consistency. It’s like having a strict editor for your code, ensuring everything looks uniform. As you save, Prettier takes over, parsing and reformatting your code to follow set rules.

It considers line length, wraps code neatly, and lets you choose which languages to format. Say goodbye to style inconsistencies in your code!

HTML CSS Class Completion

HTML CSS Class Completion can be a helpful extension if you need to use many CSS classes in your project. It frequently happens to us developers, that we are not completely sure in the exact name of a class, but it just sits at the back of our mind as passive knowledge.

This smart extension gives a solution for this problem, as it fetches the names of all CSS classes in the current workspace, and displays a list about them.

HTML CSS Class Completion

Let’s say, you want to create a site using Zurb Foundation, and you want to use the small grid. You don’t remember how the classes are exactly named, but you know they have semantic names.

With HTML CSS Class Completion you only need to start to type the word small, and the available options appear on your screen at once, so you can easily select the one you need.

HTML CSS Class Completion Example
Import Cost

Concerned about your code’s performance? The Import Cost extension is like a vigilant assistant, keeping an eye on performance as you code. It might not analyze your entire bundle, but it alerts you to heavy imports before they bog down your users.

Import Cost Extension Display

As you bring in a third-party library, Import Cost shows its size right next to your code, helping you maintain a lean, efficient project.

VSCode Edge DevTool

The Microsoft Edge Developer Tools for Visual Studio Code seamlessly integrates the robust capabilities of the browser’s DevTools into the VSCode environment, particularly for Microsoft Edge users. This extension eliminates the need to switch between your code editor and the browser while working on a project.

VSCode Edge DevTools Interface

With features like viewing and interacting with runtime HTML structure and modifying styling and layout, it offers an efficient way to handle diagnostics and debugging within VSCode.

GitLens

GitLens offers invaluable insights into your codebase. It helps you understand who made changes to the code, why, and when. The extension is great at visualizing code authorship, showing you the contributions of different team members at a glance.

GitLens User Interface

GitLens makes navigating and exploring Git repositories effortless, with features like comparison commands that provide a detailed view of changes and their impacts on your project.

View in Browser

View in Browser is a simple but powerful extension for Visual Studio Code. It can facilitate front-end development by allowing you to have a quick look at the result of your work in the browser while coding. You can open your HTML file in your default browser directly from VS Code by pressing the CTRL + F1 keyboard shortcut.

Note that View in Browser only supports HTML, so if you want to see your site you need to have the HTML file open. You can’t directly access the browser from a CSS or JavaScript file.

View in Browser
VS Code Chrome debugger

The VS Code Chrome Debugger is a game-changer for developers who frequently debug client-side JavaScript. It allows you to directly debug JavaScript running in Chrome from your Visual Studio Code environment.

VS Code Chrome Debugger in Action

By using the Chrome Debugger Protocol, this extension seamlessly connects Chrome to VS Code, enabling features like setting breakpoints, watching variables, and viewing the call stack without ever leaving your editor.

File Utils

File Utils is a powerful tool that makes handling files in your editor a breeze. It lets you create, duplicate, move, rename, and delete files and folders with simple commands.

File Utils Extension Usage

This extension is all about saving you time and effort in managing your project’s file structure. Plus, it features brace extension, which helps in quickly setting up complex document structures by automatically generating strings.

Debugger for Chrome

Debugger for Chrome was built by Microsoft itself, and it’s currently the 4th most frequently downloaded Visual Studio Code extension.

Debugger for Chrome makes it possible to debug JavaScript in Google Chrome without leaving the code editor. This means that you don’t need to work with the transpiled JavaScript the browser sees, but you can perform the debugging right from the original source files. See this demo to see how it works.

Debugger for Chrome

The extension has every feature a decent debugger needs, such as breakpoint setting, variable watching, stepping, a handy debug console, and many others (see the feature list of the first release).

To use this extension you need to start Chrome with remote debugging enabled, and set up a proper launch.json file. This latter may take for a while, but you can find detailed instructions on GitHub on how to properly do it.

File Ops

File Ops enhances your project organization by allowing you to add tags and aliases to files. This feature simplifies finding and switching between important files in your project.

File Ops Tagging Feature

The extension shines in keeping track of numerous files, offering a convenient way to list all tags. Additionally, it makes it easy to view and switch between related files in the same directory, like .css and .js files. An informative video is also available to help you understand all its functionalities.

Gremlins tracker

Gremlins Tracker is your go-to tool for spotting hidden or tricky characters in your code. It highlights characters like zero-width spaces and unusual quotation marks, which might cause unexpected errors.

Gremlins Tracker in Use

This tool uses a color-coded system to indicate the level of harm these characters pose. It also marks lines with a Gremlins icon and provides detailed hints about these characters when you hover over them, helping you maintain clean and error-free code.

JSHint

Visual Studio Code’s JSHint extension integrates the popular JSHint JavaScript linter right into the code editor, so you can be informed about your errors as soon as you commit them. By default, the JSHint extension uses the default options of the linter that you can customize with the help of a configuration file.

JSHint

The usage of this extension is quite straightforward, as JSHint marks the errors with red, and the notifications with a green underline. If you want more information on the issues, just hover over the underlined parts, and JSHint will float a label with the description of the problem at once.

JSHint Example
Polacode

Polacode transforms the way you share your code visually. It’s like a Polaroid camera for your code, simplifying the process of capturing aesthetically pleasing screenshots within Visual Studio Code (VS Code).

Polacode Screenshot Tool

You can easily edit these screenshots right in the editor, adjust the size of the code container, and control the image’s appearance with handy commands. Polacode is ideal for presenting your code in the most visually appealing manner.

jQuery Code Snippets

jQuery Code Snippets can greatly speed up front-end development in Visual Studio Code, as it lets you quickly write jQuery without basic syntax errors. jQuery Code Snippets currently has around 130 available snippets you can invoke by typing the right trigger.

jQuery Snippets

All jQuery snippets but one start with the jq prefix. The one exception is the func trigger that inserts an anonymous function into the editor.

This handy extension is a convenient help when you are not completely sure about the proper syntax, and want to spare the time to check the documentation. It also makes it easy to quickly scroll through the available options.

JSHint Example
Bower

The Bower VS Code extension can make your web development workflow more intuitive by integrating the Bower package manager into Visual Studio Code.

If you put this extension into use you don’t have to switch back and forth between the terminal and the editor, but you can easily perform your package management tasks right inside Visual Studio Code.

Bower

The Bower extension leads you through the creation of your project’s bower.json file, and you can also install, uninstall, search, update packages, manage cache, and perform many other tasks with it (see full feature list).

You can access Bower-related commands by starting the Command Palette by pressing F1, typing “Bower” into the input bar, clicking on the “Bower” option in the dropdown list that appears, and picking the appropriate Bower command.

Bower Example
Better Comments

Better Comments breathes new life into your code annotations, making them more user-friendly and visually distinguishable. This tool allows for easy categorization of comments into types like alerts, queries, todos, and highlights, helping you quickly identify the nature and importance of each comment.

Better Comments Extension

Whether it’s an alert about a deprecated method or a reminder about an incomplete task, this extension ensures clarity. It also offers styling options for commented-out code, aiding in maintaining clean and efficient code.

Git History

Git History makes it possible to follow the changes of a Git project inside Visual Studio Code. This extension is especially useful when you want to contribute to a bigger Github project, and need a way to quickly check out the modifications other developers made.

With the Git History extension installed you can view the history of an entire file, or a particular line inside of it. You can also compare previous versions of the same file.

Git History

You can access the commands related to Git History if you type the word “Git” into the Command Palette (F1), choose “Git” inside the dropdown list, and finally select the command you need. Note that you need to open the file of which you want to see the history before you can perform any actions on it.

Git History Example

The post 20 Powerful VS Code Extensions for Front-End Developers appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/visual-studio-code-extensions/feed/ 23 26494
15 Podcast Channels for Web Developers https://www.hongkiat.com/blog/podcasts-web-developers/ Fri, 01 Dec 2023 15:01:54 +0000 https://www.hongkiat.com/blog/?p=64765 Listening to podcasts is an excellent way to keep up with web development trends. They offer a flexible learning format – you can tune in without being tied to your desk. We’ve compiled a list of top podcasts for developers, spanning topics like software development, frontend development, JavaScript, CSS, and more. These podcasts cater to…

The post 15 Podcast Channels for Web Developers appeared first on Hongkiat.

]]>
Listening to podcasts is an excellent way to keep up with web development trends. They offer a flexible learning format – you can tune in without being tied to your desk.

podcasts for developers

We’ve compiled a list of top podcasts for developers, spanning topics like software development, frontend development, JavaScript, CSS, and more. These podcasts cater to all levels, from beginners to experienced developers. So, put on your headphones and dive into learning!

1. Inside Marketing Design

Podcast cover of Inside Marketing Design

Inside Marketing Design explores the lesser-known realm of design in the tech industry, focusing on marketing and brand design. It’s a fresh perspective compared to the more commonly discussed product and UI/UX design.

Each episode offers insights from marketing design specialists at leading tech firms like Zendesk, Stripe, Zapier, Shopify, and others. They discuss their approaches to creating landing pages, brand illustrations, and promotional campaigns.

This podcast gives listeners a glimpse into the workings of design teams, their project management strategies, and the challenges they encounter.

Where to Listen:

YouTube Spotify Apple Podcasts

2. Boagworld

Podcast cover of Boagworld

Paul Boag, a prominent figure in web design, is known for his bestselling books and as the founder of Headscape, a UK-based design agency. His podcast, Boagworld, has been broadcasting since 2011 and features over 100 episodes on website building and digital strategy. It’s one of the industry’s longest-running podcasts. Boagworld is available through RSS or iTunes.

Where to Listen:

Spotify

3. ShopTalk Show

Podcast cover of ShopTalk Show

ShopTalk Show, a leading podcast in web design, is hosted by Chris Coyier of CSS-Tricks and Dave of Paravel. The show brings together experts in web design and programming to share their knowledge and experiences. With over 100 episodes and new ones released weekly, it’s a treasure trove of insights for enthusiasts and professionals alike.

Where to Listen:

YouTube

4. Beyond Coding

Podcast cover of Beyond Coding

Beyond Coding is a weekly podcast that covers a wide range of topics in software development and engineering. The show, however, delves deeper than just coding. It also addresses themes like leadership, communication, self-improvement, and happiness. Hosted by Patrick Akil, the podcast features casual conversations with guests about their experiences and viewpoints. New episodes are released every Wednesday.

Where to Listen:

YouTube Apple Podcasts

5. Syntax FM

Podcast cover of Syntax FM

Syntax FM is hosted by experienced web developers Scott Tolinski and Wes Bos. This podcast covers a broad spectrum of topics, including front-end and back-end development, and design. Scott and Wes offer practical advice, tips, and insights for improving skills and keeping up with industry trends and best practices. It’s a popular choice in the web community for its thorough discussions and expert commentary.

Where to Listen:

Spotify Apple Podcasts

6. CodePen Radio

Podcast cover of CodePen Radio

CodePen Radio, from codepen.io, focuses on web development, design, and the creative aspects of coding. Hosted by Chris Coyier and Marie Mosley, the show dives into various topics relevant to front-end developers and designers, such as design patterns, CSS, and JavaScript. It’s an invaluable resource for staying abreast of the latest trends and best practices in the field.

Where to Listen:

Apple Podcasts

7. CodeNewbie Podcast

Podcast cover of CodeNewbie Podcast

CodeNewbie Podcast is tailored for those new to coding or considering a technology career. Hosted by Saron Yitbarek, it features conversations with a diverse range of developers and tech professionals. The podcast covers topics from the basics of coding and technology to advice on getting started with programming, staying motivated, and the highs and lows of learning to code. It is part of the CodeNewbie community, committed to supporting newcomers in the tech industry.

Where to Listen:

Spotify Apple Podcasts

8. Frontend Happy Hour

Podcast cover of Frontend Happy Hour

Frontend Happy Hour is hosted by seasoned web developers from notable tech companies like Netflix, Twitch, Atlassian, Evernote, and LinkedIn. The podcast covers a variety of topics in frontend development, including the latest trends, best practices, and new tools. It’s ideal for frontend developers looking to stay current with their field, seeking inspiration, and aiming to grow and succeed in their careers.

Where to Listen:

Spotify Apple Podcasts

9. Web Rush

Podcast cover of Web Rush

Web Rush is a weekly podcast for web developers hosted by John Papa, Ward Bell, Craig Shoemaker, and Dan Wahlin. It delves into various aspects of web development, from JavaScript to broader web development topics. The show focuses on offering practical insights and discussions about the everyday challenges faced by developers, featuring expert guests who share their experiences and knowledge. It’s a valuable resource for developers at all skill levels, from beginners to seasoned professionals.

Where to Listen:

Apple Podcasts

10. JavaScript Jabber

Podcast cover of JavaScript Jabber

JavaScript Jabber is a weekly podcast that tackles a wide array of topics related to JavaScript, web development, and the web platform. The podcast aims to offer insights, tips, and advice to help developers enhance their skills and stay informed on the latest trends. It’s an excellent resource for anyone interested in web development, particularly JavaScript, and caters to developers of all expertise levels, from novices to experts.

Where to Listen:

Apple Podcasts

11. Views on Vue

Podcast cover of Views on Vue

Views on Vue is a podcast focused on Vue.js, featuring dialogues with developers and experts proficient in Vue.js. It discusses a range of topics related to Vue.js, including best practices, emerging trends, and real-world projects using Vue.js. Ideal for developers keen on learning more about Vue.js or already implementing it in their projects.

Where to Listen:

Spotify Apple Podcasts

12. DeveloperTea

Podcast cover of DeveloperTea

DeveloperTea, hosted by Jonathan Cutrell, is a podcast crafted for web and software developers. The episodes, lasting around 10-15 minutes, are designed to fit into a developer’s daily routine, offering insights on a mix of technical and non-technical topics relevant to the field. It’s an excellent resource for developers at all levels, including those new to web and software development.

Where to Listen:

Apple Podcasts

13. Podrocket

Podcast cover of Podrocket

Podrocket, a weekly podcast hosted by LogRocket co-founder Ben Edelstein and the LogRocket engineering team, focuses on front-end web development. The show delves deep into libraries, frameworks, and current issues in the web development industry, offering listeners in-depth knowledge and insights. It’s a valuable resource for anyone involved in or interested in front-end web development.

Where to Listen:

Spotify Apple Podcasts

14. The Changelog

Podcast cover of The Changelog

The Changelog is a weekly podcast that dives into the world of open-source, software development, and technology. Hosted by Adam Stacoviak and Jerod Santo, it features insightful interviews with developers, engineers, and other industry experts. The show covers a wide array of topics, including new technologies, practical tips, and the future of open-source software. It’s a must-listen for anyone keen on staying current with open-source developments.

Where to Listen:

Spotify Apple Podcasts

15. The CSS Podcast

Podcast cover of The CSS Podcast

The CSS Podcast is all about CSS, hosted by Una Kravets and Adam Argyle. They discuss a broad spectrum of CSS-related topics, from the latest features to design and development tips and tricks. The show often features expert guests, offering insights into the current and future trends in CSS. For those looking to deepen their understanding of CSS and stay up-to-date with the field’s latest advancements, this podcast is an invaluable resource.

Where to Listen:

YouTube Spotify Apple Podcasts

The post 15 Podcast Channels for Web Developers appeared first on Hongkiat.

]]>
64765
How to Remove Unnecessary jQuery Modules https://www.hongkiat.com/blog/jquery-remove-modules/ https://www.hongkiat.com/blog/jquery-remove-modules/#comments Fri, 27 Oct 2023 07:01:07 +0000 https://www.hongkiat.com/blog/?p=17540 jQuery is undoubtedly the most popular JavaScript library. Almost every website on the planet uses it. Due to its widespread use, jQuery includes functionalities to cover every possible scenario. However, when working on a simple website, we might only use a few of these functions. It would be more efficient to run only the necessary…

The post How to Remove Unnecessary jQuery Modules appeared first on Hongkiat.

]]>
jQuery is undoubtedly the most popular JavaScript library. Almost every website on the planet uses it. Due to its widespread use, jQuery includes functionalities to cover every possible scenario.

However, when working on a simple website, we might only use a few of these functions. It would be more efficient to run only the necessary functions and exclude the unused ones. We can exclude certain jQuery modules that aren’t needed for our project. Let’s explore how to do this.

Getting Started

First, we need to install essential tools for the task. These tools include Git, Grunt, and Node.js. If you’re using macOS, the most straightforward method to install these tools is through the macOS package manager, Homebrew.

Installing Homebrew

Open your Terminal and execute the following command to install Homebrew. With Homebrew, installing the other tools becomes simpler.

ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
Installing Git

Once Homebrew is installed, execute the command below to install Git.

brew install git
Installing Node.js

Use the following command to install Node.js:

brew install node
Installing Grunt

Finally, install Grunt by running the command below:

npm install -g grunt-cli

For Windows users, there’s a comparable package manager named Chocolatey. You can use it to install the aforementioned packages in a similar manner.

Building jQuery

At present, jQuery allows the exclusion of the following modules:

Module Command Description
Ajax -ajax This refers to the jQuery AJAX API, which includes jQuery.ajax(), jQuery.get(), and the .load() function.
CSS -css This pertains to functions from the jQuery CSS Category, including .addClass(), .css(), and .hasClass().
Deprecated -deprecated This refers to the deprecated modules or functions.
Event Alias -event-alias This pertains to event functions such as .click(), .focus(), and .hover().
Dimensions -dimensions This relates to the functions for setting CSS dimensions, including .height(), .innerHeight(), and .innerWidth().
Effects -effects This refers to functions that apply animation effects, such as .slideToggle(), .animate(), and .fadeIn().
Offset -offset This pertains to functions that retrieve coordinates and position, including .offset() and .position().

Before customizing jQuery, we need to clone it from the GitHub repository. Execute the following command in the Terminal:

git clone git://github.com/jquery/jquery.git

A new folder named jquery will be created in your user directory. Navigate to this directory with the command:

cd jquery

Next, install the Node dependency modules required for our project:

npm install

Then, build jQuery by simply executing the Grunt command:

grunt

If successful, the following report will be displayed:

grunt report

As indicated in the report, our jQuery is stored in the dist/ folder. At this stage, our jQuery includes all functionalities, resulting in a size of 265kb. The minified version is 83kb.

jquery report

Module Removal

If you wish to remove the Effects module from jQuery, execute the following command:

grunt custom:-effects

Upon checking the file size again, you’ll notice it has reduced to 246kb.

jQuery custom build

To exclude multiple modules, list each module separated by a comma, like so:

grunt custom:-effects,-ajax,-deprecated

Excluding multiple modules will further reduce the jQuery file size. In this instance, it’s been reduced to just 207kb.

Concluding Thoughts

jQuery facilitates easy DOM manipulation, but its size, exceeding 200kb, might impact your website’s performance. By removing unnecessary jQuery modules, your script will undoubtedly run more efficiently and faster. We hope this tip proves beneficial for your upcoming projects.

The post How to Remove Unnecessary jQuery Modules appeared first on Hongkiat.

]]>
https://www.hongkiat.com/blog/jquery-remove-modules/feed/ 23 17540
30 Basic Git Commands You Should Know https://www.hongkiat.com/blog/basic-git-commands/ Mon, 12 Jun 2023 13:01:00 +0000 https://www.hongkiat.com/blog/?p=67314 The article delves into the Git commands developers should know, including initializing a repository, making commits, and much more.

The post 30 Basic Git Commands You Should Know appeared first on Hongkiat.

]]>
When it comes to software development, version control is essential. It allows you to track your code changes, revert to previous stages, and collaborate with your team on a project. One of the most popular version control systems is Git. Whether you’re a beginner just starting out or an experienced developer looking to streamline your workflow, understanding Git commands is a skill that will undoubtedly pay off.

basic git commands

In this post, we will delve into 30 basic Git commands that every developer should know. These commands will help you initialize a repository, make commits, create and switch branches, and much more. By mastering these commands, you’ll be well on your way to becoming a more efficient and effective developer.

10 Useful Github Features to Know

10 Useful Github Features to Know

Github is now the place where programmers and designers work together. They collaborate, contribute, and fix bugs. It... Read more

1. git init:

This command is used to initialize a new Git repository. It creates a new .git subdirectory in your current working directory. This will also create a new branch named master.

Example:

git init

This will initialize a Git repository in your current directory.

2. git clone:

This command is used to clone a repository. It creates a copy of a remote repository on your local machine.

Example:

git clone https://github.com/username/repository.git

This will clone the repository at the given URL to your local machine.

3. git add:

This command adds a file to the staging area in preparation for a commit.

Example:

git add filename

This will add the file named “filename” to the staging area.

4. git commit:

This command is used to save your changes to the local repository. It takes a snapshot of the changes you’ve staged using git add.

Example:

git commit -m "Commit message"

This will commit your changes with a message describing what you changed.

5. git status:

This command shows the status of changes as untracked, modified, or staged.

Example:

git status

This will display the status of your working directory.

6. git pull:

This command fetches changes from a remote repository and merges them into your current branch.

Example:

git pull origin master 

This will pull changes from the master branch of the origin remote repository.

7. git push:

This command sends your committed changes to a remote repository.

Example:

git push origin master 

This will push your committed changes to the master branch of the origin remote repository.

8. git branch:

This command lists all of the branches in your repository.

Example:

git branch

This will list all of the branches in your repository.

9. git checkout:

This command is used to switch between branches in a Git repository.

Example:

git checkout branch-name

This will switch to the branch named “branch-name”.

10. git merge:

This command merges the changes from one branch into another.

Example:

git merge branch-name
11. git diff:

This command shows the file differences which are not yet staged.

Example:

git diff 

This will show unstaged differences since the last commit.

12. git reset:

This command unstages the file, but it preserves the file contents.

Example:

git reset filename 

This will unstage the file named “filename“.

13. git rm:

This command deletes the file from your working directory and stages the deletion.

Example:

git rm filename

This will delete the file named “filename” and stage the deletion.

14. git log:

This command shows a listing of commits on a branch including the corresponding details.

Example:

git log 

This will display an ordered list of the recent commits.

15. git show:

This command shows the metadata and content changes of the specified commit.

Example:

git show

This will display the metadata and content changes of the latest commit.

16. git tag:

This command is used to give tags to the specified commit.

Example:

git tag v1.0

This will tag the latest commit with “v1.0”.

17. git fetch:

This command fetches all the objects from the remote repository that are not present in the local one.

Example:

git fetch origin

This will fetch all objects from the origin remote that don’t exist in your current repository.

18. git rebase:

This command is used to apply the changes made on the current branch ahead of another branch.

Example:

git rebase master

This will apply any changes made on the current branch ahead of the master branch.

19. git revert:

This command creates a new commit that undoes the changes made in a previous commit.

Example:

git revert HEAD

This will create a new commit that undoes the changes made in the last commit.

20. git stash:

This command temporarily saves changes that you don’t want to commit immediately. You can apply the changes later.

Example:

git stash 

This will temporarily save all modified tracked files.

21. git stash pop:

This command restores the most recently stashed changes.

Example:

git stash pop

This will apply the most recently stashed changes and remove them from the stash list.

22. git stash list:

This command lists all stashed changesets.

Example:

git stash list 

This will display all stashed changesets.

23. git stash drop:

This command discards the most recently stashed changeset.

Example:

git stash drop

This will discard the most recently stashed changeset.

24. git cherry-pick:

This command applies the changes introduced by some existing commits.

Example:

git cherry-pick commitID 

This will apply the changes introduced by the commit with the given ID.

25. git bisect:

This command uses a binary search algorithm to find which commit in your project’s history introduced a bug.

Example:

git bisect start
git bisect bad
git bisect good commitID

This will start the bisecting process, mark the current commit as bad, and mark the commit with the given ID as good.

26 git blame:

This command shows what revision and author last modified each line of a file.

Example:

git blame filename 

This will show what revision and author last modified each line of “filename”.

27. git clean:

This command removes untracked files from your working directory.

Example:

git clean -n 

This will show what will be removed without actually doing it. Replace -n with -f to actually remove the files.

28 git reflog:

This command shows a list of all references to commits in the local repository.

Example:

git reflog 

This will display all references to commits in your local repository.

29. git grep:

This command lets you search through your repository.

Example:

git grep "hello" 

This will search the repository for any occurrences of “hello”.

30. gitk:

This command launches the Git repository browser.

Example:

gitk

This will launch the Git repository browser.

Conclusion

In conclusion, Git is a powerful tool that can greatly enhance your productivity and efficiency as a developer. The 30 basic Git commands we’ve discussed in this post are just the tip of the iceberg. There are many more commands and options available in Git, and we encourage you to explore them further.

Remember, practice makes perfect. The more you use these commands, the more comfortable you’ll become with them. So, don’t be afraid to dive in and start using Git in your projects. It may seem daunting at first, but with time and practice, you’ll find that it’s an invaluable tool in your development toolkit.

The post 30 Basic Git Commands You Should Know appeared first on Hongkiat.

]]>
67314