【问题标题】:Getting object spread to work with webpack.config and babelrc files让对象传播以使用 webpack.config 和 babelrc 文件
【发布时间】:2018-07-15 07:18:22
【问题描述】:

我正在尝试让对象扩展运算符与我的反应项目一起使用。它出现了一个语法错误:

我已经尝试使用babel-plugin-transform-object-rest-spread,如 babel docs 所述。

经过一番研究,我还尝试了babel 的 GitHub 问题中描述的配置:

请在下面查看我的 .babelrc 文件:

{
    "presets": ["es2015"],
    "plugins": ["transform-object-rest-spread"],
    "sourceMaps": true,
    "retainLines": true
}

还有我的 webpack.config 文件如下:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'public', 'js'),
    publicPath: '/'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, 'src'),
        loader: 'babel-loader',
        options: {
          presets: ['react', 'es2015']
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test:/\.scss$/,
        use: [{
                loader: 'style-loader'
            }, {
                loader: 'css-loader'
                }, {
                loader: 'sass-loader', options: {
                    sourceMap: true
                }
            }]
      },
      {
        test: /.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'url-loader'
      }
    ]
  },
  devServer: {
   historyApiFallback: true,
   contentBase: path.join(__dirname, 'public'),
   publicPath: '/js/',
   port: 3000
 }
};

我使用扩展运算符的代码是:

import * as types from '../types/types'; 

const initialState ={
    mesage:''
}

export default function doodlesReducer (state = initialState, action) {
    switch(action.type) {
        case 'SET_MESSAGE' :
        return {…state, message: action.payload.message}
        default :
        return state
        }
}

谁能帮我找出正确的配置来使用对象扩展运算符?

【问题讨论】:

  • 你的代码是什么样子的?
  • ... 不是运算符,对象 spread/rest 不是 ES2015 的一部分,这就是为什么你需要一个额外的插件来转换它。

标签: reactjs webpack babeljs ecmascript-next


【解决方案1】:

您在.babelrcwebpack.config 中都列出了您的预设,请尝试将其全部移至其中一个,即仅.babelrc

{
    "presets": ["es2015", "react"],
    "plugins": ["transform-object-rest-spread"]
}

编辑:另外,不要使用现已弃用的es2015 预设,而是安装env 预设npm install --save-dev babel-preset-env 并在.babelrc 中将es2015 替换为env。 p>

编辑 2: 您正在使用的 使用了一些不受支持的字符编码,您必须从弄乱编码的地方复制粘贴它,将其替换为 ... .

【讨论】:

  • 恐怕仍然遇到同样的错误,不过感谢您的想法,我对 babel、webpack 和 react 还是很陌生。
  • 而不是使用 ES2015 安装 babel-preset-env 并在 babelrc 中将其添加为“env”
  • 未捕获错误:模块解析失败:意外令牌 (12:4) 您可能需要适当的加载程序来处理此文件类型。 | | ReactDOM.render( | | |
  • @R.Thompson 编辑 2 是您最初的问题所在,将其更改回对您有用的内容,并在编辑 2 中进行建议的更改,然后尝试在之后添加新的环境预设你得到那个工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-13
  • 2015-05-22
  • 2020-06-02
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多