如何防止 npm 安装后出现 Webpack 错误?

nas*_*ash 5 node.js webpack angular-fullstack isparta

我当时正在做一个项目,一切都很顺利,直到我做到了npm install

\n\n

然后,Webpack 抛出以下错误:

\n\n
new ForkCheckerPlugin(),\n        ^\nTypeError: ForkCheckerPlugin is not a constructor\n    at makeWebpackConfig (/home/nsanz/Documentos/git/tachology/webpack.make.js:252:9)\n    at Object.exports.default (/home/nsanz/Documentos/git/tachology/server/config/express.js:86:27)\n    at Object.<anonymous> (/home/nsanz/Documentos/git/tachology/server/app.js:28:1)\n    at Module._compile (module.js:570:32)\n    at loader (/home/nsanz/Documentos/git/tachology/node_modules/babel-register/lib/node.js:144:5)\n    at Object.require.extensions.(anonymous function) [as .js] (/home/nsanz/Documentos/git/tachology/node_modules/babel-register/lib/node.js:154:7)\n    at Module.load (module.js:487:32)\n    at tryModuleLoad (module.js:446:12)\n    at Function.Module._load (module.js:438:3)\n    at Module.require (module.js:497:17)\n    at require (internal/module.js:20:19)\n    at Object.<anonymous> (/home/nsanz/Documentos/git/tachology/server/index.js:12:28)\n    at Module._compile (module.js:570:32)\n    at Object.Module._extensions..js (module.js:579:10)\n    at Module.load (module.js:487:32)\n    at tryModuleLoad (module.js:446:12)\n    at Function.Module._load (module.js:438:3)\n    at Module.runMain (module.js:604:10)\n    at run (bootstrap_node.js:389:7)\n    at startup (bootstrap_node.js:149:9)\n    at bootstrap_node.js:504:3  \n
Run Code Online (Sandbox Code Playgroud)\n\n

我的 package.json 如下所示:

\n\n
 {\n  "name": "tachology",\n  "version": "0.0.0",\n  "main": "server/index.js",\n  "dependencies": {\n    ...\n  },\n  "devDependencies": {\n    "angular-mocks": "~1.6.0",\n    "autoprefixer": "^7.1.2",\n    "babel-core": "^6.6.5",\n    "babel-eslint": "^7.2.3",\n    "babel-register": "^6.6.5",\n    "browser-sync": "^2.8.0",\n    "bs-fullscreen-message": "^1.0.0",\n    "babel-plugin-transform-class-properties": "^6.6.0",\n    "babel-plugin-transform-runtime": "^6.6.0",\n    "babel-preset-es2015": "^6.6.0",\n    "eslint": "^4.3.0",\n    "del": "^3.0.0",\n    "gulp": "^3.9.1",\n    "gulp-babel": "^6.1.2",\n    "gulp-env": "^0.4.0",\n    "gulp-eslint": "^4.0.0",\n    "gulp-imagemin": "^3.0.1",\n    "gulp-inject": "^4.0.0",\n    "gulp-istanbul": "^1.1.1",\n    "gulp-istanbul-enforcer": "^1.0.3",\n    "gulp-load-plugins": "^1.0.0-rc.1",\n    "gulp-mocha": "^4.3.1",\n    "gulp-node-inspector": "^0.2.0",\n    "gulp-plumber": "^1.0.1",\n    "gulp-protractor": "^4.1.0",\n    "gulp-rev": "^8.0.0",\n    "gulp-rev-replace": "^0.4.2",\n    "gulp-sort": "^2.0.0",\n    "gulp-sourcemaps": "^2.6.0",\n    "gulp-util": "^3.0.5",\n    "gulp-watch": "^4.3.5",\n    "gulp-stylint": "^4.0.0",\n    "grunt": "^1.0.1",\n    "grunt-build-control": "^0.7.0",\n    "isparta": "^4.0.0",\n    "nodemon": "^1.3.7",\n    "run-sequence": "^2.1.0",\n    "lazypipe": "^1.0.1",\n    "webpack": "^3.4.1",\n    "webpack-dev-middleware": "^1.5.1",\n    "webpack-stream": "^3.2.0",\n    "extract-text-webpack-plugin": "^3.0.0",\n    "html-webpack-plugin": "^2.16.0",\n    "html-webpack-harddisk-plugin": "~0.1.0",\n    "pug-html-loader": "^1.0.8",\n    "awesome-typescript-loader": "3.2.1",\n    "ng-annotate-loader": "~0.6.1",\n    "babel-loader": "^7.1.1",\n    "css-loader": "^0.28.4",\n    "file-loader": "^0.11.2",\n    "imports-loader": "^0.7.1",\n    "isparta-instrumenter-loader": "^1.0.0",\n    "isparta-loader": "^2.0.0",\n    "istanbul-instrumenter-loader": "^2.0.0",\n    "null-loader": "^0.1.1",\n    "postcss-loader": "^2.0.6",\n    "raw-loader": "^0.5.1",\n    "style-loader": "^0.18.2",\n    "node-sass": "^4.5.3",\n    "sass-loader": "^6.0.6",\n    "karma-webpack": "^2.0.4",\n    "through2": "^2.0.1",\n    "open": "~0.0.4",\n    "istanbul": "1.1.0-alpha.1",\n    "chai": "^4.1.0",\n    "sinon": "^2.4.1",\n    "chai-as-promised": "^7.1.1",\n    "chai-things": "^0.2.0",\n    "karma": "~1.7.0",\n    "karma-firefox-launcher": "^1.0.0",\n    "karma-script-launcher": "^1.0.0",\n    "karma-coverage": "^1.0.0",\n    "karma-chrome-launcher": "^2.0.0",\n    "karma-phantomjs-launcher": "~1.0.0",\n    "karma-spec-reporter": "~0.0.20",\n    "karma-sourcemap-loader": "~0.3.7",\n    "sinon-chai": "^2.8.0",\n    "mocha": "^3.0.2",\n    "jasmine-core": "^2.3.4",\n    "karma-jasmine": "^1.0.2",\n    "jasmine-spec-reporter": "^4.1.1",\n    "phantomjs-prebuilt": "^2.1.4",\n    "proxyquire": "^1.0.1",\n    "strip-ansi": "^4.0.0",\n    "supertest": "^3.0.0"\n  },\n  "engines": {\n    "node": "^6.2.2",\n    "npm": "^3.9.5"\n  },\n  "scripts": {\n    "test": "gulp test",\n    "update-webdriver": "node node_modules/protractor/bin/webdriver-manager update",\n    "start": "node server"\n  },\n  "private": true\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

webpacke.make.json 文件:

\n\n
\'use strict\';\n/*eslint-env node*/\nvar webpack = require(\'webpack\');\nvar autoprefixer = require(\'autoprefixer\');\nvar HtmlWebpackPlugin = require(\'html-webpack-plugin\');\nvar HtmlWebpackHarddiskPlugin = require(\'html-webpack-harddisk-plugin\');\nvar ExtractTextPlugin = require(\'extract-text-webpack-plugin\');\nvar CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;\nvar fs = require(\'fs\');\nvar path = require(\'path\');\nvar ForkCheckerPlugin = require(\'awesome-typescript-loader\').ForkCheckerPlugin;\n\nmodule.exports = function makeWebpackConfig(options) {\n    /**\n     * Environment type\n     * BUILD is for generating minified builds\n     * TEST is for generating test builds\n     */\n    var BUILD = !!options.BUILD;\n    var TEST = !!options.TEST;\n    var E2E = !!options.E2E;\n    var DEV = !!options.DEV;\n\n    /**\n     * Config\n     * Reference: http://webpack.github.io/docs/configuration.html\n     * This is the object where all configuration gets set\n     */\n    var config = {};\n\n    /**\n     * Entry\n     * Reference: http://webpack.github.io/docs/configuration.html#entry\n     * Should be an empty object if it\'s generating a test build\n     * Karma will set this when it\'s a test build\n     */\n    if(TEST) {\n        config.entry = {};\n    } else {\n        config.entry = {\n            app: \'./client/app/app.js\',\n            polyfills: \'./client/polyfills.js\',\n            vendor: [\n                \'angular\',\n                \'angular-animate\',\n                \'angular-aria\',\n                \'angular-cookies\',\n                \'angular-resource\',\n\n                \'angular-sanitize\',\n\n\n                \'angular-ui-router\',\n                \'lodash\'\n            ]\n        };\n    }\n\n    /**\n     * Output\n     * Reference: http://webpack.github.io/docs/configuration.html#output\n     * Should be an empty object if it\'s generating a test build\n     * Karma will handle setting it up for you when it\'s a test build\n     */\n    if(TEST) {\n        config.output = {};\n    } else {\n        config.output = {\n            // Absolute output directory\n            path: BUILD ? path.join(__dirname, \'/dist/client/\') : path.join(__dirname, \'/.tmp/\'),\n\n            // Output path from the view of the page\n            // Uses webpack-dev-server in development\n            publicPath: BUILD || DEV || E2E ? \'/\' : `http://localhost:${8080}/`,\n            //publicPath: BUILD ? \'/\' : \'http://localhost:\' + env.port + \'/\',\n\n            // Filename for entry points\n            // Only adds hash in build mode\n            filename: BUILD ? \'[name].[hash].js\' : \'[name].bundle.js\',\n\n            // Filename for non-entry points\n            // Only adds hash in build mode\n            chunkFilename: BUILD ? \'[name].[hash].js\' : \'[name].bundle.js\'\n        };\n    }\n\n\n\n    if(TEST) {\n        config.resolve = {\n            modulesDirectories: [\n                \'node_modules\'\n            ],\n            extensions: [\'\', \'.js\', \'.ts\']\n        };\n    }\n\n    /**\n     * Devtool\n     * Reference: http://webpack.github.io/docs/configuration.html#devtool\n     * Type of sourcemap to use per build type\n     */\n    if(TEST) {\n        config.devtool = \'inline-source-map\';\n    } else if(BUILD || DEV) {\n        config.devtool = \'source-map\';\n    } else {\n        config.devtool = \'eval\';\n    }\n\n    /**\n     * Loaders\n     * Reference: http://webpack.github.io/docs/configuration.html#module-loaders\n     * List: http://webpack.github.io/docs/list-of-loaders.html\n     * This handles most of the magic responsible for converting modules\n     */\n\n    config.sassLoader = {\n        outputStyle: \'compressed\',\n        precision: 10,\n        sourceComments: false\n    };\n\n    config.babel = {\n        shouldPrintComment(commentContents) {\n            // keep `/*@ngInject*/`\n            return /@ngInject/.test(commentContents);\n        }\n    }\n\n    // Initialize module\n    config.module = {\n        preLoaders: [],\n        loaders: [{\n            // JS LOADER\n            // Reference: https://github.com/babel/babel-loader\n            // Transpile .js files using babel-loader\n            // Compiles ES6 and ES7 into ES5 code\n            test: /\\.js$/,\n            loader: \'babel\',\n            include: [\n                path.resolve(__dirname, \'client/\'),\n                path.resolve(__dirname, \'node_modules/lodash-es/\')\n            ]\n        }, {\n            // TS LOADER\n            // Reference: https://github.com/s-panferov/awesome-typescript-loader\n            // Transpile .ts files using awesome-typescript-loader\n            test: /\\.ts$/,\n            loader: \'awesome-typescript-loader\',\n            query: {\n                tsconfig: path.resolve(__dirname, \'tsconfig.client.json\')\n            },\n            include: [\n                path.resolve(__dirname, \'client/\')\n            ]\n        }, {\n            // ASSET LOADER\n            // Reference: https://github.com/webpack/file-loader\n            // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output\n            // Rename the file using the asset hash\n            // Pass along the updated reference to your code\n            // You can add here any file extension you want to get copied to your output\n            test: /\\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)([\\?]?.*)$/,\n            loader: \'file\'\n        }, {\n            // Pug HTML LOADER\n            // Reference: https://github.com/willyelm/pug-html-loader\n            // Allow loading Pug throw js\n            test: /\\.(jade|pug)$/,\n            loaders: [\'pug-html\']\n        }, {\n\n            // CSS LOADER\n            // Reference: https://github.com/webpack/css-loader\n            // Allow loading css through js\n            //\n            // Reference: https://github.com/postcss/postcss-loader\n            // Postprocess your css with PostCSS plugins\n            test: /\\.css$/,\n            loader: !TEST\n                // Reference: https://github.com/webpack/extract-text-webpack-plugin\n                // Extract css files in production builds\n                //\n                // Reference: https://github.com/webpack/style-loader\n                // Use style-loader in development for hot-loading\n                ? ExtractTextPlugin.extract(\'style\', \'css!postcss\')\n                // Reference: https://github.com/webpack/null-loader\n                // Skip loading css in test mode\n                : \'null\'\n        }, {\n            // SASS LOADER\n            // Reference: https://github.com/jtangelder/sass-loader\n            test: /\\.(scss|sass)$/,\n            loaders: [\'style\', \'css\', \'sass\'],\n            include: [\n                path.resolve(__dirname, \'node_modules/bootstrap-sass/assets/stylesheets/*.scss\'),\n                path.resolve(__dirname, \'client/app/app.scss\')\n            ]\n\n\n        }]\n    };\n\n    config.module.postLoaders = [{\n        test: /\\.js$/,\n        loader: \'ng-annotate?single_quotes\'\n    }];\n\n    // ISPARTA INSTRUMENTER LOADER\n    // Reference: https://github.com/ColCh/isparta-instrumenter-loader\n    // Instrument JS files with Isparta for subsequent code coverage reporting\n    // Skips node_modules and spec files\n    if(TEST) {\n        config.module.preLoaders.push({\n            //delays coverage til after tests are run, fixing transpiled source coverage error\n            test: /\\.js$/,\n            exclude: /(node_modules|spec\\.js|mock\\.js)/,\n            loader: \'isparta-instrumenter\',\n            query: {\n                babel: {\n                    // optional: [\'runtime\', \'es7.classProperties\', \'es7.decorators\']\n                }\n            }\n        });\n    }\n\n\n    /**\n     * PostCSS\n     * Reference: https://github.com/postcss/autoprefixer-core\n     * Add vendor prefixes to your css\n     */\n    config.postcss = [\n        autoprefixer({\n            browsers: [\'last 2 version\']\n        })\n    ];\n\n    /**\n     * Plugins\n     * Reference: http://webpack.github.io/docs/configuration.html#plugins\n     * List: http://webpack.github.io/docs/list-of-plugins.html\n     */\n    config.plugins = [\n        /*\n         * Plugin: ForkCheckerPlugin\n         * Description: Do type checking in a separate process, so webpack don\'t need to wait.\n         *\n         * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse\n         */\n        new ForkCheckerPlugin(),\n\n        // Reference: https://github.com/webpack/extract-text-webpack-plugin\n        // Extract css files\n        // Disabled when in test mode or not in build mode\n        new ExtractTextPlugin(\'[name].[hash].css\', {\n            disable: !BUILD || TEST\n        })\n    ];\n\n    if(!TEST) {\n        config.plugins.push(new CommonsChunkPlugin({\n            name: \'vendor\',\n\n            // filename: "vendor.js"\n            // (Give the chunk a different name)\n\n            minChunks: Infinity\n            // (with more entries, this ensures that no other module\n            //  goes into the vendor chunk)\n        }));\n    }\n\n    // Skip rendering index.html in test mode\n    // Reference: https://github.com/ampedandwired/html-webpack-plugin\n    // Render index.html\n    let htmlConfig = {\n        template: \'client/_index.html\',\n        filename: \'../client/index.html\',\n        alwaysWriteToDisk: true\n    }\n    config.plugins.push(\n      new HtmlWebpackPlugin(htmlConfig),\n      new HtmlWebpackHarddiskPlugin()\n    );\n\n    // Add build specific plugins\n    if(BUILD) {\n        config.plugins.push(\n            // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin\n            // Only emit files when there are no errors\n            new webpack.NoErrorsPlugin(),\n\n            // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin\n            // Dedupe modules in the output\n            new webpack.optimize.DedupePlugin(),\n\n            // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin\n            // Minify all javascript, switch loaders to minimizing mode\n            new webpack.optimize.UglifyJsPlugin({\n                mangle: false,\n                output: {\n                    comments: false\n                },\n                compress: {\n                    warnings: false\n                }\n            }),\n\n            // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin\n            // Define free global variables\n            new webpack.DefinePlugin({\n                \'process.env\': {\n                    NODE_ENV: \'"production"\'\n                }\n            })\n        );\n    }\n\n    if(DEV) {\n        config.plugins.push(\n            // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin\n            // Define free global variables\n            new webpack.DefinePlugin({\n                \'process.env\': {\n                    NODE_ENV: \'"development"\'\n                }\n            })\n        );\n    }\n\n    config.cache = DEV;\n\n    if(TEST) {\n        config.stats = {\n            colors: true,\n            reasons: true\n        };\n        config.debug = false;\n    }\n\n    /**\n     * Dev server configuration\n     * Reference: http://webpack.github.io/docs/configuration.html#devserver\n     * Reference: http://webpack.github.io/docs/webpack-dev-server.html\n     */\n    config.devServer = {\n        contentBase: \'./client/\',\n        stats: {\n            modules: false,\n            cached: false,\n            colors: true,\n            chunk: false\n        }\n    };\n\n    config.node = {\n        global: \'window\',\n        process: true,\n        crypto: \'empty\',\n        clearImmediate: false,\n        setImmediate: false\n    };\n\n    return config;\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试将 Webpack 降级到版本 1.15.0,删除该node_modules文件夹并再次安装,但仍然遇到相同的错误。

\n\n

出了什么问题?

\n\n

更新:

\n\n

以防万一它有帮助,当我这样做时npm install,Webpack 模块会像这样显示UNMET PEER DEPENDENCY webpack@3.4.1

\n\n

将 Awesome-typescript-loader 降级到 2.2.4 时出现以下错误:

\n\n
WebpackOptionsValidationError(webpackOptionsValidationErrors);\n        ^\nWebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.\n - configuration has an unknown property \'postcss\'. These properties are valid:\n   object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }\n   For typos: please correct them.\n   For loader options: webpack 2 no longer allows custom properties in configuration.\n     Loaders should be updated to allow passing options via loader options in module.rules.\n     Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n     plugins: [\n       new webpack.LoaderOptionsPlugin({\n         // test: /\\.xxx$/, // may apply this only for some modules\n         options: {\n           postcss: ...\n         }\n       })\n     ]\n - configuration.module has an unknown property \'postLoaders\'. These properties are valid:\n   object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, loaders?, noParse?, rules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }\n   Options affecting the normal modules (`NormalModuleFactory`).\n - configuration.node should be one of these:\n   false | object { Buffer?, __dirname?, __filename?, console?, global?, process?, ... }\n   Include polyfills or mocks for various node stuff.\n   Details:\n    * configuration.node should be false\n    * configuration.node.global should be a boolean.\n
Run Code Online (Sandbox Code Playgroud)\n\n

更新2:

\n\n

看来降级 webpack@2.1.0-beta.22 解决了我的问题。但现在,我收到另一个错误:

\n\n
/home/nsanz/Documentos/git/tachology/node_modules/extract-text-webpack-plugin/node_modules/async/dist/async.js:1003\n        iteratee(coll[index], index, onlyOnce(iteratorCallback));\n        ^\nTypeError: chunk.sortModules is not a function\n
Run Code Online (Sandbox Code Playgroud)\n\n

更新3:

\n\n

安装 extract-text-webpack-plugin@2.1.2 后,我收到此新错误:

\n\n
/home/nsanz/Documentos/git/tachology/node_modules/extract-text-webpack-plugin/index.js:187\n        throw new Error("Breaking change: extract now only takes a single argument. Either an options " +\n        ^\nError: Breaking change: extract now only takes a single argument. Either an options object *or* the loader(s).\nExample: i

Jos*_*cia 3

在您的 devDependencies 中,尝试降级:

awesome-typescript-loader": "3.2.1"
Run Code Online (Sandbox Code Playgroud)

对此:

awesome-typescript-loader": "2.2.4"
Run Code Online (Sandbox Code Playgroud)

如果仍然不行,我们会寻找其他解决方案。


编辑

上次问题更新后,这是我的建议。删除以下行webpack.make.json

 config.plugins = [
        /*...*/
        new ForkCheckerPlugin(), // <-- Delete this line
Run Code Online (Sandbox Code Playgroud)

这样做的原因是,fork 似乎是 Webpack >= 3.0.0 内置的


编辑2

看来 Webpack 3.4.1 给你带来了麻烦,因为你依赖于一些旧的依赖项。请执行下列操作:

npm uninstall webpack --save-dev
Run Code Online (Sandbox Code Playgroud)

然后:

npm install webpack@2.1.0-beta.22 --save-dev
Run Code Online (Sandbox Code Playgroud)

希望这现在能起作用!如果还是不行,尝试重新合并该new ForkCheckerPlugin()语句(这次使用webpack 2.1.0)


编辑3

现在似乎可以使用webpack 2.1.0-beta.22,但您遇到了另一个错误。

发生此错误的原因extract-text-webpack-plugin是主要版本不同webpack(3.xx 与 2.xx)。做这个:

npm uninstall --save-dev extract-text-webpack-plugin
Run Code Online (Sandbox Code Playgroud)

那么这个:

npm install --save-dev extract-text-webpack-plugin@2.1.2
Run Code Online (Sandbox Code Playgroud)

编辑4

这个新错误更容易解决。它在您的错误日志中进行了解释。在你的webpack.make.js更改行中:

ExtractTextPlugin.extract('style', 'css!postcss')
Run Code Online (Sandbox Code Playgroud)

到:

ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })
Run Code Online (Sandbox Code Playgroud)

编辑5

事情变得有趣了。我建议更改此设置(在 内部webpack.make.js):

}, {
    // Pug HTML LOADER
    // Reference: https://github.com/willyelm/pug-html-loader
    // Allow loading Pug throw js
    test: /\.(jade|pug)$/,
    loaders: ['pug-html']
}, {
Run Code Online (Sandbox Code Playgroud)

对此:

}, {
    // Pug HTML LOADER
    // Reference: https://github.com/willyelm/pug-html-loader
    // Allow loading Pug throw js
    test: /\.(jade|pug)$/,
    loaders: ['pug-html-loader']
}, {
Run Code Online (Sandbox Code Playgroud)