why do I have to put babel-presets inside .babelrc and webpack.config.js?

前端 未结 2 642
半阙折子戏
半阙折子戏 2021-02-01 16:38

Ok. I am bootstraping a simple app. I am using flow.js. Presets that I use are babel-preset-2015, babel-preset-react and babel-preset-stage-0. I have to put same presets inside

相关标签:
2条回答
  • 2021-02-01 17:15

    If I put presets inside webpack.config I should be able to delete .babelrc or vice verse.

    No, this is not the case. Specifying the presets in the webpack config will only affect webpack, everything else that uses babel (e.g. babel-node, babel-register, etc.) will not care about your webpack config and therefore doesn't see them.

    The other way around does work. So you can remove the webpack presets options if you have a .babelrc, because babel-loader uses babel under the hood, which obviously respects the .babelrc.

    If I for example remove them from webpack.config I get an error React is not defined.

    The problem is that your .babelrc configuration is different from the configuration in the webpack config. The culprit is "passPerPreset": true. With this option every preset is applied individually without considering the others. And for this the order matters. From the babel docs - Plugin/Preset Ordering:

    Preset ordering is reversed (last to first).

    This means they will be applied in the following order: stage-0, react, es2015. As they are applied individually, react will transform the JSX to React.createElement, because React is in scope, and es2015 will transform just the import to _react2.default, therefore React is no longer defined. The entire diff between the two bundles is this:

    @@ -9470,7 +9470,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
    // var React = require('react')
    // var ReactDOM = require('react-dom')
    
    -_reactDom2.default.render(React.createElement(
    +_reactDom2.default.render(_react2.default.createElement(
      'h1',
      null,
      'Juhuuuu'
    

    There isn't much information about passPerPreset, but it was labelled experimental in the Release notes and you should probably avoid it altogether.

    Although it would work if you put the react preset first in the list, I'd recommend to remove passPerPreset option, unless you have a very specific reason to use it.

    {
      "presets": [
        "es2015",
        "react",
        "stage-0"
      ]
    }
    
    0 讨论(0)
  • 2021-02-01 17:18

    Try and modify your Loaders like

    module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: [/node_modules/],
            use: [{
              loader: 'babel-loader',
              options: { presets: ['react','es2015', 'stage-0'] }
            }],
          }
        ]
      }
    
    0 讨论(0)
提交回复
热议问题