如何在反应样板中使用jsx而不是js扩展?

时间:2018-06-04 12:18:30

标签: reactjs redux jsx boilerplate

我只想在https://github.com/react-boilerplate/react-boilerplate/

中添加jsx页面

以下是我要添加的密码忘记页面jsx文件内容。

import React from 'react';
import { connect } from 'react-redux';
import {Link, Route} from 'react-router-dom';

class PwdForgotPage extends React.Component {
  render() {
    return (
      <div className="col-md-6 col-md-offset-3">
        Password forgot.
        <button className="btn btn-link">Back</button>
      </div>
    );
  }
}

function mapStateToProps(state) {
  const { registering } = state.registration;
  return {
    registering,
  };
}

const connectedPwdForgotPage = connect(mapStateToProps)(PwdForgotPage);
export { connectedPwdForgotPage as PwdForgotPage };

但如果我使用jsx扩展名,则无法按以下方式运行。

Module parse failed: C:\.....\frontend\app\containers\PwdForgotPage\PwdForgotPage.jsx Unexpected token (8:6)
You may need an appropriate loader to handle this file type.
|   render() {
|     return (
|       <div className="col-md-6 col-md-offset-3">
|         Password forgot.
|         <button className="btn btn-link">Back</button>

如果我使用js扩展,它可以工作。 如何在样板中更改jsx扩展支持的配置?

2 个答案:

答案 0 :(得分:2)

您需要在webpack配置中为规则添加jsx扩展名,以启用babel babel-loader

{
    test: /\.jsx?$/, // notice optional x?
    exclude: /node_modules/,
    use: {
      loader: 'babel-loader',
      options: options.babelQuery,
    },
  },

https://github.com/react-boilerplate/react-boilerplate/blob/master/internals/webpack/webpack.base.babel.js#L23

或主观上更具可读性/\.(js|jsx)$/

答案 1 :(得分:0)

从您现有的项目中,您可以运行:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

然后 .jsx 文件将被解释。

有关更多信息,请查看以下站点: https://create-react-app.dev/docs/adding-typescript/