22

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.

Vladimir Zdenek
  • 2,270
  • 1
  • 18
  • 23
Rinktacular
  • 1,116
  • 3
  • 19
  • 45
  • Your statement "When run in Production and allowing for the DeveloperExceptionPage", seems to be a contradiction. If the environment is set to Production, it's not going to use the DeveloperExceptionPage. What is the setting of your environment variable "ASPNETCORE_ENVIRONMENT"? And what does it print out for "Hosting environment" when you run "dotnet xxx.dll"? – John Pankowicz Dec 03 '17 at 22:58
  • A late reply, but might help someone.. I think this could be because you have the npm package "aspnet-webpack" in the devDependencies in package.json @ "devDependencies": { "aspnet-webpack": n.n.n } and it will not be considered in your build/published code, but then you try to run "UseWebpackDevMiddleware HotModuleReplacement" that requires the dependency. (The reason I came here was that I got the same error because I missed to add the dependency in my package.json while doing a "manual merge" of a React app into an existing dotnet core app. ) – JimiSweden Jul 07 '18 at 22:46

8 Answers8

13

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
John Pankowicz
  • 4,203
  • 2
  • 29
  • 47
  • This helped... but I set it to Development due to a vague bug in the first place. :-/ – Stefan May 26 '18 at 17:26
  • This also helped me, although my issue was caused by upgrading dotnet core versions, which automatically added the environment variable to my web.config – bmw15 Dec 07 '18 at 19:11
  • This fixed it! We added a dedicated configuration switch to turn the webpack dev middleware on and off for local development vs development builds created through dotnet publish. – Ryan Jan 30 '20 at 01:04
11

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
Nidust
  • 599
  • 1
  • 8
  • 16
9

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")
  });
Jason Learmouth
  • 569
  • 5
  • 9
7

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.

Nicolás Alarcón Rapela
  • 2,714
  • 1
  • 18
  • 29
Sanjay Zalke
  • 1,331
  • 1
  • 18
  • 25
  • Interesting, I move away to a node.js app the remove the .Net Core component entirely, but I plan to re implement that soon to give it another go. I am sure something like this is going to be very helpful, thank you! I agree, more details would be lovely.. – Rinktacular Nov 27 '17 at 14:45
  • 1
    I was hoping to solve this issue downgrading from 2.0.5 to 2.0.0 as you said Sanjay, but I didn't have luck. I still get the same error. – Carolina Bauque Feb 09 '18 at 15:50
  • @CarolinaBauque Can you provide more info on the error details you are getting on the Package Mgr console? – Sanjay Zalke Feb 14 '18 at 08:20
  • I realized that I never commented back on here, but this solution did help me. – Rinktacular May 08 '18 at 13:26
  • For me, I had to downgrade "aspnet-webpack" in package.json from 2.0.3 to 2.0.0 – levis84 Sep 01 '18 at 21:07
7

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

URL_Flip
  • 143
  • 2
  • 9
2

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

Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53
0

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"

Omar Isaid
  • 514
  • 5
  • 12
0

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.

BeaST 30
  • 696
  • 1
  • 10
  • 22