This proof-of-concept application demonstrates the integration of ASP.NET Core with Vite, showcasing an approach to bundling in a hybrid multi-page application using .NET.
The primary goal of this sample code is to demonstrate:
- Using Vite/Rollup bundling in an ASP.NET Core hybrid multi-page application
- Associating TypeScript files with Razor views, similar to the built-in CSS isolation feature
- ASP.NET Core backend
- Vite for fast and efficient bundling
- TypeScript support
- Razor Pages integration
- cshtml.ts files as entry points for Razor views
The core feature of this demo is the use of cshtml.ts
files as entry points for Razor views. This approach offers several advantages:
- Colocation: Define client-side code in the same location as your Razor view
- Tree-shaking: Benefit from Vite's tree-shaking capabilities for your client-side code
- Code splitting: Automatically chunk your client-side code for optimal loading
- Improved navigation: Easier to locate and manage associated client-side code for each view
- Create a
[ViewName].cshtml.ts
file alongside your Razor view - Write your TypeScript code in this file
- Vite/globby gathers these files and turns them into entry points for each page
- The build process bundles these files, making them available to your Razor views
Example:
// Index.cshtml.ts
console.log('This script is associated with the Index view');
- Clone the repository
- Navigate to the project directory
- Run
dotnet restore
to restore .NET dependencies - Run
npm install
orpnpm install
to install frontend dependencies - Run
npm run dev
to start the Vite development server - Use
dotnet run
to start the application
While hot module replacement (HMR) is possible with Vite.AspNetCore, this sample takes a different approach:
- In development mode, all files are written to disk
- The sample utilizes ASP.NET Core's built-in hot reloading to update on changes
- This approach provides a simpler setup while still offering quick feedback during development
This project uses Vite.AspNetCore to enable reading the Vite manifest for generating links to bundled files in Razor views.
- Add a tag helper <script asp-entry> to automatically associate code with page
- How to handle nested razor, components?
This project is open source and available under the MIT License.