Загрузка файла jsx в React-component

У меня есть компоненты / Header / index.jsx, которые выглядят так:

import React from 'react';
import PropTypes from 'prop-types';
import Breadcrumb from '../Breadcrumb';
// import styled from 'styled-components';
import Logo from '../Logo';

/* eslint-disable react/prefer-stateless-function */
class Header extends React.Component {

  render() {
    const providerId = (this.props.profileData.profileData.length > 0) ? this.props.profileData.profileData[0].provider_id : null;
    if (!providerId) {
      return "Loading...";
    }

    const certifStatus = (this.props.profileData.profileData.length > 0) ? this.props.profileData.profileData[0].certification_status : null;
    let showInfo = false;
    if (certifStatus === 'certified'){
      showInfo = true;
    }
    return (
      <div className = "header">
        <div className = "header__top">
          <div className = "container-fluid">
            <div className = "row">
              <div className = "col-12">
                <a href = "/" className = "header__logo">
                  <Logo providerId = {providerId} />
                </a>
                <span style = {{ marginLeft: '4px' }} className = "header__title">
                  {this.props.text}
                </span>
              </div>
            </div>
          </div>
        </div>
        <Breadcrumb text = "Artist certification" link = "https://www.believebackstage.com/" showInfo = {showInfo} infoLink = "#"/>
      </div>
    );
  }
}

Header.propTypes = {
  profileData: PropTypes.object,
  text: PropTypes.string,
};

export default Header;

Когда я пытаюсь импортировать его в контейнеры / ProfilePage / index.js

import Header from '../../components/Header/index.jsx';

Выбрасывает:

    ERROR in ./app/components/Header/index.jsx 28:6
Module parse failed: Unexpected token (28:6)
You may need an appropriate loader to handle this file type.
|     }
|     return (
>       <div className = "header">
|         <div className = "header__top">
|           <div className = "container-fluid">
 @ ./app/containers/ProfilePage/index.js 30:0-55 69:28-34
 @ ./app/containers/ProfilePage/Loadable.js
 @ ./app/containers/App/index.js
 @ ./app/app.js
 @ multi eventsource-polyfill webpack-hot-middleware/client?reload=true ./app/app.js

Кажется, что это проблема с веб-пакетом, поэтому вот как выглядит мой внутренний / webpack / webpack.base.babel.js:

   /**
 * COMMON WEBPACK CONFIGURATION
 */

const path = require('path');
const webpack = require('webpack');

// Remove this line once the following warning goes away (it was meant for webpack loader authors not users):
// 'DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic,
// see https://github.com/webpack/loader-utils/issues/56 parseQuery() will be replaced with getOptions()
// in the next major version of loader-utils.'
process.noDeprecation = true;

module.exports = options => ({
  mode: options.mode,
  entry: options.entry,
  output: Object.assign(
    {
      // Compile into js/build.js
      path: path.resolve(process.cwd(), 'build'),
      publicPath: '/',
    },
    options.output,
  ), // Merge with env dependent settings
  optimization: options.optimization,
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/, // Transform all .js files required somewhere with Babel
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: options.babelQuery,
        },
      },
      {
        // Preprocess our own .css files
        // This is the place to add your own loaders (e.g. sass/less etc.)
        // for a list of loaders, see https://webpack.js.org/loaders/#styling
        test: /\.scss$/,
        exclude: /node_modules/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        // Preprocess 3rd party .css files located in node_modules
        test: /\.css$/,
        include: /node_modules/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(eot|otf|ttf|woff|woff2)$/,
        use: 'file-loader',
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-url-loader',
            options: {
              // Inline files smaller than 10 kB
              limit: 10 * 1024,
              noquotes: true,
            },
          },
        ],
      },
      {
        test: /\.(jpg|png|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              // Inline files smaller than 10 kB
              limit: 10 * 1024,
            },
          },
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                enabled: false,
                // NOTE: mozjpeg is disabled as it causes errors in some Linux environments
                // Try enabling it in your environment by switching the config to:
                // enabled: true,
                // progressive: true,
              },
              gifsicle: {
                interlaced: false,
              },
              optipng: {
                optimizationLevel: 7,
              },
              pngquant: {
                quality: '65-90',
                speed: 4,
              },
            },
          },
        ],
      },
      {
        test: /\.html$/,
        use: 'html-loader',
      },
      {
        test: /\.(mp4|webm)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10000,
          },
        },
      },
    ],
  },
  plugins: options.plugins.concat([
    new webpack.ProvidePlugin({
      // make fetch available
      fetch: 'exports-loader?self.fetch!whatwg-fetch',
    }),

    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
  ]),
  resolve: {
    modules: ['node_modules', 'app'],
    extensions: ['.js', '.jsx', '.react.js'],
    mainFields: ['browser', 'jsnext:main', 'main'],
  },
  devtool: options.devtool,
  target: 'web', // Make web variables accessible to webpack, e.g. window
  performance: options.performance || {},
});

Я пробовал решения из нескольких похожих вопросов, таких как Вот этот.

Примечание: Я использую это реагировать котел. Пожалуйста, помогите мне, ребята.

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
0
1 009
1

Ответы 1

Посмотрев на документы немного внимательнее, вот как я заставил его работать ...

Взгляните сюда: https://github.com/react-boilerplate/react-boilerplate/tree/master/docs/js

Они используют plop для автогенерации контейнеров компонентов и т. д.

Так что вы просто делаете: npm run generate and follow the prompts...

Я сделал и создал контейнер под названием ProfilePage ...

В моем ProfilePage я импортировал заголовок (остальное он просто автоматически сгенерировал, единственное, что я добавил, это оператор импорта:

Вот:

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Helmet } from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import { compose } from 'redux';

// Here is my import (notice no relative path needed)
import Header from 'components/Header';

import injectSaga from 'utils/injectSaga';
import injectReducer from 'utils/injectReducer';
import makeSelectProfilePage from './selectors';
import reducer from './reducer';
import saga from './saga';
import messages from './messages';

/* eslint-disable react/prefer-stateless-function */
export class ProfilePage extends React.Component {
  render() {
    return (
      <div>
        <Helmet>
          <title>ProfilePage</title>
          <meta name = "description" content = "Description of ProfilePage" />
        </Helmet>
        <FormattedMessage {...messages.header} />
        // Here is where I render it
        <Header />
      </div>
    );
  }
}

ProfilePage.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  profilepage: makeSelectProfilePage(),
});

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
  };
}

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

const withReducer = injectReducer({ key: 'profilePage', reducer });
const withSaga = injectSaga({ key: 'profilePage', saga });

export default compose(
  withReducer,
  withSaga,
  withConnect,
)(ProfilePage);

Все это, за исключением import Header from 'components/Header' и рендеринга заголовка <Header /> чуть ниже <FormattedMessage {...messages.header} />, было автоматически сгенерировано с использованием plop

Затем я просто импортировал ProfilePage в свой App / index.js и добавил маршрут ... Теперь, когда я перехожу к localhost: 3000 / profile, ProfilePage появляется вместе с заголовком ...

Вот файл App / index.js:

import React from 'react';
import { Helmet } from 'react-helmet';
import styled from 'styled-components';
import { Switch, Route } from 'react-router-dom';

import HomePage from 'containers/HomePage/Loadable';
import FeaturePage from 'containers/FeaturePage/Loadable';
import NotFoundPage from 'containers/NotFoundPage/Loadable';
import Header from 'components/Header';
import Footer from 'components/Footer';

// Here is where I import it...
import ProfiePage from 'containers/ProfilePage';

const AppWrapper = styled.div`
  max-width: calc(768px + 16px * 2);
  margin: 0 auto;
  display: flex;
  min-height: 100%;
  padding: 0 16px;
  flex-direction: column;
`;

export default function App() {
  return (
    <AppWrapper>
      <Helmet
        titleTemplate = "%s - React.js Boilerplate"
        defaultTitle = "React.js Boilerplate"
      >
        <meta name = "description" content = "A React.js Boilerplate application" />
      </Helmet>
      <Header />
      <Switch>
        <Route exact path = "/" component = {HomePage} />
        <Route path = "/features" component = {FeaturePage} />
        // Here is the route I added...
        <Route path = "/profile" conmponent = {ProfiePage} />
        <Route component = {NotFoundPage} />
      </Switch>
      <Footer />
    </AppWrapper>
  );
}

В заключение, если вы собираетесь использовать этот шаблон, вам абсолютно необходимо просмотреть их документацию ...

Я внимательно посмотрел на документы и изменил свой ответ ... также обратите внимание, что вам не нужно выполнять относительный импорт ... (имеется в виду ../../components/Header и т. д.). Это сложный шаблон с много встроенных инструментов ... Вам действительно нужно глубже изучить документацию ...

SakoBu 22.10.2018 03:53

Другие вопросы по теме