asp.net - Angular 5/ASP.NET - “No ResourceLoader implementation has been provided. Can' t 读取 URL”

标签 asp.net angular visual-studio visual-studio-2017

我正在尝试在 Visual Studio 2017 上构建一个新的 Angular5/ASP.NET SPA。因此我使用 Angular 创建了一个 .NET Core->ASP.NET Core-Web 应用程序,这导致了一个包含 Angular4 示例的项目申请。

运行此应用程序完全没有问题,当我尝试使用此应用程序继续使用 Angular 5(5.0.1 或 5.0.0,无关紧要)时,问题就开始了。

完成所有必要步骤后,应用程序在 Debug模式下运行良好。但是尝试在 Release 中构建和启动它(或将其部署到 Azure)会导致以下错误:

An unhandled exception occurred while processing the request.

NodeInvocationException: No ResourceLoader implementation has been provided. Can't read the url "app.component.html"
Error: No ResourceLoader implementation has been provided. Can't read the url "app.component.html"
at Object.get (E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:98069:15)
at DirectiveNormalizer.module.exports.DirectiveNormalizer._fetch (E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:44087:43)
at DirectiveNormalizer.module.exports.DirectiveNormalizer._preParseTemplate (E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:44142:29)
at DirectiveNormalizer.module.exports.DirectiveNormalizer.normalizeTemplate (E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:44122:36)
at CompileMetadataResolver.module.exports.CompileMetadataResolver.loadDirectiveMetadata (E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:55794:75)
at E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:74510:72
at Array.forEach (native)
at E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:74509:72
at Array.forEach (native)
at JitCompiler.module.exports.JitCompiler._loadModules (E:\angular4_spielwiese\vs spielwiese\myAngularApp\myAngularApp\ClientApp\dist\vendor.js:74506:75)
Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance+<InvokeExportAsync>d__7.MoveNext()

我为迁移到 Angular5 所做的是: 将所有 Angular 模块的 package.json 中的版本更改为 5.0.1,同时将 typescript、rxjs、angular/cli 和 @ngtools/webpack (1.5.0 -> 1.8.0) 更改为更新版本 所以我的新 package.json 看起来像这样:

{
  "name": "myAngularApp",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/animations": "^5.0.1",
    "@angular/common": "^5.0.1",
    "@angular/compiler": "^5.0.1",
    "@angular/core": "^5.0.1",
    "@angular/forms": "^5.0.1",
    "@angular/http": "^5.0.1",
    "@angular/platform-browser": "^5.0.1",
    "@angular/platform-browser-dynamic": "^5.0.1",
    "@angular/platform-server": "^5.0.1",
    "@angular/router": "^5.0.1",
    "@types/webpack-env": "^1.13.0",
    "angular2-template-loader": "^0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "^3.2.1",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.28.7",
    "es6-shim": "^0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "^0.7.3",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^3.2.1",
    "json-loader": "^0.5.4",
    "preboot": "^5.1.7",
    "raw-loader": "^0.5.1",
    "reflect-metadata": "^0.1.10",
    "rxjs": "^5.5.2",
    "style-loader": "^0.19.0",
    "to-string-loader": "^1.1.5",
    "typescript": "^2.6.1",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@angular/cli": "1.5.0",
    "@angular/compiler-cli": "^5.0.1",
    "@ngtools/webpack": "1.8.0",
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.6.3",
    "chai": "4.0.2",
    "jasmine-core": "2.6.4",
    "karma": "1.7.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.3",
    "url-loader": "0.6.2",
    "webpack": "3.8.1",
    "webpack-hot-middleware": "2.20.0",
    "webpack-merge": "4.1.1"
  }
}

然后我将 webpack.config.js 中的 AotPlugin 更改为 AngularCompilerPlugin 这是我的 webpack.config.js:

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

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        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$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] },// '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: [ 'to-string-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 AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#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 AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

当我现在使用 VS2017 中的 Release-config 启动应用程序(执行 npm 安装,然后使用 --env.prod 开关运行 webpack)时,我得到上面的堆栈跟踪。当我将应用程序部署到 Azure 时,也会发生同样的事情。

在本地主机上,如果我等待几秒钟并强制重新加载我的浏览器,应用程序会突然运行。这在 Azure 上不起作用,这对我来说有点奇怪。

您对我可能做错了什么或遗漏了什么有什么建议吗?

最佳答案

几天来我遇到了同样的问题,我在 GitHub 中找到了一个 VS2017 - Angular 5 项目(没有确切的 URL),我从中复制了 webpack.config.js 我也更新了我的 Angular 到 5.0.3 我运行了有效的“dotnet publish”(或“dotnet publish -c Release”) 我面临(并且仍然面临)的唯一问题是在复杂化期间,编译器弄乱了 main-server.js,因此作为一种解决方法,我在复杂化之前复制了 main-server.js(10MB 对 2MB)。 运行“dotnet mydll.dll”时 - 效果很好。

webpack.config.js:

/*
 * Webpack (JavaScriptServices) with a few changes & updates
 * - This is to keep us inline with JSServices, and help those using that template to add things from this one
 *
 * Things updated or changed:
 * module -> rules []
 *    .ts$ test : Added 'angular2-router-loader' for lazy-loading in development
 *    added ...sharedModuleRules (for scss & font-awesome loaders)
 */

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
//const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        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', 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
            })
        ] : [
                // new BundleAnalyzerPlugin(),
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AngularCompilerPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ]),
        devtool: isDevBuild ? 'cheap-eval-source-map' : false,
        node: {
            fs: "empty"
        }
    });

    // 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'
            }),
            new webpack.ContextReplacementPlugin(
                // fixes WARNING Critical dependency: the request of a dependency is an expression
                /(.+)?angular(\\|\/)core(.+)?/,
                path.join(__dirname, 'src'), // location of your src
                {} // a map of your routes
            ),
            new webpack.ContextReplacementPlugin(
                // fixes WARNING Critical dependency: the request of a dependency is an expression
                /(.+)?express(\\|\/)(.+)?/,
                path.join(__dirname, 'src'),
                {}
            )
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin({
                compress: false,
                mangle: false
            }),
            // Plugins that apply in production builds only
            new AngularCompilerPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        // switch to "inline-source-map" if you want to debug the TS during SSR
        devtool: isDevBuild ? 'cheap-eval-source-map' : false
    });

    return [clientBundleConfig, serverBundleConfig];
};

编辑 - 除了对 webpack.config.js 进行更改外,我还进行了以下两项更改,解决了我的问题!: 在 index.cshtml 中: 改变自

<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>

到:

<app>Loading...</app>

在 boot.server.ts 中: 更改自:

const zone = moduleRef.injector.get(NgZone);

到:

const zone: NgZone = moduleRef.injector.get(NgZone);

阅读http://www.talkingdotnet.com/upgrade-angular-4-app-angular-5-visual-studio-2017/了解更多信息。

关于asp.net - Angular 5/ASP.NET - “No ResourceLoader implementation has been provided. Can' t 读取 URL”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303692/

相关文章:

asp.net - System.NullReferenceException : Object reference not set to an instance of an object. in vb.net

c# - 确认代码隐藏中的函数

asp.net - 具有多个 Azure 云应用程序实例的 Asp.Net Charting 控件中的 #SEQ 关键字

angular - 使用 angular 4 在 mat-table 中添加一个新行

asp.net - 环境标签助手

visual-studio - 在 Visual Studio 中记录调用堆栈

c# - 十六进制值 0x00,是无效字符 : still encounter problem after replace\0 with ""

无法找到 Angular Material MatTableDataSource

javascript - 如何在主题行为之前检查谷歌扩展存储?

c# - 从 ASP.NET WebForms 重定向到 MVC