当前位置: 首页 > 知识库问答 >
问题:

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

皇甫鸿远
2023-03-14

我正在尝试使用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文件内容从“React”导入React从“React dom”导入ReactDOM从“React dom”导入{Switch,BrowserRouter,Route}从“React router dom”导入Home从“./components/Home.js”

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

共有1个答案

松波
2023-03-14

我认为这可能与您的加载器的包含属性有关:

// 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')], 
 类似资料: