简体   繁体   中英

'import' issue with React, webpack hot reload

I have an issue in my react project. I am using webpack dev server to serve my files. the webpack build is successful but I am getting an error on the browser like

"app.js:7 Uncaught SyntaxError: Unexpected token import"

in the line:

import React from 'react';

Below is my webpack.config.js

module.exports = {
context: __dirname + "/app",    
entry: "./app.js",     output: {
    filename: "app.build.js",
    path: __dirname + "/dist",
},

module: {
    loaders: [
        {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loaders: ["react-hot-loader", "babel-loader"],
        },
        {
            test: /\.html$/,
            loader: "file?name=[name].[ext]",
        },            

        { 
            test: /\.js$/, 
            exclude: /node_modules/, 
            loaders: ["react-hot-loader", "babel-loader"],
        }

    ]
}    
};

And in my .babelrc I have

{
   "presets": ["react", "es2015"]
}

I have tried adding various babel configs like using stage-0, stage-2, etc., but none of them worked. Is there any way to fix this.

I found answer to my own question:

The way react hot loader works is the output file app.build.js mentioned in the webpack config.js is served by the hot loader server directly but not created under specific path(dist/) as mentioned in config.

so localhost/app.build.js is available instead of localhost/dist/app.build.js.

when I refer "script src="app.build.js" in my index.html it started working.

The file app.build.js is created in path ("/dist") only for "webpack" or "webpack --watch" command. not for "webpack-dev-server" command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM