javascript - 找不到 react

标签 javascript reactjs webpack

index.js:

import react from 'react';
import {render} from 'react-dom';

render(
    <h1>Hello World!</h1>,
    document.getElementById('root')
);

package.json:

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --progress --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Callum Linington",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "whatwg-fetch": "^2.0.3"
  },
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-env": "^1.3.2",
    "bluebird": "^3.5.0",
    "eslint": "^3.19.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}

Webpack 配置:

var webpack = require('webpack');
var packages = require('./package.json');
var path = require('path');

module.exports = {
    entry: {
        main: './src/index.js',
        vendor: Object.keys(packages.dependencies)
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor' // Specify the common bundle's name.
        })
    ],

    devtool: "cheap-eval-source-map",

    devServer: {
        contentBase: path.join(__dirname, "dist"),
        publicPath: '/',
        port: 9000
    },

    module: {
        rules: [
            {
                test: /\.js?$/,
                use: [ 'babel-loader', ],
                exclude: /node_modules/
            }
        ]
    }
};

Webpack 输出:

enter image description here

Chrome 开发输出:

enter image description here

最佳答案

以大写字母开头命名导入的 React 类至关重要。第一行应该是:import React from 'react';。这是因为所有 JSX 标签都会被 Babel 转换为类似 React.createElement(....) 的内容,而 React 不存在。控制台输出告诉您的正是如此。

关于javascript - 找不到 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43159945/

相关文章:

javascript - iframe 在另一个 iframe 中调用 javascript 函数?

javascript - 变量值从 Jsp 到 Javascript 的传递

javascript - 当到达断点时触发 jQuery

ios - 无法在 Node.JS 和 React-Native (Socket.IO) 之间建立连接

javascript - 在 ReactBootstrap Modal 中使用 KendoReact DropDownList

css - 使用 webpack,为什么要从 JS 源代码导入 CSS 文件而不是像传统那样单独构建 CSS?

javascript - 如何使用 Webpack 在 JS/TS 中只导入一小部分 npm 模块?

javascript - 使用下拉列表从 mysql 数据库中获取数据,然后使用搜索功能从选定的下拉列表选项中过滤数据

reactjs - 为什么要导入React

javascript - React 构建多个文件