Set up Master CSS in Blazor
Guide to setting up Master CSS in your Blazor project.
Create a project
If you don't have a Blazor project, create one first. It's recommended to refer to Build your first Blazor app
dotnet new blazorserver -o project --no-https -f net6.0cd projectCreate a New Folder
Add a new folder named npm_packages to root directory.
mkdir npm_packagescd npm_packagesSet up NPM
Set up NPM and install the required webpack dependencies.
npm init -ynpm install webpack webpack-cli --save-devCreate a configuration file
Run the command to create a master.css.js file.
npm create @master/css@rcInstall Master CSS
Install Master CSS into your project via package managers.
npm i @master/css-runtime@rcSet up CSS runtime engine
Create a new file npm_packages/src/index.js and import the master.css.js to enable the runtime engine.
…import { initCSSRuntime } from '@master/css-runtime'; import config from 'master.css'; initCSSRuntime(config) Add an NPM build script
Add an NPM build script on script section of the package.json file.
{ ... scripts: { ... "build": "webpack ./src/index.js --output-path ../wwwroot/js --output-filename index.bundle.js --mode=development" }}Add prebuild step
Add a prebuild step that will run npm install and npm run build whenever compile or build the application to the project.csproj file.
<Project> ... <Target Name="PreBuild" BeforeTargets="PreBuildEvent"> <Exec Command="npm install" WorkingDirectory="npm_packages" /> <Exec Command="npm run build" WorkingDirectory="npm_packages" /> </Target> ...</Project>Import bundles JavaScript file
Webpack will create a index.bundle.js file in wwwroot/js, and import the file to entry file Pages/_Layout.cshtml
<html> ... <body> ... <script src="_framework/blazor.server.js"></script> <script src="js/index.bundle.js"></script> </body></html>Build and start the app
Navigate to project directory, and build and start your app with dotnet watch
cd projectdotnet watchHello world!
Now style your first element using Master CSS syntax!
@page "/"<PageTitle>Index</PageTitle><h1 class="italic m:12x fg:strong font:40 font:heavy"> Hello World </h1> Welcome to your new app.<SurveyPrompt Title="How is Blazor working for you?" />Open your browser to watch the changes.