«Uncaught Error: ожидаемые стили должны быть массивом строк» ​​при попытке запустить приложение Angular 8 - PullRequest
0 голосов
/ 11 июня 2019

У меня есть приложение 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. Я обновил до Angular 8 с 7.2.14.Это потребовало обновления 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];
};

Мой пакет. 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 голосов
/ 13 июня 2019

Я получил это работает, но я не уверен, почему. Чтобы заставить его работать, я изменил свой webpack.config.js, не используя mini-css-extract-plugin и переключившись с использования style-loader на to-string-loader. Таким образом, часть правила css этого файла выглядит следующим образом:

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

Если кто-нибудь скажет мне, почему это работает, я буду очень признателен. Я надеюсь, что это может помочь кому-то еще.

0 голосов
/ 12 июня 2019

По умолчанию в Visual Studio 2019 уже есть шаблон SPA для углов, подобный этому

enter image description here

enter image description here

Так что я бы посоветовал вам удалить все ваши веб-пакеты, потому что, насколько я помню, эти файлы webpack.config используются для угловых 5. Сейчас шаблон использует угловые кли

Cheers

...