Search code examples
webpackbabeljswebpackerreact-on-rails

` Unexpected token 'const'` webpack and babel not transpiling code in WEBPACK VAR INJECTION section


We have a Rails 5 project that uses react_on_rails, and thus webpack (via the webpacker gem) and babel. We are running testing using capybara webkit and we are getting this error when using the webkit_debug javascript driver.

http://localhost:3001/packs-test/kronos-bundle-b399226ff352220cce47.js|80403|SyntaxError: Unexpected token 'const'

Both our production and test webpacks have const variables in the WEBPACK VAR INJECTION section of the pack, but I think modern browsers are ok with let and const now so we haven't noticed.

Our .babelrc looks like:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "node": "current",
          "browsers": ["last 2 versions", "safari >= 7"],
          "uglify": true
        },
        "useBuiltIns": true
      }
    ],
    "es2015",
    "react",
    "stage-1"
  ],
  "plugins": [
    "transform-flow-strip-types",
    "syntax-dynamic-import",
    "transform-object-rest-spread",
    [
      "transform-class-properties",
      {
        "spec": true
      }
    ]
  ]
}

Any ideas?


Solution

  • Turns out there were two issues here that were biting me. First, there were two modules we were using that we not being transformed, so I had to add explict includes for them in webpack to pass them to babel-loader:

      {
        test: /\.jsx?$/,
        include: [path.resolve(__dirname, '../../node_modules/')],
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: 'tmp/cache/webpacker/babel-loader'
            }
          }
        ]
      }
    

    Once i did that, I found that both webpack and poltergeist needed still more conversion to get to generic ES5. To do this, we needed to add the es5-shim to our entry point. I chose to do this by modifying our /config/webpack/test.js file like this:

    const environment = require('./environment');
    
    const config = environment.toWebpackConfig();
    
    const entry = config.entry['kronos-bundle'];
    
    config.entry = {
      'kronos-bundle': ['es5-shim/es5-shim', 'babel-polyfill', entry]
    };
    
    module.exports = config;
    

    Not sure if there is a better way to load that ployfill but this now works.