问题
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
commandor
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:
- right click on the lib directory inside wwwroot
- Click Add, and choose Client-Side Library
- From the provider, choose fileSystem (if desired files already exist in node_modules folder)
- Choose all or specific files needed
- 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