如何在 ASP.NET Core 中使用 Bootstrap 4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48481003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Bootstrap 4 in ASP.NET Core
提问by developer
I want to update Bootstrap in ASP.NET Core with NuGet. I used this:
我想使用 NuGet 更新 ASP.NET Core 中的 Bootstrap。我用过这个:
Install-Package bootstrap -Version 4.0.0
It did add the dependencies but how do I add it to my project now? What is the path for local NuGet dependencies?
它确实添加了依赖项,但我现在如何将其添加到我的项目中?本地 NuGet 依赖项的路径是什么?


回答by poke
As others already mentioned, the package manager Bower, that was usually used for dependencies like this in application that do not rely on heavy client-side scripting, is on the way outand actively recommending to move to other solutions:
正如其他人已经提到的,包管理器Bower,通常用于不依赖大量客户端脚本的应用程序中的此类依赖项,正在退出并积极建议转向其他解决方案:
..psst! While Bower is maintained, we recommend yarnand webpackfor new front-end projects!
So although you can still use it right now, Bootstrap has also announced to drop support for it. As a result, the built-in ASP.NET Core templates are slowly being edited to move away from it too.
所以虽然你现在仍然可以使用它,但 Bootstrap 也宣布放弃对它的支持。因此,内置的 ASP.NET Core 模板也在慢慢被编辑以远离它。
Unfortunately, there is no clear path forward. This is mostly due to the fact that web applications are continuously moving further into the client-side, requiring complex client-side build systems and many dependencies. So if you are building something like that, you might already know how to solve this then, and you can expand your existing build process to simply also include Bootstrap and jQuery there.
不幸的是,没有明确的前进道路。这主要是因为 Web 应用程序不断向客户端移动,需要复杂的客户端构建系统和许多依赖项。因此,如果您正在构建类似的东西,那么您可能已经知道如何解决这个问题,并且您可以扩展现有的构建过程,以便在其中也包含 Bootstrap 和 jQuery。
But there are still many web applications out there that are not that heavy on the client-side, where the application still runs mainly on the server and the server serves static views as a result. Bower previously filled this by making it easy to just publish client-side dependencies without that much of a process.
但是仍然有许多 Web 应用程序在客户端没有那么重,应用程序仍然主要在服务器上运行,因此服务器提供静态视图。Bower 之前通过使发布客户端依赖项变得容易而无需那么多流程来填补这一点。
In the .NET world we also have NuGet and with previous ASP.NET versions, we could use NuGet as well to add dependencies to some client-side dependencies since NuGet would just place the content into our project correctly. Unfortunately, with the new .csprojformat and the new NuGet, installed packages are located outside of our project, so we cannot simply reference those.
在 .NET 世界中,我们也有 NuGet,在以前的 ASP.NET 版本中,我们也可以使用 NuGet 向某些客户端依赖项添加依赖项,因为 NuGet 只会将内容正确地放入我们的项目中。不幸的是,使用新.csproj格式和新 NuGet,已安装的包位于我们的项目之外,因此我们不能简单地引用它们。
This leaves us with a few options how to add our dependencies:
这给我们留下了一些如何添加依赖项的选项:
One-time installation
一次性安装
This is what the ASP.NET Core templates, that are not single-page applications, are currently doing. When you use those to create a new application, the wwwrootfolder simply contains a folder libthat contains the dependencies:
这就是 ASP.NET Core 模板(不是单页应用程序)当前正在做的事情。当您使用它们创建新应用程序时,该wwwroot文件夹仅包含一个lib包含依赖项的文件夹:


If you look closely at the files currently, you can see that they were originally placed there with Bower to create the template, but that is likely to change soon. The basic idea is that the files are copied onceto the wwwrootfolder so you can depend on them.
如果您仔细查看当前的文件,您会发现它们最初与 Bower 一起放置在那里以创建模板,但这可能很快就会改变。基本思想是将文件一次复制到wwwroot文件夹中,以便您可以依赖它们。
To do this, we can simply follow Bootstrap's introduction and download the compiled filesdirectly. As mentioned on the download site, this does not include jQuery, so we need to download that separately too; it does containPopper.jsthough if we choose to use the bootstrap.bundlefile later—which we will do. For jQuery, we can simply get a single “compressed, production” file from the download site(right-click the link and select "Save link as..." from the menu).
为此,我们只需按照Bootstrap的介绍,直接下载编译好的文件即可。如下载站点所述,这不包括jQuery,因此我们也需要单独下载;它确实包含Popper.js,但如果我们bootstrap.bundle稍后选择使用该文件 - 我们将这样做。对于 jQuery,我们可以简单地从下载站点获取一个“压缩的生产”文件(右键单击链接并从菜单中选择“将链接另存为...”)。
This leaves us with a few files which will simply extract and copy into the wwwrootfolder. We can also make a libfolder to make it clearer that these are external dependencies:
这给我们留下了一些文件,它们将简单地提取并复制到wwwroot文件夹中。我们还可以创建一个lib文件夹来更清楚地说明这些是外部依赖项:


That's all we need, so now we just need to adjust our _Layout.cshtmlfile to include those dependencies. For that, we add the following block to the <head>:
这就是我们所需要的,所以现在我们只需要调整我们的_Layout.cshtml文件以包含这些依赖项。为此,我们将以下块添加到<head>:
<environment include="Development">
<link rel="stylesheet" href="~/lib/css/bootstrap.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="~/lib/css/bootstrap.min.css" />
</environment>
And the following block at the very end of the <body>:
以及 最末尾的以下块<body>:
<environment include="Development">
<script src="~/lib/js/jquery-3.3.1.js"></script>
<script src="~/lib/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/js/jquery-3.3.1.min.js"></script>
<script src="~/lib/js/bootstrap.bundle.min.js"></script>
</environment>
You can also just include the minified versions and skip the <environment>tag helpers here to make it a bit simpler. But that's all you need to do to keep you starting.
您也可以只包含缩小版本并跳过<environment>此处的标签助手以使其更简单。但这就是你需要做的一切,让你开始。
Dependencies from NPM
来自 NPM 的依赖
The more modern way, also if you want to keep your dependencies updated, would be to get the dependencies from the NPM package repository. You can use either NPM or Yarn for this; in my example, I'll use NPM.
更现代的方法是从 NPM 包存储库中获取依赖项,如果您想保持更新的依赖项也是如此。为此,您可以使用 NPM 或 Yarn;在我的示例中,我将使用 NPM。
To start off, we need to create a package.jsonfile for our project, so we can specify our dependencies. To do this, we simply do that from the “Add New Item” dialog:
首先,我们需要package.json为我们的项目创建一个文件,以便我们可以指定我们的依赖项。为此,我们只需从“添加新项目”对话框中执行此操作:


Once we have that, we need to edit it to include our dependencies. It should something look like this:
一旦我们有了它,我们需要编辑它以包含我们的依赖项。它应该是这样的:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.0.0",
"jquery": "3.3.1",
"popper.js": "1.12.9"
}
}
By saving, Visual Studio will already run NPM to install the dependencies for us. They will be installed into the node_modulesfolder. So what is left to do is to get the files from there into our wwwrootfolder. There are a few options to do that:
通过保存,Visual Studio 已经运行 NPM 来为我们安装依赖项。它们将被安装到node_modules文件夹中。所以剩下要做的就是将文件从那里获取到我们的wwwroot文件夹中。有几个选项可以做到这一点:
bundleconfig.jsonfor bundling and minification
bundleconfig.json用于捆绑和缩小
We can use one of the various ways to consume a bundleconfig.jsonfor bundling and minification, as explained in the documentation. A very easy way is to simply use the BuildBundlerMinifier NuGet packagewhich automatically sets up a build task for this.
我们可以使用多种方法之一来使用 abundleconfig.json进行捆绑和缩小,如文档中所述。一个非常简单的方法是简单地使用BuildBundlerMinifier NuGet 包,它会自动为此设置一个构建任务。
After installing that package, we need to create a bundleconfig.jsonat the root of the project with the following contents:
安装该包后,我们需要bundleconfig.json在项目的根目录创建一个包含以下内容的文件:
[
{
"outputFileName": "wwwroot/vendor.min.css",
"inputFiles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"minify": { "enabled": false }
},
{
"outputFileName": "wwwroot/vendor.min.js",
"inputFiles": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"minify": { "enabled": false }
}
]
This basically configures which files to combine into what. And when we build, we can see that the vendor.min.cssand vendor.js.cssare created correctly. So all we need to do is to adjust our _Layouts.htmlagain to include those files:
这基本上配置了哪些文件要组合成什么。当我们构建时,我们可以看到vendor.min.css和vendor.js.css被正确创建。所以我们需要做的就是_Layouts.html再次调整我们的文件以包含这些文件:
<!-- inside <head> -->
<link rel="stylesheet" href="~/vendor.min.css" />
<!-- at the end of <body> -->
<script src="~/vendor.min.js"></script>
Using a task manager like Gulp
使用像 Gulp 这样的任务管理器
If we want to move a bit more into client-side development, we can also start to use tools that we would use there. For example Webpackwhich is a very commonly used build tool for really everything. But we can also start with a simpler task manager like Gulpand do the few necessary steps ourselves.
如果我们想更多地进入客户端开发,我们也可以开始使用我们将在那里使用的工具。例如Webpack,它是一个非常常用的构建工具,用于真正的一切。但是我们也可以从一个更简单的任务管理器开始,比如Gulp,然后自己做一些必要的步骤。
For that, we add a gulpfile.jsinto our project root, with the following contents:
为此,我们将一个添加gulpfile.js到我们的项目根目录中,其内容如下:
const gulp = require('gulp');
const concat = require('gulp-concat');
const vendorStyles = [
"node_modules/bootstrap/dist/css/bootstrap.min.css"
];
const vendorScripts = [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
];
gulp.task('build-vendor-css', () => {
return gulp.src(vendorStyles)
.pipe(concat('vendor.min.css'))
.pipe(gulp.dest('wwwroot'));
});
gulp.task('build-vendor-js', () => {
return gulp.src(vendorScripts)
.pipe(concat('vendor.min.js'))
.pipe(gulp.dest('wwwroot'));
});
gulp.task('build-vendor', gulp.parallel('build-vendor-css', 'build-vendor-js'));
gulp.task('default', gulp.series('build-vendor'));
Now, we also need to adjust our package.jsonto have dependencies on gulpand gulp-concat:
现在,我们还需要调整我们的package.json依赖于gulp和gulp-concat:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.0.0",
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"jquery": "3.3.1",
"popper.js": "1.12.9"
}
}
Finally, we edit our .csprojto add the following task which makes sure that our Gulp task runs when we build the project:
最后,我们编辑我们的.csproj以添加以下任务,以确保我们的 Gulp 任务在我们构建项目时运行:
<Target Name="RunGulp" BeforeTargets="Build">
<Exec Command="node_modules\.bin\gulp.cmd" />
</Target>
Now, when we build, the defaultGulp task runs, which runs the build-vendortasks, which then builds our vendor.min.cssand vendor.min.jsjust like we did before. So after adjusting our _Layout.cshtmljust like above, we can make use of jQuery and Bootstrap.
现在,当我们构建时,defaultGulp 任务运行,它运行build-vendor任务,然后构建我们的vendor.min.css和vendor.min.js就像我们之前所做的一样。所以_Layout.cshtml像上面一样调整我们之后,我们就可以使用jQuery和Bootstrap了。
While the initial setup of Gulp is a bit more complicated than the bundleconfig.jsonone above, we have now have entered the Node-world and can start to make use of all the other cool tools there. So it might be worth to start with this.
虽然 Gulp 的初始设置比bundleconfig.json上面的要复杂一些,但我们现在已经进入了 Node 世界,可以开始使用那里的所有其他很酷的工具。所以从这个开始可能是值得的。
Conclusion
结论
While this suddenly got a lot more complicated than with just using Bower, we also do gain a lot of control with those new options. For example, we can now decide what files are actually included within the wwwrootfolder and how those exactly look like. And we also can use this to make the first moves into the client-side development world with Node which at least should help a bitwith the learning curve.
虽然这突然变得比仅使用 Bower 复杂得多,但我们也确实通过这些新选项获得了很多控制权。例如,我们现在可以决定文件wwwroot夹中实际包含哪些文件以及这些文件的确切外观。而且我们还可以用它来使第一移动到客户端开发世界节点至少应有助于有点用的学习曲线。
回答by Sunsetquest
Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.
考虑到这一点,似乎 LibMan 方法最适合我添加 Bootstrap 的需求。我喜欢它,因为它现在内置在 Visual Studio 2017(15.8 或更高版本)中并且有自己的对话框。
The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bowerpage they write:

VS 添加到项目的默认方法使用 Bower,但看起来它正在退出。在微软凉亭页面的标题中,他们写道:

Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studiowhere it showshow libs can be added using a built-in Dialog:
以下几个链接指向在 Visual Studio 中将 LibMan 与 ASP.NET Core一起使用,其中显示了如何使用内置对话框添加库:
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]
在解决方案资源管理器中,右键单击应添加文件的项目文件夹。选择添加 > 客户端库。出现“添加客户端库”对话框:[来源:Scott Addie 2018]
Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")
然后对于引导程序(1)选择 unpkg,(2)输入“bootstrap@..”(3)安装。在此之后,您只想验证 _Layout.cshtml 或其他地方的所有包含是否正确。它们应该类似于href="~/lib/bootstrap/dist/js/bootstrap...")
回答by ysabih
回答by Auguste
What does the trick for me is:
对我来说有什么窍门是:
1) Right click on wwwroot > Add > Client Side Library
1) 右键单击 wwwroot > 添加 > 客户端库
2) Typed "bootstrap" on the search box
2)在搜索框中输入“bootstrap”
3) Select "Choose specific files"
3)选择“选择特定文件”
4) Scroll down and select a folder. In my case I chose "twitter-bootstrap"
4) 向下滚动并选择一个文件夹。就我而言,我选择了“twitter-bootstrap”
5) Check "css" and "js"
5)检查“css”和“js”
6) Click "Install".
6) 点击“安装”。
A few seconds later I have all of them wwwroot folder. Do the same for all client side packages that you want to add.
几秒钟后,我拥有了所有这些 wwwroot 文件夹。对要添加的所有客户端包执行相同操作。
回答by Marcel Melzig
Libman seems to be the tool preferred by Microsoft now. It is integrated in Visual Studio 2017(15.8).
Libman 似乎是微软现在首选的工具。它集成在 Visual Studio 2017(15.8) 中。
This articledescribes how to use it and even how to set up a restore performed by the build process.
本文介绍了如何使用它,甚至如何设置由构建过程执行的还原。
Bootstrap's documentationtells you what files you need in your project.
Bootstrap 的文档会告诉您项目中需要哪些文件。
The following example should work as a configuration for libman.json.
以下示例应用作 libman.json 的配置。
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "[email protected]",
"destination": "wwwroot/lib/bootstrap",
"files": [
"js/bootstrap.bundle.js",
"css/bootstrap.min.css"
]
},
{
"library": "[email protected]",
"destination": "wwwroot/lib/jquery",
"files": [
"jquery.min.js"
]
}
]
}
}
回答by Balah
Unfortunately, you're going to have a hard time using NuGet to install Bootstrap (or most other JavaScript/CSS frameworks) on a .NET Core project. If you look at the NuGet install it tells you it is incompatible:
不幸的是,您将很难使用 NuGet 在 .NET Core 项目上安装 Bootstrap(或大多数其他 JavaScript/CSS 框架)。如果您查看 NuGet 安装,它会告诉您它不兼容:
if you must know where local packages dependencies are, they are now in your local profile directory. i.e. %userprofile%\.nuget\packages\bootstrap\4.0.0\content\Scripts.
如果您必须知道本地包依赖项在哪里,它们现在位于您的本地配置文件目录中。即%userprofile%\.nuget\packages\bootstrap\4.0.0\content\Scripts。
However, I suggest switching to npm, or bower - like in Saineshwar's answer.
但是,我建议切换到 npm 或 bower - 就像 Saineshwar 的回答一样。
回答by Mark Redman
We use bootstrap 4 in asp.net core but reference the libraries from "npm" using the "Package Installer" extension and found this to be better than Nuget for Javascript/CSS libraries.
我们在 asp.net core 中使用 bootstrap 4,但使用“Package Installer”扩展从“npm”引用库,发现这比 Nuget 对于 Javascript/CSS 库更好。
We then use the "Bundler & Minifier" extension to copy the relevant files for distribution (from the npm node_modules folder, which sits outside the project) into wwwroot as we like for development/deployment.
然后,我们使用“Bundler & Minifier”扩展将相关的分发文件(从位于项目外部的 npm node_modules 文件夹中)复制到 wwwroot 中,因为我们喜欢进行开发/部署。
回答by klewis
BS4 is now available on .NET Core 2.2. On the SDK 2.2.105 x64 installer for sure. I'm running Visual Studio 2017 with it. So far so good for new web application projects.
BS4 现在可在.NET Core 2.2 上使用。在 SDK 2.2.105 x64 安装程序上是肯定的。我正在使用它运行 Visual Studio 2017。到目前为止,对于新的 Web 应用程序项目来说还不错。
回答by Edge
Why not just use a CDN? Unless you need to edit the code of BS, then you just need to reference the codes in CDN.
为什么不直接使用 CDN?除非你需要编辑BS的代码,那么你只需要引用CDN中的代码即可。
See BS 4 CDN Here:
在此处查看 BS 4 CDN:
https://www.w3schools.com/bootstrap4/bootstrap_get_started.asp
https://www.w3schools.com/bootstrap4/bootstrap_get_started.asp
At the bottom of the page.
在页面的底部。
回答by Alexandre le Grand
Use nmp configuration file (add it to your web project) then add the needed packages in the same way we did using bower.json and save. Visual studio will download and install it. You'll find the package the under the nmp node of your project.
使用 nmp 配置文件(将其添加到您的 Web 项目中)然后以与使用 bower.json 相同的方式添加所需的包并保存。Visual Studio 将下载并安装它。您将在项目的 nmp 节点下找到包。

