Build the angular project and run on server namecheap, hostinger etc | Deploy angular
Angular is a popular front-end web development framework that helps developers build scalable and maintainable applications. This article will guide you through the process of building and deploying an Angular project step by step.
Prerequisites
Before you start, ensure that you have the following tools installed on your system:
- Node.js and npm (Node Package Manager)
- Angular CLI (Command Line Interface)
Step 1: Set all paths to root in the components folder
To avoid potential issues with the deployment, make sure all paths are set to root in your components folder. Update the href attribute for any links, and ensure that the assets folder path is correctly set.
Step 2: Build the Angular project
Navigate to your project's root directory in the terminal or command prompt and execute the following command:
ng build --base-href "https://newsite.com"
Replace "https://newsite.com" with the base URL of your website. This command will generate a "dist" folder containing your compiled Angular application.
Step 3: Add an .htaccess file for URL rewriting
Create an .htaccess file in your 'dist' folder and add the following configuration:
RewriteEngine On
# Redirect requests to the index.html file
RewriteRule ^$ index.html [L]
RewriteRule ^index.html$ index.html [L]
# Redirect non-existing files and directories to index.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.html [L]
This configuration ensures that all requests are redirected to the 'index.html' file, allowing Angular's routing to handle URL changes.
Step 4: Upload the project to the server
Finally, upload the contents of the 'dist' folder to your web server. Make sure to configure your server to serve the 'index.html' file as the default document for your site.
Conclusion
Building and deploying an Angular project involves setting the appropriate paths, building the project with the Angular CLI, updating the base URL, adding URL rewriting with an .htaccess file, and uploading the project to your web server. By following these steps, you'll be able to deploy your Angular application successfully.