Babel loader无法识别es2015代码

时间:2016-03-14 09:09:51

标签: javascript reactjs webpack babeljs

更新

我将示例项目上传到github:https://github.com/guocheng/debug-webpack

在此示例项目中,我有两个相同的index.js文件。一个在项目根目录下,另一个在/src下。

npm install之后,运行此命令webpack-dev-server --config webpack.dev.config.js。你应该看到这个错误:

ERROR in ./index.js
Module parse failed: /Users/cheng/Dev/debug-webpack/index.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import React, { Component } from 'react';
|
| export default class App extends Component {
 @ multi main

但如果您将webpack.dev.config.js中的Line #9更改为./src/index,则相同的命令将起作用。

因此我放置index.js的位置会影响输出。

有关为何发生这种情况的任何想法?

这是我的.babelrc文件:

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": ["transform-decorators-legacy", "transform-runtime"],
  "ignore": ["node-modues/**/*.js"]
}

我安装了babel-preset-2015, stage-0 and react

我使用此CLI命令运行webpack-dev-servernode ./webpack/server.js

以下是server.js

const webpack = require('webpack'),
      WebpackDevServer = require('webpack-dev-server'),
      config = require('./dev.config')

new WebpackDevServer(webpack(config), {
    contentBase: './build',
    // webpack-dev-server options
    hot: true,
    historyApiFallback: true,
    inline: true,
    // webpack-dev-middleware options
    noInfo: false,
    quiet: false,
    lazy: false,
    publicPath: config.output.publicPath,
    headers: {'Access-Control-Allow-Origin': '*'},
    stats: { colors: true }
}).listen(port, ip, function(err, result) {
    if (err) {
        console.log(err)
    }
})

这是我使用的webpack配置文件:

const webpack = require('webpack'),
    path = require('path'),
    ExtractTextPlugin = require('extract-text-webpack-plugin')

const PATHS = {
    app: path.join(__dirname, 'app'),
    build: path.join(__dirname, 'build'),
    dist: path.join(__dirname, 'dist')
}

module.exports = {
    devtool: 'inline-source-map',
    entry: {
        javascript: [
            'webpack-dev-server/client?http://127.0.0.1:5555',
            'webpack/hot/only-dev-server',
            './app/index.js'
        ]
    },
    output: {
        path: PATHS.dist,
        filename: 'bundle.js',
        publicPath: '/static/'
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loaders: ['react-hot', 'babel?cacheDirectory'],
            exclude: /(node_modules|bower_components)/,
            include: path.join(__dirname, 'app'),
        },{
            test: /\.css$/,
            loader: ExtractTextPlugin.extract('style-loader', 'css-loader!cssnext-loader')
        },{
            test: /\.(woff|woff2|eot|ttf)$/,
            loader: 'url-loader?limit=8192&name=fonts/[name].[ext]'
        },{
            test: /\.(png|jpg|svg)$/,
            loader: 'url-loader?limit=8192&name=img/[name].[ext]'
        }]

    },
    cssnext: {
        browsers: 'last 2 versions'
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new ExtractTextPlugin(
            'bundle.css',
            {allChunks: true}),
        new webpack.DefinePlugin({
            '__DEVELOPMENT__': true,
            '__DEVTOOLS__': true
        })
    ]
}

当我运行dev服务器时,这是错误消息:

ERROR in ./app/index.js
Module parse failed: /Users/cheng/Dev/note/note-client/app/index.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import React from 'react'
| import ReactDOM from 'react-dom'
| import { Provider } from 'react-redux'
 @ multi javascript

出于某种原因,presets没有启动。我尝试使用babel CLI手动测试文件:

babel index.js  // note: .babelrc is used for configuring the presets

我实际上可以看到正确的输出。有关可能导致问题的原因的任何建议?

我安装的软件包版本:

├── babel-core@6.7.2
├── babel-eslint@5.0.0
├── babel-loader@6.2.3
├── babel-plugin-transform-decorators-legacy@1.3.4
├── babel-plugin-transform-runtime@6.6.0
├── babel-preset-es2015@6.6.0
├── babel-preset-react@6.5.0
├── babel-preset-stage-0@6.5.0
├── webpack-dev-server@1.14.1

这是我的项目折叠结构:

project_name
   |── app
        |── index.js
   |── dist
   |── build  
   |── webpack
          |── dev.config.js
          |── server.js
   |── .babelrc

我试图在项目根目录下运行以下命令,它给了我同样的错误:

webpack-dev-server --config ./webpack/dev.config.js

babel ./app/index.js有效。

1 个答案:

答案 0 :(得分:1)

由于您的配置位于webpack目录中,因此您在js loader中包含无效的路径:

    {
        test: /\.jsx?$/,
        loaders: ['react-hot', 'babel?cacheDirectory'],
        exclude: /(node_modules|bower_components)/,
        include: path.join(__dirname, 'app'),
    }

您案例中的包含路径为root/webpack/app,且必须为root/webpack/../app

path.join(__dirname, '..', 'app')