The problem with reflect-metadata - __webpack_require__ arises from the absence of the 'Require' definition

I'm facing an issue while trying to launch my angular app in Visual Studio. It seems to be stuck on the "Loading..." section.

Upon checking Chrome's error console, I came across the following error:

https://i.sstatic.net/1aSZT.jpg

Uncaught ReferenceError: require is not defined at Object. < anonymous > __ webpack_require __

The reflect-metadata shows the following:

module.exports = require("reflect-metadata");
, and it's causing the error due to the use of "require".


Take a look at some snippets from my code...

webpack.config.js

const path = require('path');    
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');

// Rest of the code here...

After searching online for solutions, most of them suggest modifications in the systemjs.config file. However, since my app isn't built with Angular CLI, that solution doesn't apply.


UPDATES SECTION

  1. UPDATE #1

It appears that the issue stems from using webpack-node-externals in browser mode. I need to find an alternative approach for this.


If you have any suggestions or troubleshooting tips, please share.

Thank you in advance!


  1. UPDATE #2

Update: I managed to resolve the issue, check out my answer below.

Answer №1

UNDERSTOOD!

The root of the problem stemmed from my use of webpack-node-externals in my shared configuration.

To delve deeper into the solution, please refer to both my question and answer on this matter by visiting: Webpack - Excluding node_modules with also keep a separated browser and server management. This will provide more comprehensive details.

In summary, here are the steps I took:

  • Installation of requireJS ==> http://requirejs.org/docs/node.html
  • Elimination of
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
    from my general webpack configuration and transferring it under my server setup (accomplished prior to posing the question, yet incredibly crucial) [refer to webpack.config.js content in the linked inquiry above or in the snippet provided]
  • Inclusion of target: 'node', prior to my previous externals mention within my server-side segment (executed before raising the question, however an essential step) [see webpack.config.js content in the linked question above or in the excerpt below]
    This ensures the target remains 'web' for the browser side (default target), transitioning to 'node' solely for the server
  • Manually executed webpack config vendor command via PowerShell using
    webpack --config webpack.config.vendor.js
  • Manually ran webpack config command through PowerShell employing
    webpack --config webpack.config.js

These actions proved effective for me! Hopefully, they will be beneficial to anyone who happens upon this question while facing the same dilemma!


webpack.config.js snippet:

const path = require('path');    
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

var nodeExternals = require('webpack-node-externals');

module.exports = (env) => {
    // Configuration common to client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        //removed from here, moved below.
        //externals: [nodeExternals()], // in order to ignore all modules in node_modules folder

        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: [ '.js', '.ts' ] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' 
        },
        module: {
            rules: [
                { test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Client-side bundle settings for browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            })
        ].concat(isDevBuild ? [
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map',
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]')
            })
        ] : [
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Server-side (prerendering) bundle configuration for Node environment
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },

        target: 'node',
        externals: [nodeExternals()],
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

Utilize Ajax to invoke a function simultaneously with another Ajax call that includes preventDefault to submit the data

I am currently implementing two AJAX calls within my form. The first call is used to dynamically update the options in the second select element based on the value selected in the first select element. This call reaches out to a PHP page to process the dat ...

Performance issues are being experienced on website for tablet and smartphone usage due to slow loading times

My client's website is running on an old Dell PowerEdge 2600 with Windows Server 2008. While desktop and laptop access to the site is smooth, access from tablets and smartphones is extremely slow, taking over 10 minutes to load or sometimes not loadin ...

Executing Javascript and C# functions through a single click

I need to call a method in Javascript and a method in C# when a button is clicked. First, I want to call the C# method called 'Find_Direction' on click, which takes two inputs. Then, I want to call the Javascript method named calcRoute. I attem ...

What is the best way to determine if an item in an array is not empty?

Let's consider an array: arr = [{}, {}, {}, {}] If we want to determine the length of the array by counting only objects that contain at least one property, we can do this: [{}, {name: "Manchester United", odds: 3}, {}, {}] // 1 [{}, {name: "Liver ...

Troubleshooting a metadata issue while pre-compiling a feature module in Angular 2

Currently, I am in the process of developing an Angular2 library using Angular2 RC6. This particular library consists of a single module: import { Component, OnInit, NgModule } from '@angular/core'; import { CommonModule } from '@angular/c ...

Issue with remove functionality in Vue js implementation causing erratic behavior in my script

Within my Vue.js code, I have a functionality that displays categories from an API. When a category is clicked, it is added to the AddCategory array and then posted to the API. I have also implemented a button called RemoveAll which successfully empties th ...

Unable to modify the border-radius property of Material UI DatePicker

I'm having difficulties setting rounded borders for my DatePicker component from @mui/x-date-pickers and Material UI V5. Here is the intended look I am aiming for: https://i.stack.imgur.com/c1T8b.png I've tried using styled components from Mat ...

Troubleshooting problems with the Quora pixel after refreshing the page

Having a strange issue with the Quora pixel integration on Angular. I have added the script in the HTML code as follows: ! function(q, e, v, n, t, s) { if (q.qp) return; n = q.qp = function() { n.qp ? n.qp.apply(n, arguments) : n.queue.push ...

Issue with Vue JS Components: Button function not working on second click with @click

I've been working with Vue JS and Laravel to create a modal. The first time I press the button with @click, it works fine but the next time I encounter an error. Here's my Laravel Blade code: <div class="col-span-12 mb-5" id="a ...

I aim to adjust the width of a logo and ensure its size is fixed for optimal visibility

The selected logo needs to be more visible. I have attempted to use media queries to adjust its visibility, but I am having trouble with it. I want the logo to be able to stretch in width, but I am unsure how to achieve that. Currently, this is what I hav ...

TypeScript declaration specifying a NodeJS module that exports a class definition

Currently grappling with creating a TypeScript declaration file for HtmlWebpackPlugin, but struggling to make it functional. The default export of HtmlWebpackPlugin is the constructor for the class HtmlWebpackPlugin, which I aim to use as shown below: so ...

Incorrect deduction of the argument type for a higher-order function

If I wanted to create a function that takes an object of type T and another value, where the type P should somehow be restricted by T (for example, P should be an array of keys of T), I could easily write it like this: function customFunction<T, P exte ...

The essential criteria for script tag and page validation requirements

There are instances where I have pages that contain only a script without any content (such as sending data through postMessage and then closing itself). In these cases, is the page considered valid with just <script>doSomeStuff</script> or do ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...

Obtaining connection data in jsPlumb can be accomplished through a variety of

I have created a compact table of nodes that allow me to drag and drop connections or manually input node IDs to establish connections between them. Despite searching through the documentation and scouring the internet for examples, I am struggling to fin ...

Is there a way to create a div that resembles a box similar to the one shown in the

Hello, I am attempting to achieve a specific effect on my webpage. When the page loads, I would like a popup to appear at the center of the screen. To accomplish this, I have created a div element and initially set its display property to 'none'. ...

One effective method for populating my form following the retrieval of JSON data

Currently, I am working on a VueJs project where I am fetching data from a Mysql database using Axios. My next step is to implement an edit option for user profiles. I am wondering what the most efficient method is for populating the form with the fetche ...

Is it possible to access a class with protected/private fields written in TypeScript from outside the class in JavaScript?

Currently, I am delving into TypeScript classes (though my experience with OOP is limited). The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html Here's the issue at hand: I ...