webpack4:React babel-您可能需要适当的加载程序来处理此文件类型

时间:2018-07-20 19:33:13

标签: javascript reactjs webpack babeljs

我是webpack 4 / react / babel的新手,但出现以下错误:

ERROR in ./src/index.js 7:4
Module parse failed: Unexpected token (7:4)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
>     <Hello compiler="TypeScript" framework="React" />,
|     document.getElementById("example")
| );

我尝试了以下解决方案:link from stack overflow,但是也没有用。

所以我被困住了,主要区别是我使用的是webpack 4(请注意,我没有使其与webpack 3一起使用)

我的环境是:

  • windows:10
  • nodejs:6.9.5

下面是带有相对路径的文件

./ package.json

{
  "name": "using-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.4.1",
    "react-dom": "^16.4.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "file-loader": "^1.1.11",
    "webpack": "^4.16.1"
  }
}

./ .. babelrc

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

./ webpack.config.js

    module.exports = {
        mode:"development",
    entry: {
        javascript: "./src/index.js",
        html: "./src/index.html",
    },
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".js"]
    },

    module: {
        rules: [
            { 
                test:"/\.js$/",
                exclude:"/node_modules/",
                loader:"babel-loader",
            },
        ]
    },////

    externals: {
        "react": "React",
        "react-dom": "ReactDOM"
    }
};

./ index.js

import * as React from "react";
import * as ReactDOM from "react-dom";

import { Hello } from "./components/hello";

ReactDOM.render(
    <Hello compiler="TypeScript" framework="React" />,
    document.getElementById("example")
);

./ components / hello.js

import * as React from "react";


// 'HelloProps' describes the shape of props.
// State is never set so we use the '{}' type.
export class Hello extends React.Component {
    render() {
        return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>;
    }
}

1 个答案:

答案 0 :(得分:1)

您的模块部分应包含正则表达式,而其中包含纯字符串。

删除正则表达式周围的引号! :)

module: {
    rules: [
        { 
            test: /\.js$/,
            exclude: /node_modules/,
            loader:"babel-loader",
        },
    ]
},