【问题标题】:React / Webpack - "Module parse failed: Unexpected token - You may need an appropriate loader to handle this file type."React / Webpack - “模块解析失败:意外令牌 - 您可能需要适当的加载程序来处理此文件类型。”
【发布时间】:2018-07-12 05:58:56
【问题描述】:

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

> 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 文件内容 从“反应”导入反应 从 'react-dom' 导入 ReactDOM 从 'react-router-dom' 导入 { Switch, BrowserRouter, Route } 从'./components/home.js'导入主页

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

下面是我的文件夹结构如下:

【问题讨论】:

    标签: reactjs webpack


    【解决方案1】:

    我认为这可能与您的加载程序的 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')], 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-09
      • 2019-02-26
      • 2019-01-28
      • 2021-12-04
      • 2022-11-10
      • 2018-02-27
      • 2019-10-11
      • 2021-02-10
      相关资源
      最近更新 更多