React / Webpack - “模块解析失败:意外令牌 - 您可能需要适当的加载程序来处理此文件类型。”

Posted

技术标签:

【中文标题】React / Webpack - “模块解析失败:意外令牌 - 您可能需要适当的加载程序来处理此文件类型。”【英文标题】:React / Webpack - "Module parse failed: Unexpected token - You may need an appropriate loader to handle this file type." 【发布时间】: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')
)

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

【问题讨论】:

【参考方案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')], 

【讨论】:

以上是关于React / Webpack - “模块解析失败:意外令牌 - 您可能需要适当的加载程序来处理此文件类型。”的主要内容,如果未能解决你的问题,请参考以下文章

模块解析失败:Webpack Typescript Loader 中出现意外的令牌

模块解析失败:意外字符“@”(1:0)

模块解析失败:意外的令牌。 react-native/index.js "typeof" 运算符

webpack 4 - 模块解析失败:简单 JS 文件上的意外字符 '�' (1:0)

Webpack通过“模块解析失败,出现意外令牌”

当使用 webpack 编译 React 时,它返回 Unexpected token (