How to access node_modules folder from wwwroot in

2019-01-19 11:39发布

问题:

How can I access the node_modules folder which is not included in the visual studio solution file from the wwwroot where my index.html is put. That index.html file need to reference the npm installed packages like angular.js.

But how?

I do not want to copy the whole node_modules folder into wwwroot. Those are not the files to live there...

I do not want to include the node_modules folder to the solution because that will slow down everything and hang up...

It seems Frontend development belongs not in VS...

回答1:

You are not supposed to access files from outside of wwwroot. The wwwroot folder is the public folder that's accessible from outside, when you host it.

Everything over it, is off-limits.

The typical publishing process is, that you have a gulp or grunt task that runs when your ASP.NET webproject is compiled or published, it would run the tasks there and copy over the necessary files inside wwwroot folder, i.e. wwwroot/libs or wwwdata/js.

Of course you can also manually copy the files over, but that's rather bad especially when you update many dependencies it's hard to keep track manually.

While it's not displayed in the solution (just indirectly, in the Dependencies/npm section), you can still make it visible by hitting the "Show all files" button on top of the Solution Explorer and copy over the files you need.

But it's best to set up a gulp task for it, but that's out of the scope of this question.



回答2:

There are at least two sane choices:

  • Serve other folders by using app.UseStaticFiles. The original solution is from Ode to Code. I use it for development, because Visual Studio doesn't seem to respect local .npmrc file set up with prefix = wwwroot/node_modules. Ideally, node_modules should be bundled for production. There is npm rollup plugin that can automatically bundle scripts using import feature (ES2015).

  • Serve node_modules from CDN (e.g. unpkg.com). This is fairly simple, the only downside is CDN's response time, especially if you've disabled browser caching for development purposes.

Here is the code to serve folders in ASP.NET Core. You only need to change the Startup class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...some other stuff

    if (env.IsDevelopment())
    {
        ServeFromDirectory(app, env, "node_modules");
    }
}

public void ServeFromDirectory(IApplicationBuilder app, IHostingEnvironment env, string path)
{
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(env.ContentRootPath, path)
        ),
        RequestPath = "/" + path
    });
}