13 安装前端库.mp4 (81.83MB)

VS 使用 NPM

可以直接添加 NPM 配置文件:右键项目添加 - 新建项 - 搜索 npm。

然后直接编辑 NPM 配置文件(pacakge.json)并保存,VS 就会自动添加包。

自动创建的 node_modules 文件夹默认不被伺服,可以通过修改 Startup 手动将其伺服。

  1. app.UseStaticFiles(new StaticFileOptions
  2. {
  3. RequestPath = "/node_modules",
  4. FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
  5. });

参见:NuGet & NPM

前端验证

通过 jquery + jquery-validation + jquery-validation-unobtrusive 实现前端验证。

  1. {
  2. "version": "1.0.0",
  3. "name": "tutorial",
  4. "private": true,
  5. "devDependencies": {},
  6. "dependencies": {
  7. "bootstrap": "4.3.1",
  8. "jquery": "3.3.1",
  9. "jquery-validation": "1.19.0",
  10. "jquery-validation-unobtrusive": "3.2.11"
  11. }
  12. }

CDN 与 asp-fallback

https://www.bootcdn.cn

通过 asp-fallback-src 和 asp-fallback-test 实现回落机制,当测试发现 CDN 的 js 无法使用时,切换为本地 js。

  1. <environment include="Development">
  2. <script src="~/node_modules/jquery/dist/jquery.js"></script>
  3. <script src="~/node_modules/jquery-validation/dist/jquery.validate.js"></script>
  4. <script src="~/node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script>
  5. </environment>
  6. <environment exclude="Development">
  7. <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"
  8. asp-fallback-src="~/node_modules/jquery/dist/jquery.js"
  9. asp-fallback-test="window.jQuery"></script>
  10. <script src="https://cdn.bootcss.com/jquery-validate/1.19.0/jquery.validate.js"
  11. asp-fallback-src="~/node_modules/jquery-validation/dist/jquery.validate.js"
  12. asp-fallback-test="window.jQuery && window.jQuery.validator"></script>
  13. <script src="https://cdn.bootcss.com/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.js"
  14. asp-fallback-src="~/node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"
  15. asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"></script>
  16. </environment>

可以使用相似的方法配置 css 回落:

  1. <environment include="Development">
  2. <link href="~/node_modules/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
  3. </environment>
  4. <environment exclude="Development">
  5. <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.css"
  6. asp-fallback-href="~/node_modules/bootstrap/dist/css/bootstrap.css"
  7. asp-fallback-test-class="sr-only"
  8. asp-fallback-test-property="position"
  9. asp-fallback-test-value="absolute"
  10. rel="stylesheet">
  11. </environment>

Gulp

官方推荐使用 Gulp 伺服前端库。

看了一下官方教程,还是 NPM + bundle + minify 好上手

源码

Tutorial.zip