DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Masui Masanori
Masui Masanori

Posted on

[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)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.