Webpack:ES6 语法给出了 Module build failed: SyntaxError: Unexpected token

Posted

技术标签:

【中文标题】Webpack:ES6 语法给出了 Module build failed: SyntaxError: Unexpected token【英文标题】:Webpack: ES6 syntax gives Module build failed: SyntaxError: Unexpected token 【发布时间】:2017-05-14 18:23:11 【问题描述】:

我正在尝试使用固定数据表的示例,并将其与 webpack 捆绑在一起。

我正在使用 babel-loader,否则我的代码会毫无问题地捆绑在一起。

运行 webpack 指向一个错误,据我所知这是 ES6 语法的一部分(不是 ES5)... ... ,例如这里:

render() var sortDir, children, ...props = this.props;

...props 特别是。

这是我的 webpack 配置:

"use strict";

var webpack = require("webpack");

module.exports = 
    entry: 
        app: './app.js',
        vendor: ["fixed-data-table","react","react-dom","jquery", "bootstrap", "vis", "chart.js"],
    ,
    output:  path: "./", filename: 'bundle.js' ,

    plugins: [
        new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js"),
        new webpack.ProvidePlugin(
            $: "jquery",
            jQuery: "jquery"
        )
    ],

    module: 
        loaders: [
            
                test: /.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: 
                    presets: ['es2015', 'react']
                
            
        ]
    ,
;

我正在使用 es2015 并作为预设做出反应并使用 babel-loader 加载。应该理解和处理 ES6 语法,怎么会抛出语法错误?

这是我的 Package.json。我可能需要升级某些版本吗?


  "name": "test",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": 
    "test": "echo \"Error: no test specified\" && exit 1"
  ,
  "author": "",
  "license": "ISC",
  "devDependencies": 
    "babel-core": "^6.3.17",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-runtime": "^6.3.19",
    "webpack": "^1.12.9"
  ,
  "dependencies": 
    "bootstrap": "^3.3.7",
    "chart.js": "^2.4.0",
    "fixed-data-table": "^0.6.0",
    "jquery": "^3.1.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3",
    "vis": "^4.17.0"
  ,
  "description": ""

【问题讨论】:

这不是 ES7 Rest property 的特性吗? 真的吗? Facebook在这里有他们的例子;是基于 ES7 的吗? github.com/facebook/fixed-data-table/blob/master/examples/… 它甚至不是 ES7 或 ES8,它仍然是一个实验性提案。 可能想知道为什么 Facebook 开发人员选择使用它。不过谢谢。我解决了:) 【参考方案1】:

我需要 babel 预设向后兼容 ES7。

解决者:

npm install babel-preset-stage-0 --save-dev

接着在上面的 webpack 配置中添加预设:

presets: ['es2015', 'react', 'stage-0']

【讨论】:

以上是关于Webpack:ES6 语法给出了 Module build failed: SyntaxError: Unexpected token的主要内容,如果未能解决你的问题,请参考以下文章

webpack原理:ES6 module在Webpack中如何Tree-shaking构建

ES6入门十二:Module(模块化)

在webpack用插件uglifyjs-webpack-plugin压缩ES6语法

webpack如何编译ES6打包

webpack 支持的模块方法

带有 es6 导入的 Module.exports 用于 typescript 中的 webpack.config.ts