简体   繁体   中英

Importing React Component with JSX

There was a problem with importing react component with JXS. Components are imported from library (used like a SDK).

/sdk/dist/js/app.js

import React, { Component } from 'react';

 export default class Test extends Component {
    render() {
       return <div>Hello</div>;
    }
 }

There is a project where this SDK is used, there is webpack / babel that already does a build, the file with import of this component looks like this:

app/js/index.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import Test from 'sdk/dist/js/App';

Result: введите сюда описание изображения

BUT! Everything will work if:

  1. We remove JSX from this component

app/js/index.js

import React, { Component } from 'react';

export default class Test extends Component {
    render() {
        return React.createElement(
            "div",
            null,
            "Hello"
        );
    }
}

  1. Remove import and insert component directly.

app/js/index.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Test extends Component {
    render() {
        return <div>Hello</div>;
    }
}

введите сюда описание изображения

The problem is that it needs to work through import. I suggest that the problem is that the webpack does not transpose the imported file - and reads it as is ...

webpack:

{
      entry: './app/js/index.js',
      output: {
        path: resolve(__dirname, plConfig.paths.public.root),
        filename: "[name].js"
      },

      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: [
              {
                loader: "babel-loader",
                options: {
                  cacheDirectory: true
                }
              }
            ]
          }
        ]
      }

.babelrc:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

You'll need a babel plugin to transform jsx...

@babel/plugin-transform-react-jsx

Install npm i -D @babel/plugin-transform-react-jsx

Use in .babelrc

{
    presets: [ ... ],
    plugins: [ "@babel/plugin-transform-react-jsx", ...other plugins ]
}

EDIT :

You also need to add a babel rule for jsx ... In your webpack module rules...

Change test: /\\.js$/ to test: /\\.jsx?$/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM