【问题标题】:Simple Webpack + React + ES6 + babel example doesn't work. Unexpected token error简单的 Webpack + React + ES6 + babel 示例不起作用。意外的令牌错误
【发布时间】:2016-11-23 12:52:33
【问题描述】:

在运行 webpack 编译 jsx 语法时出现解析错误。如果有人能指出我的错误,将不胜感激。我看到一个类似的问题问Webpack, React, JSX, Babel - Unexpected token <,但建议的解决方案对我不起作用。

这是我的配置文件的样子:

package.json

 {
  "name": "dropdowns",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "react": "^15.2.1",
    "react-dom": "^15.2.1",
    "babel-core": "^6.11.4",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1"
  },
  "devDependencies": {
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1"
  },
  "author": "",
  "license": "ISC"
}

我的 webpack.config.js 文件是

    module.exports = {
    context: __dirname + "/app",
    entry: "./main.js",

    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }


};

在本地应用程序文件夹中,我有 main.js 和 IdMappingOptions.js,如下所示:

// in IdMappingOptions.js
import React from 'react';
class IdMappingOptions extends React.Component {
    render () {
        return <span>Hello!</span>
    }
}
export default IdMappingOptions;
// in main.js
    import React from 'react';
import { render } from 'react-dom';
import IdMappingOptions from './IdMappingOptions';

render(
    <IdMappingOptions/>, document.body
);

运行 node_modules/.bin/webpack 时,我得到以下错误跟踪:

Hash: 396f0bfb9d565b6f60f0
Version: webpack 1.13.1
Time: 37ms
  [0] ./main.js 0 bytes [built] [failed]
ERROR in ./main.js
Module parse failed: /scratch/parallel/repository/dropdowns/app/main.js    Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
 SyntaxError: Unexpected token (6:4)
 at Parser.pp.raise (/scratch/parallel/repository/dropdowns/node_module/acorn/dist/acorn.js:923:13)

编辑: 根据下面的 cmets 修复了测试模式并在 webpack.config.js 中添加了 babel-core。这是我的

【问题讨论】:

  • 你能分享你的应用程序文件夹结构吗?

标签: javascript reactjs webpack babeljs


【解决方案1】:

您的测试似乎有问题:

test: "/.js$"

试试这个:

test: /\.js$/

【讨论】:

    【解决方案2】:

    你需要 babel-core 才能在你的项目中使用 babel。 (https://github.com/babel/babel-loader#installation)。

    npm install --save-dev babel-core
    

    【讨论】:

      猜你喜欢
      • 2016-07-10
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 1970-01-01
      • 2019-09-16
      • 2017-02-01
      相关资源
      最近更新 更多