React / Webpack - "模块解析失败:意外的令牌 - 您可能需要一个合适的加载器来处理这种文件类型。"

时间:2018-02-01 19:55:41

标签: reactjs webpack

我正在尝试使用Webpack构建一个简单的React应用程序,但是在从Webpack dev服务器运行时,我收到以下错误:

> ERROR in ./client/components/home.js Module parse failed: Unexpected
> token (8:3) You may need an appropriate loader to handle this file
> type. |   render(){ |         return( |           <h1>Hello World!</h1> |         ) |     } 
> @ ./client/app.js 13:12-43  @ multi
> (webpack)-dev-server/client?http://localhost:8080 ./client/app.js

这是我的Webpack.config.js文件内容:

var path = require('path');
var debug = process.env.NODE_ENV !== 'production';
var webpack = require('webpack');


module.exports = {
    context: __dirname,
    devtool: debug ? 'inline-sourcemap' : null,
    entry: './client/app.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'app.js'
    },
    module: {
        loaders: [{
            test: /\.js?$/,
            exclude: /(node_modules|bower_components)/,
            include: [path.resolve(__dirname, 'client/app.js')],
            loader: 'babel-loader',
            query: {
                presets: ['react', 'es2015', 'stage-3'],
                plugins: ['transform-react-jsx']
            }
        }, {
            test: /\.scss$/,
            include: [path.resolve(__dirname, 'sass/style.scss')],
            loaders: ['style-loader' ,'css-loader' ,'sass-loader']
        }]
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            mangle: false,
            sourcemap: false
        }),
    ],
};

app.js文件内容 导入反应来自&#39;反应&#39; 从&#39; react-dom&#39;导入ReactDOM 从&#39; react-router-dom&#39; import {Switch,BrowserRouter,Route} 从&#39; ./ components / home.js&#39;

导入主页
ReactDOM.render((
     <BrowserRouter>
          <Switch>
            <Route exact path="/" component={Home}/>
        </Switch>
     </BrowserRouter>
     ),
     document.getElementById('app')
)

以下是我的文件夹结构如下: enter image description here

1 个答案:

答案 0 :(得分:0)

我认为它可能与您的装载机的includes属性有关:

// Here you are telling babel to ONLY transpile client/app.js. One file.
include: [path.resolve(__dirname, 'client/app.js')]

应该是:

// Instead, it needs to transpile ALL .js files under /client
include: [path.resolve(__dirname, 'client')],