无效的配置对象。Webpack已使用与API模式不匹配的配置对象进行初始化。

181

我有一个简单的helloworld react应用,是从在线课程中创建的,但是我得到了以下错误:

无效的配置对象。Webpack已经初始化使用一个与API模式不匹配的配置对象。 - 配置具有未知属性“postcss”。这些属性有效: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?} 对于拼写错误:请纠正它们。
对于加载程序选项:webpack 2不再允许在配置中使用自定义属性。 应该更新装载机以允许通过module.rules中的loader选项传递选项。 直到装载程序更新为止,可以使用LoaderOptionsPlugin将这些选项传递给装载程序: plugins: [ new webpack.LoaderOptionsPlugin({ // test: /.xxx$/, // may apply this only for some modules options: { postcss:... } }) ] - 配置.resolve具有未知属性'root'。这些属性有效:object {alias?,aliasFields? cachePredicate?,descriptionFiles?,enforceExtension? enforceModuleExtension?,extensions?,fileSystem?,mainFields? mainFiles?,moduleExtensions?,modules?,plugins? resolver?,symlinks?,unsafeCache?,useSyncFileSystemCalls?} - 配置.resolve.extensions [0]不应为空。

我的webpack文件为:

// work with all paths in a cross-platform manner
const path = require('path');

// plugins covered below
const { ProvidePlugin } = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

// configure source and distribution folder paths
const srcFolder = 'src';
const distFolder = 'dist';

// merge the common configuration with the environment specific configuration
module.exports = {

    // entry point for application
    entry: {
        'app': path.join(__dirname, srcFolder, 'ts', 'app.tsx')
    },

    // allows us to require modules using
    // import { someExport } from './my-module';
    // instead of
    // import { someExport } from './my-module.ts';
    // with the extensions in the list, the extension can be omitted from the 
    // import from path
    resolve: {
        // order matters, resolves left to right
        extensions: ['', '.js', '.ts', '.tsx', '.json'],
        // root is an absolute path to the folder containing our application 
        // modules
        root: path.join(__dirname, srcFolder, 'ts')
    },

    module: {
        loaders: [
            // process all TypeScript files (ts and tsx) through the TypeScript 
            // preprocessor
            { test: /\.tsx?$/,loader: 'ts-loader' },
            // processes JSON files, useful for config files and mock data
            { test: /\.json$/, loader: 'json' },
            // transpiles global SCSS stylesheets
            // loader order is executed right to left
            {
                test: /\.scss$/,
                exclude: [path.join(__dirname, srcFolder, 'ts')],
                loaders: ['style', 'css', 'postcss', 'sass']
            },
            // process Bootstrap SCSS files
            {
                test: /\.scss$/,
                exclude: [path.join(__dirname, srcFolder, 'scss')],
                loaders: ['raw', 'sass']
            }
        ]
    },

    // configuration for the postcss loader which modifies CSS after
    // processing
    // autoprefixer plugin for postcss adds vendor specific prefixing for
    // non-standard or experimental css properties
    postcss: [ require('autoprefixer') ],

    plugins: [
        // provides Promise and fetch API for browsers which do not support
        // them
        new ProvidePlugin({
            'Promise': 'es6-promise',
            'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
        }),
        // copies image files directly when they are changed
        new CopyWebpackPlugin([{
            from: path.join(srcFolder, 'images'),
            to: path.join('..', 'images')
        }]),
        // copies the index.html file, and injects a reference to the output JS 
        // file, app.js
        new HtmlWebpackPlugin({
            template: path.join(__dirname, srcFolder, 'index.html'),
            filename:  path.join('..', 'index.html'),
            inject: 'body',
        })
    ],

    // output file settings
    // path points to web server content folder where the web server will serve 
    // the files from file name is the name of the files, where [name] is the 
    // name of each entry point 
    output: {
        path: path.join(__dirname, distFolder, 'js'),
        filename: '[name].js',
        publicPath: '/js'
    },

    // use full source maps
    // this specific setting value is required to set breakpoints in they
    // TypeScript source in the web browser for development other source map
    devtool: 'source-map',

    // use the webpack dev server to serve up the web application
    devServer: {
        // files are served from this folder
        contentBase: 'dist',
        // support HTML5 History API for react router
        historyApiFallback: true,
        // listen to port 5000, change this to another port if another server 
        // is already listening on this port
        port: 5000,
        // proxy requests to the JSON server REST service
        proxy: {
            '/widgets': {
                // server to proxy
                target: 'http://0.0.0.0:3010'
            }
        }
    }

};

在我的情况下,我在我的AureliaJs应用程序中运行了一个错误的命令来运行我的单元测试,例如:"au run test"而不是"au test",所以要小心。希望能帮助到别人,节省时间。 - undefined
35个回答

62

只需在 "webpack.config.js" 中将 "loaders" 更改为 "rules"

因为 Webpack 1 中使用了 "loaders",而在 Webpack2 中使用了 "rules"。 你可以看到有区别


如何在Vue.js中实现这个? - AnonymousUser

44

随着每个重大版本的发布,Webpack的配置文件也在不断变化。现在要回答的问题是:

为什么我会收到这个错误信息?

Invalid configuration object. Webpack has been initialised using a 
configuration object that does not match the API schema

问题是因为配置文件与使用的webpack版本不匹配。

被接受的答案并没有说明这一点,其他答案则暗示了这一点但没有明确说明npm install webpack@2.1.0-beta.22只需在"webpack.config.js"中将"loaders"改成"rules"此答案。 因此,我决定提供我的答案。

卸载和重新安装webpack,或者使用全局版本的webpack都无法解决这个问题。对于正在使用的配置文件使用正确的webpack版本才是重要的。

如果在使用全局版本时解决了此问题,则很可能意味着您的全局版本已经“过时”,您正在使用的webpack.config.js文件格式也是“旧的”,因此它们“匹配”,然后奇迹般地开始工作。虽然我希望万事顺利,但我希望读者知道为什么会奏效。

每当您获得一个希望解决问题的webpack配置时...请问一下它是用于哪个版本的webpack。

有许多学习webpack的好资源。其中一些是:

  • 官方Webpack网站描述webpack配置,目前版本为4.x。虽然这是查找webpack应该如何工作的绝佳资源,但它并不总是最好的,因为它没有很好地学习webpack中2或3个选项如何共同解决问题。但它是最好的开始之处,因为它强制您知道使用的webpack版本。:-)
  • Webpack(v3?)示例 - 采用逐步学习webpack的方法,选择一个问题,然后展示如何在webpack中解决它。我喜欢这种方法。不幸的是,它没有教授webpack 4,但仍然是好的。

  • 从头开始设置Webpack4、Babel和React,重温 - 这是特定于React的,但如果您想学习创建单页React应用程序所需的许多内容,那么它就非常好。

  • Webpack(v3)-令人困惑的部分 - 很好,涵盖了很多内容。它的出版日期是2016年4月10日,没有涵盖webpack4,但许多教学点都是有效的或者有用的。

还有更多学习以示例为基础的webpack4的好资源,请在评论中添加如果您知道其他资源。希望未来的webpack文章能声明所使用的/解释的版本。


1
我希望我能够给这个答案更多的赞。 - socjopata
1
好消息是,上面的链接包含了创建自己的webpack文件教程,适用于4.x以上版本并使用cli。这使得更新您的webpack和解决问题变得非常容易。 - Saurabh Gupta
1
好的一点是,上面的链接中包含了使用命令行界面创建适用于4.x版本以上的自定义webpack文件的教程。这使得更新webpack并解决问题变得非常容易。 - undefined

40

我通过从我的resolve数组中删除空字符串来解决了这个问题。请参阅webpack网站上的resolve文档

//Doesn't work
module.exports = {
  resolve: {
    extensions: ['', '.js', '.jsx']
  }
  ...
}; 

//Works!
module.exports = {
  resolve: {
    extensions: ['.js', '.jsx']
  }
  ...
};

2
为什么不再工作了?在旧版本的webpack中,我总是看到extensions数组值的第一个索引处为空字符串。 - guilima

34

我不确定是什么原因导致了这个问题,但我用以下方法解决了它。
重新安装整个项目,但记住必须全局安装webpack-dev-server。
我遇到了一些服务器错误,如找不到webpack,所以我使用链接命令链接了Webpack。
在输出中解决了一些绝对路径问题。

在devServer中添加object: inline: false

webpack.config.js

module.exports = {
    entry: "./src/js/main.js",
    output: {
        path:__dirname+ '/dist/',
        filename: "bundle.js",
        publicPath: '/'
    },
    devServer: {
        inline: false,
        contentBase: "./dist",
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude:/(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }

};
{"package.json"}
{
  "name": "react-flux-architecture-es6",
  "version": "1.0.0",
  "description": "egghead",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/cichy/react-flux-architecture-es6.git"
  },
  "keywords": [
    "React",
    "flux"
  ],
  "author": "Jarosław Cichoń",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/cichy/react-flux-architecture-es6/issues"
  },
  "homepage": "https://github.com/cichy/react-flux-architecture-es6#readme",
  "dependencies": {
    "flux": "^3.1.2",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^3.0.2"
  },
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0"
  }
}

1
只需删除本地安装的webpack-dev-server并全局安装即可解决我的问题。 - Sam
54
我认为 loaders 选项已被替换为 rules,请参见https://webpack.js.org/concepts/loaders/。 - Olotin Temitope

30

请尝试以下步骤:

npm uninstall webpack --save-dev

随后是

npm install webpack@2.1.0-beta.22 --save-dev

那你应该能够再次成功地使用 gulp 了。这个方法解决了我的问题。


20

当您的AngularJS版本存在冲突时,通常会出现此错误。因此,webpack无法启动应用程序。您只需删除webpack并重新安装即可轻松解决此问题。

npm uninstall webpack --save-dev
npm install webpack --save-dev
重新启动您的应用程序,一切都会正常。
我希望能够帮助到某个人。干杯!

我在将一个项目升级到新版 Angular 时遇到了这个问题。只需要重新安装 Webpack 就可以解决!谢谢! - Iván Pérez

17

如果Webpack 3仍然存在这个问题怎么办? - mjwrazor
你的链接已经失效。 - drweird

17

对于像我这样最近开始学习的人来说:关键字loaders已被替换rules,尽管它仍代表着加载器的概念。因此,我的 React 应用程序的 webpack.config.js 如下:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module : {
    rules : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  }
};

module.exports = config;

10

使用规则来替代加载器实现。

module : {
  rules : [
    {
      test : /\.jsx?/,
      include : APP_DIR,
      loader : 'babel-loader'
    }
  ]
}

10

使用 npm i -S webpack@latest 安装 "webpack": "^5.41.1" 可以解决这个问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接