0

我们有一个使用 react_on_rails 的 Rails 5 项目,因此使用了 webpack(通过 webpacker gem)和 babel。我们正在使用 capybara webkit 运行测试,并且在使用 webkit_debug javascript 驱动程序时出现此错误。

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

我们的生产和测试 webpackconst在包的部分都有变量WEBPACK VAR INJECTION,但我认为现代浏览器可以接受letconst现在我们没有注意到。

我们的.babelrc样子:

{
  "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
      }
    ]
  ]
}

有任何想法吗?

4

1 回答 1

0

原来这里有两个问题困扰着我。首先,我们使用的两个模块没有被转换,所以我必须在 webpack 中为它们添加显式包含以将它们传递给 babel-loader:

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

一旦我这样做了,我发现 webpack 和 poltergeist 都需要更多的转换才能得到通用的 ES5。为此,我们需要将 es5-shim 添加到我们的入口点。我选择通过像这样修改我们的/config/webpack/test.js文件来做到这一点:

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;

不确定是否有更好的方法来加载该 ployfill,但现在可以使用。

于 2018-01-19T14:27:14.440 回答