简体   繁体   English

未在反射元数据上定义需求-__webpack_require__问题

[英]Require is not defined on reflect-metadata - __webpack_require__ issue

I'm trying to launch my angular app on visual studio but when it starts, it stucks on "Loading..." section. 我试图在Visual Studio上启动我的角度应用程序,但是当它启动时,它停留在“正在加载...”部分。

If i read Chrome's error console i get the following error: 如果我阅读了Chrome的错误控制台,则会收到以下错误消息:

ERROR_ON_CHROME_CONSOLE

Uncaught ReferenceError: require is not defined at Object. 未捕获的ReferenceError:require未在Object上定义。 < anonymous > __ webpack_require __ <匿名> __ webpack_require __

The reflect-metadata contains the following: module.exports = require("reflect-metadata"); 反射元数据包含以下内容: module.exports = require("reflect-metadata"); , which "require" causes the error. ,“需要”会导致错误。


Here's some of my code... 这是我的一些代码...

webpack.config.js 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');

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {

        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/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        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()]
    };

    // Configuration for client-side bundle suitable for running in 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 ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    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 ? [] : [
            // Plugins that apply in production builds only
            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',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

Searching on the internet, all of the troubleshooting suggests doing something on the systemjs.config file but mine is not an angular-cli app so I can't do it. 在Internet上搜索时,所有故障排除建议在systemjs.config文件上执行某些操作,但是我的不是angular-cli应用程序,因此我无法执行此操作。


UPDATES SECTION 更新部分

  1. UPDATE #1 更新1

Looks like the problem is caused by webpack-node-externals executed in browser mode. 看来问题是由在浏览器模式下执行的webpack-node-externals引起的。

Got to find another way for that. 找到了另一种方法。


Got any troubleshooting or potential solution suggestion? 有任何故障排除或潜在的解决方案建议吗?

Thanks in advance! 提前致谢!


  1. UPDATE #2 更新#2

I've made it, see my answer below 我已经做到了,请参阅下面的答案

GOT IT! 得到它了!

The issue was caused by webpack-node-externals used on my common configuration. 问题是由我的常用配置中使用的webpack-node-externals引起的。

See my question and my answer to my own question at the following: Webpack - Excluding node_modules with also keep a separated browser and server management for more details. 请在以下位置查看我的问题和对自己问题的回答: Webpack-排除node_modules并保留单独的浏览器和服务器管理以获取更多详细信息。

So, in a nutshell, the steps that I followed are these: 简而言之,我遵循的步骤如下:

  • Installing requireJS ==> http://requirejs.org/docs/node.html 安装requireJS ==> http://requirejs.org/docs/node.html
  • Removing externals: [nodeExternals()], // in order to ignore all modules in node_modules folder from my common webpack configuration and adding it under my server configuration (done before my question, but it's a really important step) [see webpack.config.js content in the question linked right above in this answer or in the snippet below] 删除 externals: [nodeExternals()], // in order to ignore all modules in node_modules folder从我的常见Webpack配置中externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 并将其添加到我的服务器配置下 (在我的问题之前做,但这是一个非常重要的步骤)[请参阅webpack.config .js内容位于此答案上方或下面的摘录链接的问题中]
  • Adding target: 'node', before my externals point above, under my server side section (done before my question, but it's a really important step) [see webpack.config.js content in the question linked right above in this answer or in the snippet below] 在我的外部指向上方之前,在服务器端部分下方添加 target: 'node', (在我的问题之前完成,但这是非常重要的一步)[请参阅此答案或以上内容中链接的问题中的webpack.config.js内容下面的代码段]
    This makes sure that browser side keeps target:'web' (default target), and target becomes node just for the server. 这可以确保浏览器端保留目标:“ web”(默认目标),并且目标成为仅用于服务器的节点。
  • launched webpack config vendor command manually from powershell webpack --config webpack.config.vendor.js 从powershell webpack --config webpack.config.vendor.js 手动启动了webpack config供应商命令 webpack --config webpack.config.vendor.js
  • launched webpack config command manually from powershell webpack --config webpack.config.js 从powershell webpack --config webpack.config.js 手动启动了webpack config命令

That worked for me! 那对我有用! Hope It will works also for anyone else reading this question and encountering this issue! 希望它也适用于任何其他阅读此问题并遇到此问题的人!


webpack.config.js content: 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');

module.exports = (env) => {
    // Configuration in common to both 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/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        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()]
    };

    // Configuration for client-side bundle suitable for running in 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 ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
            // Plugins that apply in production builds only
            new webpack.optimize.UglifyJsPlugin(),
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                exclude: ['./**/*.server.ts']
            })
        ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    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 ? [] : [
            // Plugins that apply in production builds only
            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')
        },

        //added target and externals HERE, in order to prevent webpack to read node_modules
        //this also prevents fake-positives parsing errors
        target: 'node',
        externals: [nodeExternals()], // in order to ignore all modules in node_modules folder,
            devtool: 'inline-source-map'
        });

    return [clientBundleConfig, serverBundleConfig];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 __webpack_require__(...).context 不是 function - __webpack_require__(...).context is not a function 在 __webpack_require__ 中的 NextJS 中构建错误 - Build errors in NextJS in __webpack_require__ 未捕获的类型错误:__webpack_require__(...).context 不是 function - Uncaught TypeError: __webpack_require__(...).context is not a function 为什么webpack向&#39;__webpack_require__&#39;函数添加属性? - Why webpack add properties to '__webpack_require__' function? TypeError: __webpack_require__(...).context 不是 function - 硬编码但不带参数 - TypeError: __webpack_require__(…).context is not a function - Works hardcoded but not with parameter 诊断未捕获的TypeError:__webpack_require __(…).createServer不是函数? - Diagnosing Uncaught TypeError: __webpack_require__(…).createServer is not a function? Karma Jasmine - 未捕获的类型错误:__webpack_require__(...).context 不是 function - Karma Jasmine - Uncaught TypeError: __webpack_require__(...).context is not a function 未捕获的类型错误:无法读取 __webpack_require__ 处未定义的属性“调用” - Uncaught TypeError: Cannot read property 'call' of undefined at __webpack_require__ “require未定义”使用webpack 2 - “require is not defined” Using webpack 2 Webpack ReferenceError: require 未定义 (ReactJS) - Webpack ReferenceError: require is not defined (ReactJS)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM