更新了npm依赖关系,现在将无法编译

时间:2019-12-06 13:21:52

标签: reactjs npm webpack react-redux

我将几年前所做的react-redux测试项目更新为所有最新版本的npm依赖项,但是现在我无法对其进行编译。运行npm run dev时收到错误消息:

ERROR in ./js/client.js 10:16
Module parse failed: Unexpected token (10:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders                                                                         
| const app = document.getElementById('app')
| 
> ReactDOM.render(<Provider store={store}>
|   <Layout />
| </Provider>, app);
ℹ 「wdm」: Failed to compile.

我的webpack.config.js看起来像

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./js/client.js",
  module: {
  },
  output: {
    path: __dirname + "/src/",
    filename: "client.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
  devServer: {
    host: "0.0.0.0",
  }
};

我知道这在几年前就行了,但是我也知道JavaScript世界发展很快。我用邮件搜索了一下,但是我发现的所有匹配都与.jsx文件扩展名有关,而我却没有任何匹配项。

1 个答案:

答案 0 :(得分:2)

我不确定您所使用的软件包的先前版本,但是webpack已朝着将loaders与核心解耦的方向发展。因此,您必须单独安装它们。

您将加载程序添加到module文件的webpack.config.js部分中。更多信息和此处的教程:https://webpack.js.org/concepts/#loaders

babel-loader如今是.js和/或.jsx中最受欢迎的。 https://www.npmjs.com/package/babel-loader/v/8.0.0-beta.1

试一下,下面是使用yarn add babel-loader @babel/core @babel/preset-react -D安装后的外观,它将把这些依赖关系添加到package.json的dev部分中。

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./js/client.js",
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        }
      },
    ],
  },
  output: {
    path: __dirname + "/src/",
    filename: "client.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
  devServer: {
    host: "0.0.0.0",
  }
};

这几步之后,您很可能会出现其他错误,但是如果您能及时更新,很高兴能帮助您启动并运行webpack!

编辑

您还需要在项目根目录中使用babel.config.js(或类似的模式),在此处详细了解有关babel的信息:https://babeljs.io/

这是一个例子:

module.exports = (api) => {
  api.cache(true)

  const presets = [
    '@babel/preset-env', '@babel/preset-react'
  ]
  // add any more presets you need above as shown

  const plugins = [
    // add any plugins you need here
  ]
  return {
    presets,
    plugins
  }
}