尝试运行Angular 8应用程序时出现“未捕获的错误:预期'样式'为字符串数组”

时间:2019-06-11 00:30:28

标签: angular asp.net-core webpack asp.net-core-mvc css-loader

我有一个Angular 8应用程序,该应用程序托管在.net Core 2.2 MVC应用程序中。它使用的是与Webpack 4捆绑在一起的项目模板。当我尝试在Visual Studio 2019中运行它时,它无法加载并出现以下错误:

    "Uncaught Error: Expected 'styles' to be an array of strings.
       at assertArrayOfStrings (vendor.js:34916)
       at CompileMetadataResolver.getNonNormalizedDirectiveMetadata 
      (vendor.js:50233)
       at CompileMetadataResolver._getEntryComponentMetadata (vendor.js:50878)
       at vendor.js:50869
       at Array.forEach (<anonymous>)
       at CompileMetadataResolver._getEntryComponentsFromProvider 
      (vendor.js:50868)
       at vendor.js:50841
       at Array.forEach (<anonymous>)
       at CompileMetadataResolver._getProvidersMetadata (vendor.js:50804)
       at vendor.js:50806"

一直有效,直到我进行了两次更改。

  1. 我将css-loader软件包从0.28.11升级到了2.1.1。这需要更改我的webpack.config.js文件才能使其正常工作。
  2. 我从7.2.14升级到Angular 8。这需要将Typescript升级到3.4。

我尝试了所有可能在Google上找到的潜在修复程序,但仍然收到此错误。我的想法不多了。请帮忙。

我的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;
const CopyWebpackPlugin = require('copy-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const TerserPlugin = require('terser-webpack-plugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = (env) => {
    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';

    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        mode: 'production',
        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', 'angular-router-loader'] : '@ngtools/webpack' },
                {
                    test: /\.html$/,
                    use: [{
                        loader: 'html-loader',
                        options: {
                            minimize: false
                        }
                    }]
                },
                {
                    test: /\.css(\?|$)/,
                    use: [
                        // fallback to style-loader in development
                        isDevBuild ? 'style-loader' : {
                            loader: MiniCssExtractPlugin.loader,
                            options: {

                            }
                        },
                        "css-loader",
                        "sass-loader"
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        'style-loader', // creates style nodes from JS strings
                        'css-loader', // translates CSS into CommonJS
                        'sass-loader' // compiles Sass to CSS
                    ]
                },
                {
                    test: /\.(png|gif|jpg|jpeg|woff|woff2|eot|ttf|svg)$/i,
                    use: [
                        {
                            loader: 'url-loader',
                            options: {
                                limit: 25000
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "[name].css",
                chunkFilename: "[id].css"
            }),
            new CheckerPlugin(),
            new CopyWebpackPlugin([
                { from: 'ClientApp/assets', to: 'assets' }
            ]),
            new CircularDependencyPlugin({
                // `onStart` is called before the cycle detection starts
                onStart({ compilation }) {
                    console.log('start detecting webpack modules cycles');
                },
                // `onDetected` is called for each module that is cyclical
                onDetected({ module: webpackModuleRecord, paths, compilation }) {
                    // `paths` will be an Array of the relative module paths that make up the cycle
                    // `module` will be the module record generated by webpack that caused the cycle
                    compilation.errors.push(new Error(paths.join(' -> ')));
                },
                // `onEnd` is called before the cycle detection ends
                onEnd({ compilation }) {
                    console.log('end detecting webpack modules cycles');
                }
            })
        ]
    };


    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')
            }),
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            })
        ].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 AngularCompilerPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ]),
        optimization: {
            //splitChunks: {},
            minimizer: [].concat(isDevBuild ? [] : [
                new TerserPlugin({
                    cache: true,
                    parallel: true,
                    terserOptions: {
                        compress: true,
                        ecma: 6,
                        mangle: {
                            toplevel: true, properties: false
                        },
                        toplevel: true,
                        keep_classnames: false,
                        keep_fnames: false
                    },
                    sourceMap: false
                })
            ])
        }
    });

    // 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.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AngularCompilerPlugin({
                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: isDevBuild ? 'inline-source-map' : '(none)',
        optimization: {
            //splitChunks: {},
            minimizer: [].concat(isDevBuild ? [] : [
                new TerserPlugin({
                    cache: true,
                    parallel: true,
                    terserOptions: {
                        compress: true,
                        ecma: 6,
                        mangle: {
                            toplevel: true, properties: false
                        },
                        toplevel: true,
                        keep_classnames: false,
                        keep_fnames: false
                    },
                    sourceMap: false
                })
            ])
        }
    });

    return [clientBundleConfig, serverBundleConfig];
};

我的webpack.config.vendor.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const treeShakableModules = [
    '@angular/animations',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    'zone.js'
];
const nonTreeShakableModules = [
    'bootstrap',
    'bootstrap/dist/css/bootstrap.css',
    '@ng-select/ng-select/themes/default.theme.css',
    'primeicons/primeicons.css',
    'primeng/resources/themes/nova-light/theme.css',
    'primeng/resources/primeng.css',
    'es6-promise',
    'es6-shim',
    'event-source-polyfill',
    'jquery'
];
const allModules = treeShakableModules.concat(nonTreeShakableModules);

module.exports = (env) => {
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        mode: 'production',
        stats: { modules: false },
        resolve: { extensions: ['.js'] },
        module: {
            rules: [
                {
                    test: /\.(png|gif|jpg|jpeg|woff|woff2|eot|ttf|svg)$/i,
                    use: [
                        {
                            loader: 'url-loader',
                            options: {
                                limit: 100000
                            }
                        }
                    ]
                }
            ]
        },
        output: {
            publicPath: 'dist/',
            filename: '[name].js',
            library: '[name]_[hash]'
        },
        plugins: [
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }) 
        ]
    };

    const clientBundleConfig = merge(sharedConfig, {
        entry: {
            // To keep development builds fast, include all vendor dependencies in the vendor bundle.
            // But for production builds, leave the tree-shakable ones out so the AOT compiler can produce a smaller bundle.
            vendor: isDevBuild ? allModules : nonTreeShakableModules
        },
        output: { path: path.join(__dirname, 'wwwroot', 'dist') },
        module: {
            rules: [
                {
                    test: /\.css(\?|$)/,
                    use: [
                        // fallback to style-loader in development
                        isDevBuild ? 'style-loader' : {
                            loader: MiniCssExtractPlugin.loader,
                            options: {

                            }
                        },
                        "css-loader",
                        "sass-loader"
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        'style-loader', // creates style nodes from JS strings
                        'css-loader', // translates CSS into CommonJS
                        'sass-loader' // compiles Sass to CSS
                    ]
                }
            ]
        },
        plugins: [
            new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "[name].css",
                chunkFilename: "[id].css"
            }),
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ].concat(isDevBuild ? [] : [
        ]),
        optimization: {
            // splitChunks: {},
            minimizer: [].concat(isDevBuild ? [] : [
                new TerserPlugin({
                    cache: true,
                    parallel: true,
                    terserOptions: {
                        compress: false,
                        ecma: 6,
                        mangle: false,
                        toplevel: false,
                        keep_classnames: true,
                        keep_fnames: true
                    },
                    sourceMap: true
                })
            ])
        }
    });

    const serverBundleConfig = merge(sharedConfig, {
        target: 'node',
        resolve: { mainFields: ['main'] },
        entry: { vendor: allModules.concat(['aspnet-prerendering']) },
        output: {
            path: path.join(__dirname, 'ClientApp', 'dist'),
            libraryTarget: 'commonjs2'
        },
        module: {
            rules: [
                {
                    test: /\.css(\?|$)/,
                    use: [
                        // fallback to style-loader in development
                        isDevBuild ? 'style-loader' : {
                            loader: MiniCssExtractPlugin.loader,
                            options: {

                            }
                        },
                        "css-loader",
                        "sass-loader"
                    ]
                },
                {
                    test: /\.scss$/,
                    use: [
                        'style-loader', // creates style nodes from JS strings
                        'css-loader', // translates CSS into CommonJS
                        'sass-loader' // compiles Sass to CSS
                    ]
                }
            ]
        },
        plugins: [
            new MiniCssExtractPlugin({
                // Options similar to the same options in webpackOptions.output
                // both options are optional
                filename: "[name].css",
                chunkFilename: "[id].css"
            }),
            new webpack.DllPlugin({
                path: path.join(__dirname, 'ClientApp', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            })
        ],
        optimization: {
            //splitChunks: {},
            minimizer: [].concat(isDevBuild ? [] : [
                new TerserPlugin({
                    cache: true,
                    parallel: true,
                    terserOptions: {
                        compress: false,
                        ecma: 6,
                        mangle: false,
                        toplevel: false,
                        keep_classnames: true,
                        keep_fnames: true
                    },
                    sourceMap: true
                })
            ])
        }
    });

    return [clientBundleConfig, serverBundleConfig];
};

我的package.json

{
    "name": "myapp",
    "private": true,
    "version": "0.0.0",
    "scripts": {
        "test": "karma start ClientApp/test/karma.conf.js",
        "postinstall": "webpack --config webpack.config.vendor.js"
    },
    "postcss": {},
    "dependencies": {
        "@angular/animations": "8.0.0",
        "@angular/cdk": "8.0.0",
        "@angular/common": "8.0.0",
        "@angular/compiler": "8.0.0",
        "@angular/core": "8.0.0",
        "@angular/forms": "8.0.0",
        "@angular/material": "8.0.0",
        "@angular/platform-browser": "8.0.0",
        "@angular/platform-browser-dynamic": "8.0.0",
        "@angular/platform-server": "8.0.0",
        "@angular/router": "8.0.0",
        "@fortawesome/angular-fontawesome": "0.4.0",
        "@fortawesome/fontawesome-svg-core": "1.2.20-2",
        "@fortawesome/free-solid-svg-icons": "5.10.0-2",
        "@ng-bootstrap/ng-bootstrap": "4.2.1",
        "@ng-select/ng-select": "2.20.0",
        "angular-dual-listbox": "4.7.0",
        "angular2-notifications": "2.0.0",
        "core-js": "3.1.3",
        "hammer-timejs": "1.1.0",
        "hammerjs": "2.0.8",
        "jwt-decode": "^2.2.0",
        "material-design-icons": "3.0.1",
        "primeicons": "1.0.0",
        "primeng": "7.1.3",
        "rxjs": "6.5.2",
        "zone.js": "0.9.1"
    },
    "devDependencies": {
        "@angular/compiler-cli": "8.0.0",
        "@intervolga/optimize-cssnano-plugin": "1.0.6",
        "@ngtools/webpack": "8.0.2",
        "@types/chai": "4.1.7",
        "@types/jasmine": "3.3.13",
        "@types/jwt-decode": "2.2.1",
        "@types/webpack-env": "1.13.9",
        "angular-router-loader": "0.8.5",
        "angular2-template-loader": "0.6.2",
        "aspnet-prerendering": "3.0.1",
        "aspnet-webpack": "3.0.0",
        "autoprefixer": "^9.6.0",
        "awesome-typescript-loader": "5.2.1",
        "bootstrap": "4.3.1",
        "chai": "4.2.0",
        "circular-dependency-plugin": "5.0.2",
        "clean-webpack-plugin": "3.0.0",
        "copy-webpack-plugin": "5.0.3",
        "css": "2.2.4",
        "css-loader": "2.1.1",
        "es6-promise": "4.2.6",
        "es6-shim": "0.35.5",
        "event-source-polyfill": "1.0.5",
        "expose-loader": "0.7.5",
        "extract-text-webpack-plugin": "4.0.0-beta.0",
        "file-loader": "4.0.0",
        "html-loader": "0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "isomorphic-fetch": "2.2.1",
        "jasmine-core": "3.3.0",
        "jquery": "3.4.1",
        "json-loader": "0.5.7",
        "karma": "4.1.0",
        "karma-chai": "0.1.0",
        "karma-chrome-launcher": "2.2.0",
        "karma-cli": "2.0.0",
        "karma-jasmine": "2.0.1",
        "karma-webpack": "3.0.5",
        "mini-css-extract-plugin": "0.7.0",
        "node-sass": "4.12.0",
        "popper.js": "1.15.0",
        "postcss-load-config": "^2.0.0",
        "postcss-loader": "^3.0.0",
        "preboot": "7.0.0",
        "raw-loader": "3.0.0",
        "reflect-metadata": "0.1.13",
        "sass-loader": "7.1.0",
        "style-loader": "0.23.1",
        "terser-webpack-plugin": "1.3.0",
        "to-string-loader": "1.1.5",
        "typescript": "3.4.5",
        "uglifyjs-webpack-plugin": "2.1.3",
        "url-loader": "2.0.0",
        "webpack": "4.33.0",
        "webpack-bundle-analyzer": "3.3.2",
        "webpack-cli": "3.3.3",
        "webpack-hot-middleware": "2.25.0",
        "webpack-merge": "4.2.1"
    }
}

2 个答案:

答案 0 :(得分:0)

默认情况下,Visual Studio 2019默认已经具有用于这样的角度的SPA模板

enter image description here

enter image description here

所以我建议您删除所有webpack,因为我记得那些webpack.config文件用于angular5。现在模板使用angular cli

欢呼

答案 1 :(得分:0)

我让它工作了,但是我不确定为什么。为了使其正常工作,我通过不使用mini-css-extract-plugin并从使用样式加载器切换为字符串加载器来更改了webpack.config.js。因此,该文件的css规则部分如下所示:

                {
                    test: /\.css(\?|$)/,
                    use: [
                        'to-string-loader',
                        'css-loader'
                    ]
                }

如果有人能告诉我它为什么起作用,我将非常感谢。我希望这可以帮助其他人。