DEV Community

Masui Masanori
Masui Masanori

Posted on

4 3

[ASP.NET Core] Using Bootstrap with package managers

Intro

This time, I wll try using CSS of Bootstrap in ASP.NET Core projects.
And I want to add Bootstrap packages with package managers(ex. NuGet, NPM, etc.).

CLI project templates

For example, when I create a new project with the MVC template, Bootstrap packages will be included in the project.

dotnet new mvc -n MvcSample
Enter fullscreen mode Exit fullscreen mode

But they won't be managed by package managers.
They will be put into "wwwroot/lib/bootstrap/dist" directly.
Alt Text

So I must find another way.

NuGet

I can install Bootstrap with NuGet package manager.

But in my ASP.NET Core project, I couldn't get any Bootstrap package files after installing.
And I couldn't find how to use it.

So I gave up using NuGet to use Bootstrap.

NPM + PostCSS

I also can install Bootstrap with NPM.

npm install --save bootstrap
Enter fullscreen mode Exit fullscreen mode

The package files are in "node_modules" directory.
But how can I use them?

By default, ASP.NET Core doesn't publish "node_modules" directory.
And I don't want to do that, too.

So shall I copy the files into "wwwroot" directory manually?
I also don't want to do that.

So I decided to use PostCSS to import the Bootstrap files.

postcss-import

I can import CSS files by "postcss-import".

package.json

{
    "browserslist": [
        "last 2 version"
    ],
    "dependencies": {
        "@microsoft/signalr": "^5.0.4",
        "autoprefixer": "^10.2.5",
        "bootstrap": "^4.6.0",
        "postcss": "^8.2.8",
        "postcss-cli": "^8.3.1",
        "postcss-import": "^14.0.0",
        "ts-loader": "^8.0.17",
        "tsc": "^1.20150623.0",
        "typescript": "^4.2.3",
        "webpack": "^5.24.4",
        "webpack-cli": "^4.5.0"
    },
    "scripts": {
        "css": "npx postcss postcss/*.css -c postcss.config.js -d wwwroot/css -w"
    }
}
Enter fullscreen mode Exit fullscreen mode

postcss.config.js

module.exports = {
    plugins: [
      require("postcss-import")(),
      require("autoprefixer")({
        "grid": true
      }),
    ]
  }
Enter fullscreen mode Exit fullscreen mode

Because I don't add any codes, I just import the Bootstrap CSS file.

main.page.css

@import "../node_modules/bootstrap/dist/css/bootstrap.min.css"
Enter fullscreen mode Exit fullscreen mode

Now I can use Bootstrap CSS files after executing "npm run css" command.

Before

Alt Text

After

Alt Text

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay