使用带有babel和webpack的javascript生成器

时间:2017-08-31 13:01:02

标签: javascript generator babel uglifyjs polyfills

我尝试测试以下js代码:

function* foo(x) {
    var y = 2 * (yield (x + 1));
    var z = yield (y / 3);
    return (x + y + z);
}

const it = foo( 5 );

// note: not sending anything into `next()` here
console.log( it.next() );       // { value:6, done:false }
console.log( it.next( 12 ) );   // { value:8, done:false }
console.log( it.next( 13 ) );   // { value:42, done:true }

但我得到了:

  

模块构建失败:SyntaxError:意外的令牌

我遵循了本指南link,但我可以让我的webpack使用生成器构建我的代码。这是我的webpack:

config.module.rules.push({
  test: /\.(js|jsx)$/,
  exclude: /node_modules\/(?!geniuz)/,
  use: [{
    loader: 'babel-loader',
    query: {
      cacheDirectory: true,
      plugins: [
        'babel-plugin-transform-class-properties',
        'babel-plugin-syntax-dynamic-import',
        [
          'babel-plugin-transform-runtime',
          {
            helpers: true,
            polyfill: false, // we polyfill needed features in src/normalize.js
            regenerator: true,
          },
        ],
        [
          'babel-plugin-transform-object-rest-spread',
          {
            useBuiltIns: true // we polyfill Object.assign in src/normalize.js
          },
        ],
        ['transform-regenerator'],
      ],
      presets: [
        'babel-preset-react',
        ['babel-preset-env', {
          modules: false,
          targets: {
            ie9: true,
          },
          uglify: true,
        }],
      ]
    },
  }],
})

我也尝试过:

['transform-regenerator', {
          generators: true,
        }],

2 个答案:

答案 0 :(得分:0)

这对我有用:

module: { 
        rules: [   
          {     
            test:/\.js$/,       
            exclude: path.resolve(__dirname,'node_modules'), 
            loader: 'babel-loader', 
            query: {presets: ['es2015']}  
          }  
        ]         
    } 

答案 1 :(得分:0)

必须将@babel/transform-runtime插件添加到babel.config.js文件,如下所示:

presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
  '@babel/transform-runtime',
  '@babel/plugin-syntax-dynamic-import',
  '@loadable/babel-plugin',
],