Cannot find module 'aspnet-webpack' when using 'dotnet publish' in .Net Core 2.0 & Angular

点点圈 提交于 2019-12-18 14:43:07

问题


I have been trying to follow answers to this problem but to no avail.. I am trying to publish my .Net Core 2.0 & Angular project using the command line command 'dotnet publish' I successfully publish, however when trying to run my project's .dll in the published folder, my project spits in out this error when run in a development environment:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'

When run in Production and allowing for the DeveloperExceptionPage (as shown in my statup.cs below) the .netcore app runs, but crashes within the actual web app, which I assume is due to the larger error, aspnet-webpack not being found:

NodeInvocationException: Uncaught (in promise): Error: No component factory found for HomeComponent. Did you add it to @NgModule.entryComponents?

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            //app.UseExceptionHandler("/Home/Error");
            app.UseDeveloperExceptionPage();
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }
}

I am not using @Angular/Cli, but I am using the default Angular Project that VS2017 (August update, I believe?) generates, which seems to only use Webpack. The problem seems to be that the Production config of the project expects a reference that I am not providing, but I can not figure out why that is.

No other answers to this question have helped me thus far, so I apologize if this is a repeat question.


回答1:


I had same issue with "aspnet-webpack", this was introduced halfway in the project development so I was bit surprised to see sudden death of the solution. It was all working fine couple of months on IIS but suddenly failed to boot.

IIS log files were not helpful, so I tried to resolve this couple of ways, one of them worked. Hurry!

Solution

I ran following on package-manager window :

dotnet run --project <Full path of *.csproj> --configuration Debug

It give me some pointers and I started searching for "Error: Cannot find module 'aspnet-webpack'" issue. I tried to go through all the changes for last couple of check-ins, and found out that we updated the "Microsoft.AspNetCore.All" from 2.0.0 to 2.0.3 version, so downgrading it to original version fixed it.

I guess they both uses different versions of node packages. So don't update for sake unless for a very good reason. Reading around this some bits are very tightly coupled to specific versions and Angular very easily breaks, if something changed. In process though I have managed to upgrade the node version to latest 5.0.0

Love to find more details, but for time being no details on why it needs a specific version.




回答2:


After you publish your .Net Core 2.0 & Angular project, and before you run it, you need to ensure that the environment variable ASPNETCORE_ENVIRONMENT isn't set to Development. The published project doesn't include support for the WebpackDevMiddleware or HotModuleReplacement. But it will attempt to use them if the environment is set to Development.

HotModuleReplacement automatically updates Webpack-built resources (such as JavaScript, CSS, or images) in your web browser whenever source files are changed. This is obviously something that you don't want in production.

If ASPNETCORE_ENVIRONMENT is set to "Development", you can change the setting with:

setx ASPNETCORE_ENVIRONMENT "Production"

You will need to close the current command window and open another to see the change.

You can also comment out the following code in startup.cs to accomplish the same result:

#if DEBUG
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
    HotModuleReplacement = true
});
#endif



回答3:


Make sure you have fully installed all of these dependencies:

npm install webpack-hot-middleware --save-dev
npm install webpack-dev-middleware --save-dev
npm install aspnet-webpack --save-dev



回答4:


In my case the cause was that the SPA (Vue in my case) is in the ClientApp folder and app.UseWebpackDevMiddleware expects it to be in the project root.

Setting the ProjectPath option solved this for me.

app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
  {
    HotModuleReplacement = true,
    ConfigFile = Path.Combine(env.ContentRootPath, @"ClientApp\node_modules\@vue\cli-service\webpack.config.js"),
    ProjectPath = Path.Combine(env.ContentRootPath, @"ClientApp")
  });



回答5:


I got the same error as you in a project without Angular:

Unhandled Exception: System.AggregateException: One or more errors occurred. (Webpack dev middleware failed because of an error while loading 'aspnet-webpack'. Error was: Error: Cannot find module 'aspnet-webpack'

Turned out to be a simple problem with node that I tend to forget.

npm install

Remember that npm commands need to be run in the top directory which contains your package.json file. I hope that this helps someone who has as much problems as me remembering to actually run npm commands. Thanks to the forum which reminded me:

https://www.ebenmonney.com/forum/?view=thread&id=20&part=1#postid-57




回答6:


Check that node.js is installed in production and is in the path.

Node.js is used by webpack

Also check that you have a recent version of Node.js (4+)

Reference : AspNetCore + Angular 2: WebpackDevMiddleware Error with new project

Version of Node.js can be checked with :

where.exe node.exe (Windows 7+)

which node.exe (linux bash)

And of course path environment variable should be checked and updated if pointing to obsolete Node.js

All the best




回答7:


AT configure function of startup.cs You can use if statement for development environment

 if (env.IsDevelopment())
        {
            // Print exception and all details for the developer 
            app.UseDeveloperExceptionPage();
            // Use WebPack to update css , js , html automatically 
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });  

        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();

        } 

You can this comman in command print to change current environment : setx ASPNETCORE_ENVIRONMENT "Development"




回答8:


The main reason for this error is that you are using a dependency somewhere in your code and it isn't installed in your solution. If you are using visual studio, try using clean build, it will show up the errors in your project which'll help you in finding it.



来源:https://stackoverflow.com/questions/46911802/cannot-find-module-aspnet-webpack-when-using-dotnet-publish-in-net-core-2-0

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