How to use npm packages with ASP.NET CORE 2 in Visual Studio 2017?

旧街凉风 提交于 2020-01-05 07:26:51

问题


I added some npm packages to my ASP.NET Core 2 project in Visual Studio 2017. Now I want to use css and js files from these packages, but VS doesn't see them because node_modules folder is outside wwwroot. What is the common practice here, how to make Visual Studio working with node_modules?


回答1:


The common practice is to bundle your web assets, and put only the compiled bundle into your wwwroot folder.

Since Visual Studio 2015 we have multiple Taskrunners from the NPM World:

  • Gulp
  • Grunt

With them you could write a script, which automatically bundles your web assets. This script has full access to the NPM infrastructure.

There are some tools out there which make this super easy:

  • gulp-uglify
  • gulp-cssmin

More Information: https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp


That said, it is also possible to include your npm folder:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
        RequestPath = "/node_modules"
    });
}

But this would be the wrong way.




回答2:


As soon as you add the desired npm packages to your project, either through:

  • npm install command

    or

  • typing the package name and its version in the npm configuration file

    or

  • searching the package in the Library Dialog, indicated in the following image for instance,

they will be downloaded and restored in the node_modules folder. But to use them in your views, you need to add them to a client-side folder, such as lib under wwwroot folder.

You can copy them to wwwroot folder manually through the file system, or use the Library dialog:

  1. right click on the lib directory inside wwwroot
  2. Click Add, and choose Client-Side Library
  3. From the provider, choose fileSystem (if desired files already exist in node_modules folder)
  4. Choose all or specific files needed
  5. Click install

However, you can manage this file copying operation manually.

Now, from the folders under wwwroot, you can drag and drop the file into your views. Be careful to omit ~ if your view is a Layout.

Hope this helped.... More details here: https://docs.microsoft.com/en-us/aspnet/core/client-side/libman/libman-vs?view=aspnetcore-3.0



来源:https://stackoverflow.com/questions/49120107/how-to-use-npm-packages-with-asp-net-core-2-in-visual-studio-2017

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!