javascript - React - Babel 不转译文件

标签 javascript reactjs babeljs

我正在检查路由 lessons对于 react

经过多次尝试,我得到了一个可以运行的应用程序,我可以使用:

var react = require("react");
var Render = require('react-dom');
Render((
<Router history={hashHistory}>
<Route path="/about" component={About}/>
</Router>
), document.getElementById('app'))

然而,网络上的大多数示例都使用 import 语句,例如:

import { Router, Route, hashHistory } from 'react-router'

render((
  <Router history={hashHistory}>
    <Route path="/" component={App}/>
  </Router>
 ), document.getElementById('app'))

在我的浏览器中产生以下错误:enter image description here (渲染未定义)。

这是我的 web.pack.config:

    var path = require('path');
    var webpack = require('webpack');
     module.exports = {
      entry: [
       './src/app.js'
      ],
      output: {
      path: path.join(__dirname, 'public/js'),
      filename: 'app.built.js'
      },
      module: {
       loaders: [
        { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?  
       presets[]=es2015&presets[]=react'
        }
       ]
     }
   }

我必须做什么才能开始使用 import 语句?

最佳答案

该错误是因为您没有导入 ReactDOM。最好的方法是

import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, IndexRoute, hashHistory } from "react-router";

import App from "./App";

const app = document.getElementById('app');

ReactDOM.render(
  <Router history={hashHistory}>
    <Route path="/" component={App}></Route>
  </Router>, app);

考虑到您在同一目录中有一个名为 App 的组件,如下所示:

App.js

import React from "react";

export default class App extends React.Component {
  render() {
    return (
      <div>My App!</div>
    );
  }
}

关于javascript - React - Babel 不转译文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776317/

相关文章:

javascript - 我可以传递对特定对象的实例函数的引用吗?

javascript - 当在 "TypeError: Cannot read property ' 内部时, react "Map"未定义状态'

javascript - 尝试写入 firestore 时“RestConnection 提交失败并出现错误”

node.js - 在 Node.js 中动态导入 webpack

node.js - React 代码无法使用 webpack 进行编译

javascript - 如何在 vue.js 中添加 v-model 动态创建的 html?

javascript - jQuery 在悬停时切换 backgroundPosition?

javascript - 没有 jQuery 的委托(delegate)事件处理程序

javascript - 当 React Native(android) 中的 Multiline={true} 时,onSubmitEditing 不适用于 TextInput

javascript - 访问 React 事件的 props