使用React,Node和Express创建WebApp

时间:2017-03-24 22:23:32

标签: node.js reactjs express jsx

我的WebApp需要一些帮助 所以我开始使用NodeJs和Express,现在我想在EditProfile页面上集成一些React。

那我该怎么办呢?

我尝试过像

这样简单的事情
ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

但它不起作用

在这里和那里搜索了一些帮助但是找不到任何简单的例子让我理解。

任何人都可以给我一些提示,以帮助用反应和节点来建立水疗中心吗?

1 个答案:

答案 0 :(得分:0)

我认为你使用webpack作为你的捆绑者(如果你没有webpack,它是我更加舒适的,所以我可以给你更好的指导):

sudo npm install -g webpack@1.12.13

首先,您需要确保安装了react和react-dom库,如果没有,请转到项目文件夹并运行此命令(这是我目前在项目中使用的版本,但您可以使用另一个):

npm install --save react@0.14.7 react-dom@0.14.7

其次,你需要Babel来转换ES6代码,不是强制性的,但是对Babel来说更加舒适,这是你在开发环境中需要的依赖:

npm install --save-dev webpack@1.12.13 babel-core@6.5.1 babel-loader@6.2.2 babel-preset-es2015@6.5.0 babel-preset-react@6.5.0

我知道这可能很乏味,所以忍受我......

在您的开发设置中,您可能会使用ES6功能,这是当像webpack和Babel这样的捆绑器派上用场时,Babel会将您的ES6代码转换为ES5(在每个浏览器中实现)并且Webpack将要捆绑你需要的所有文件以及你的依赖项,并生成一个bundle.js(你的整个应用程序)。

让我们配置Webpack! 在项目的根目录中,您将找到(或创建)webpack.config.js文件,内容应该看起来像这样一个非常简单的设置:

  module.exports = {
  entry: './public/app.jsx',
  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  resolve: {
    root: __dirname,
    // Thanks to this aliases we can reference component files without specifiying the path each time
    alias: {
    },
    extensions: ['', '.js', '.jsx']
  },
  module: {
  //Added the loader into modules
    loaders: [
      {
      //Loader Name
        loader: 'babel-loader',
        //Specifies what we whant the loader to make with our files
        query: {
        //We told Babel to take our files and transforms them trough react and then the es2015
          presets: ['react', 'es2015']
        },
        //Regular expresion to find the files we want to parse within our project
        test: /\.jsx?$/,
        //Specifies the directories we do not want to parse.
        exclude: /(node_modules|bower_components)/
      }
    ]
  }
};

现在您已完成所有基本设置,您可以使用以下命令捆绑所有内容:

webpack

你可以找到我制作的样板项目,其中包含如何在我的github配置文件中运行它的说明,它有一个很好的文件夹结构和一个快速服务器供你运行测试。这应该让一切都更清楚。

https://github.com/agustincastro/ReactBoilerplate

我希望它能帮助您完成基本设置并运行,以便您可以使用React。

干杯!!