缺少类属性转换反应

时间:2018-06-06 16:40:02

标签: javascript reactjs webpack babel

我知道有很多问题/答案,但似乎没有一个能帮我解决问题。我不明白我的设置有什么问题: enter image description here

这是我的webpack.config.js:

var path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'ftux-components.js',
    library: "shared-components",
    libraryTarget: "umd"
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules)/,
        loader: 'babel',
        query: {
          presets: ['env', 'react', 'es2015', 'stage-0'],
          plugins: ["transform-class-properties"]
        }
      },
      {
        test: /\.s?css$/,
        loaders: ['style', 'css', 'sass', 'postcss-loader']
      },
      {
        test: /\.(ttf|eot|svg|jpg|png|woff)$/,
        loader: 'url-loader'
      }
    ],
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  },
  externals: {
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    },
    'react-dom': {
      root: 'ReactDOM',
      commonjs2: 'react-dom',
      commonjs: 'react-dom',
      amd: 'react-dom'
    },
    'styled-components': {
      commonjs: 'styled-components',
      commonjs2: 'styled-components',
      amd: 'styled-components'
    }
  }
};

这是我的babelrc:

{
    "presets": ["env", "react", "es2015", "stage-0"],
    "plugins": [
        "transform-class-properties",
        "transform-object-rest-spread",
        "transform-react-jsx"
    ]
}

我尝试重新排序预设,添加适当的插件(transform-class-properties),删除重新安装node_modules但似乎没有任何帮助。我的npm和节点是最新的,也尝试使用this来确保我包含了我需要的所有babel。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

在你的babel加载器中,即使你已经安装了它,你也不会包含类属性的插件。尝试让你的装载机看起来像这样:

     {
        test: /\.jsx?$/,
        exclude: /(node_modules)/,
        loader: 'babel',
        query: {
          presets: ['env', 'react', 'es2015', 'stage-0'],
          plugins: ["transform-class-properties"]
        }
      },

答案 1 :(得分:1)

好吧我明白了。我需要在webpack.config.js中的模块对象的rules数组中包含预设和插件:

rules: [
    {
    test: /\.js$/,
    include: path.resolve(__dirname, 'src'),
    exclude: /(node_modules|bower_components|build)/,
    loader: 'babel-loader',
    query: {
        presets: ['env', 'react', 'es2015', 'stage-0'],
        plugins: ["transform-class-properties"]
    }
    }
]

找到答案here