Eject react что это
Отказ от create-react-app и создание собственного шаблона для React-приложений
Что такое CRA?
Create React App — это набор инструментов, созданный и поддерживаемый разработчиками из Facebook. CRA предназначен для быстрого создания шаблонных проектов React-приложений. При использовании CRA база React-проекта создаётся с помощью одной команды.
Сильные стороны CRA
Недостатки CRA
Альтернатива CRA
Вот репозиторий, в котором имеется весь код, который мы будем обсуждать в этом материале.
Начнём работу с инициализации проекта средствами npm и с инициализации его git-репозитория:
Это позволит нам не включать в состав репозитория папки, имена которых присутствуют в файле.
Теперь поразмыслим о том, какие основные зависимости нам нужны для того чтобы собрать и запустить React-приложение.
Библиотеки react и react-dom
Это — единственные зависимости времени выполнения, которые нам нужны:
Транспилятор (Babel)
Транспилятор Babel преобразует код, соответствующий стандартам ECMAScript 2015+, в код, который будет работать и в новых, и в устаревших браузерах. Babel, благодаря применению пресетов, используется и для обработки JSX-кода:
Babel поддерживает множество пресетов и плагинов. Их можно добавлять в проект по мере возникновения необходимости в них.
Бандлер (Webpack)
Бандлер Webpack отвечает за сборку проекта, формируя на основе кода проекта и кода его зависимостей единственный файл (бандл) приложения. При использовании таких техник оптимизации проектов, как разделение кода, в бандл приложения могут входить и несколько файлов.
Простая конфигурация Webpack, предназначенная для сборки пакетов React-приложений, выглядит так, как показано ниже:
Сюда, в соответствии с нуждами конкретного приложения, можно добавить различные загрузчики. Если вам эта тема интересна — взгляните на мой материал, где я рассказываю о конфигурациях Webpack, которыми можно воспользоваться для подготовки React-приложений к использованию в продакшне.
Это — все необходимые нам зависимости. Теперь давайте добавим в проект шаблонный HTML-файл и заготовку React-компонента.
Создадим в директории проекта папку src и добавим в неё файл index.html :
В той же папке создадим React-компонент HelloWorld :
В ту же папку добавим файл index.js :
И наконец — добавим в package.json описания скриптов для запуска ( start ) и сборки ( build ) проекта:
Теперь давайте оснастим нашу систему возможностью подготовки шаблона проекта с помощью единственной команды. То есть — воссоздадим одну из сильных сторон CRA. Мы собираемся использовать исполняемый JS-файл, который будет вызываться при вводе соответствующей команды в командной строке. Например, подобная команда может выглядеть так:
Сначала установим пакет fs-extra:
Теперь давайте свяжем этот исполняемый JS-файл с командой из package.json :
Создадим локальную связь для пакета:
Замечательно. Теперь всё это работает на вашем компьютере и позволяет вам, пользуясь единственной командой, создавать базовые React-проекты, обладающие собственной конфигурацией сборки.
Вы можете пойти дальше и опубликовать свой шаблон в реестре npm. Для того чтобы это сделать, сначала надо отправить проект в GitHub-репозиторий. А дальше — следуйте этим инструкциям.
Конечно, наше решение минималистично. Проекты, создаваемые на его основе, нельзя признать готовыми к использованию в продакшне. Для того чтобы подготовить их к реальной работе, нужно оснастить наш шаблон некоторыми настройками Webpack, ответственными за оптимизацию сборок проектов.
Я подготовил шаблон reactjs-boilerplate, позволяющий создавать проекты, готовые к работе в продакшне. Тут используется соответствующая конфигурация сборки, линтинг и хуки, ответственные за проверку проекта перед созданием коммитов. Испытайте этот шаблон. Если у вас появятся какие-то идеи по его совершенствованию, или если вы решите сделать вклад в его разработку — присоединяйтесь к работе над ним.
Итоги
Вот о чём мы говорили в этом материале:
Пользуетесь ли вы create-react-app при создании новых React-проектов?
Все, что вам нужно знать о react-scripts
В прошлом создание приложения React было болезненным процессом. Вам пришлось пройти через множество настроек, прежде чем вы могли запачкать руки и развить что-то осмысленное.
Что такое сценарий?
create-react-app поставляется с четырьмя основными сценариями, каждый из которых мы рассмотрим позже. Но сейчас мы сосредоточимся на том, где найти эти скрипты.
Теперь, когда мы знаем, что такое скрипт и где его найти, давайте углубимся в каждый из них и объясним, что он делает с приложением React.
start
Или, если вы используете npm:
Эта команда не только запускает сервер, но также реагирует и отображает последнюю версию при каждом изменении. Кроме того, он покажет ошибки lint на терминале (консоли), когда он не сможет запустить сервер в виде значимых сообщений об ошибках.
Сценарий test может быть запущен на терминале с помощью следующих команд.
build
React является модульным, поэтому вы можете создавать несколько файлов или компонентов, если хотите. Эти отдельные файлы должны быть объединены или объединены, чтобы быть точными в одном файле.
Сценарий можно запустить с помощью следующих команд.
eject
Чтобы запустить команду на терминале, введите следующую команду.
Вывод
Я надеюсь, что это руководство пролило некоторый свет на удивительную конфигурацию приложения Create React. Он поставляется не только с полезными сценариями, которые могут помочь облегчить жизнь любому разработчику, но и с некоторыми командами, имеющими гибкие параметры, которые позволяют адаптировать сценарии к уникальным потребностям вашего проекта.
Полная видимость в производственных приложениях React
LogRocket похож на видеорегистратор для веб-приложений, записывая буквально все, что происходит в вашем приложении React. Вместо того, чтобы гадать, почему возникают проблемы, вы можете агрегировать и сообщать, в каком состоянии было ваше приложение, когда возникла проблема. LogRocket также отслеживает производительность вашего приложения, предоставляя отчеты с такими показателями, как загрузка ЦП клиента, использование памяти клиента и т. д.
Промежуточный пакет LogRocket Redux добавляет дополнительный уровень видимости в ваши пользовательские сессии. LogRocket записывает все действия и состояние из ваших магазинов Redux.
React: Установка и настройка
В настоящее время React является самой популярной библиотекой JavaScript для создания пользовательских интерфейсов, и в обозримом будущем эта тенденция сохранится. В этой статье мы рассмотрим способы быстрой и безболезненной настройки React. Так что мы можем погрузиться прямо в программирование!
Почему React?
Установка и настройка
Есть несколько способов начать работу с React. Во-первых, мы взглянем на CodeSandbox и CodePen. Если вы хотите сразу начать играть с кодом, это хороший способ!
React в CodeSandbox
Перейдите на https://codesandbox.io/s и нажмите «React».
Мгновенно вы окажетесь в среде React, которая была настроена с помощью create-react-app. Мы рассмотрим этот метод далее в статье! Если вы хотите начать программирование без настройки локальной установки, это отличный способ! Такие задачи, как сборка, преобразование и управление зависимостями, все автоматизированы, и вы можете легко поделиться ссылкой на все, над чем вы работали!
React в CodePen
Создаем приложение React
Установка с помощью Create React App
Все, что нам нужно сделать, это открыть наш терминал и запустить следующую команду:
Запустите указанную выше команду, чтобы начать установку! Дайте ему любое имя, которое вам нравится..
Установка может занять несколько минут. Прямо сейчас он устанавливает все зависимости, необходимые для построения вашего проекта. И это также генерирует вашу первоначальную структуру проекта.
Успех! Теперь вы можете открыть папку вашего проекта и проверить созданную файловую структуру.
Несколько команд были добавлены в файл package.json :
Запуск вашего приложения
Теперь давайте запустим наш локальный сервер! Из папки вашего приложения запустите:
Ваше приложение запустится в браузере на localhost:3000
Каждый раз, когда вы начинаете новый проект с помощью create-react-app, вы будете иметь последнюю версию React, React-DOM и React-Scripts. Теперь давайте кратко рассмотрим некоторые функции create-react-app.
Возможности Create-React-App
Прод сборка
Сама команда build преобразует ваш код React в код, который понимает браузер (используя Babel). Он также оптимизирует ваши файлы для лучшей производительности, объединяя все ваши файлы JavaScript в один файл, который будет минимизирован для сокращения времени загрузки.
Тестирование вашего приложения
Ejecting
Сообщения об ошибках
Опечатки и синтаксические ошибки приведут к ошибке компиляции. И если у вас есть куча ошибок, вы получите оверлей, разбивающий каждую, например так:
Заключение
Create Apps with No Configuration
Create React App is a new officially supported way to create single-page React applications. It offers a modern build setup with no configuration.
First, install the global package:
Node.js 4.x or higher is required.
Now you can use it to create a new app:
This will take a while as npm installs the transitive dependencies, but once it’s done, you will see a list of commands you can run in the created folder:
Starting the Server
Run npm start to launch the development server. The browser will open automatically with the created app’s URL.
Create React App uses both webpack and Babel under the hood. The console output is tuned to be minimal to help you focus on the problems:
ESLint is also integrated so lint warnings are displayed right in the console:
We only picked a small subset of lint rules that often lead to bugs.
Building for Production
To build an optimized bundle, run npm run build :
It is minified, correctly envified, and the assets include content hashes for caching.
Your package.json contains only a single build dependency and a few scripts:
We take care of updating Babel, ESLint, and webpack to stable compatible versions so you can update a single dependency to get them all.
It is worth repeating: there are no configuration files or complicated folder structures. The tool only generates the files you need to build your app.
All the build settings are preconfigured and can’t be changed. Some features, such as testing, are currently missing. This is an intentional limitation, and we recognize it might not work for everybody. And this brings us to the last point.
We first saw this feature in Enclave, and we loved it. We talked to Ean, and he was excited to collaborate with us. He already sent a few pull requests!
“Ejecting” lets you leave the comfort of Create React App setup at any time. You run a single command, and all the build dependencies, configs, and scripts are moved right into your project. At this point you can customize everything you want, but effectively you are forking our configuration and going your own way. If you’re experienced with build tooling and prefer to fine-tune everything to your taste, this lets you use Create React App as a boilerplate generator.
We expect that at early stages, many people will “eject” for one reason or another, but as we learn from them, we will make the default setup more and more compelling while still providing no configuration.
You can find Create React App with additional instructions on GitHub.
This is an experiment, and only time will tell if it becomes a popular way of creating and building React apps, or fades into obscurity.
We welcome you to participate in this experiment. Help us build the React tooling that more people can use. We are always open to feedback.
React was one of the first libraries to embrace transpiling JavaScript. As a result, even though you can learn React without any tooling, the React ecosystem has commonly become associated with an overwhelming explosion of tools.
Eric Clemmons called this phenomenon the “JavaScript Fatigue”:
Ultimately, the problem is that by choosing React (and inherently JSX), you’ve unwittingly opted into a confusing nest of build tools, boilerplate, linters, & time-sinks to deal with before you ever get to create anything.
It is tempting to write code in ES2015 and JSX. It is sensible to use a bundler to keep the codebase modular, and a linter to catch the common mistakes. It is nice to have a development server with fast rebuilds, and a command to produce optimized bundles for production.
Combining these tools requires some experience with each of them. Even so, it is far too easy to get dragged into fighting small incompatibilities, unsatisfied peerDependencies, and illegible configuration files.
Many of those tools are plugin platforms and don’t directly acknowledge each other’s existence. They leave it up to the users to wire them together. The tools mature and change independently, and tutorials quickly get out of date.
Marc was almost ready to implement his «hello world» React app pic.twitter.com/ptdg4yteF1
This doesn’t mean those tools aren’t great. To many of us, they have become indispensable, and we very much appreciate the effort of their maintainers. They already have too much on their plates to worry about the state of the React ecosystem.
Still, we knew it was frustrating to spend days setting up a project when all you wanted was to learn React. We wanted to fix this.
We found ourselves in an unusual dilemma.
So far, our strategy has been to only release the code that we are using at Facebook. This helped us ensure that every project is battle-tested and has clearly defined scope and priorities.
However, tooling at Facebook is different than at many smaller companies. Linting, transpilation, and packaging are all handled by powerful remote development servers, and product engineers don’t need to configure them. While we wish we could give a dedicated server to every user of React, even Facebook cannot scale that well!
The React community is very important to us. We knew that we couldn’t fix the problem within the limits of our open source philosophy. This is why we decided to make an exception, and to ship something that we didn’t use ourselves, but that we thought would be useful to the community.
The Quest for a React CLI
Having just attended EmberCamp a week ago, I was excited about Ember CLI. Ember users have a great “getting started” experience thanks to a curated set of tools united under a single command-line interface. I have heard similar feedback about Elm Reactor.
Providing a cohesive curated experience is valuable by itself, even if the user could in theory assemble those parts themselves. Kathy Sierra explains it best:
If your UX asks the user to make choices, for example, even if those choices are both clear and useful, the act of deciding is a cognitive drain. And not just while they’re deciding… even after we choose, an unconscious cognitive background thread is slowly consuming/leaking resources, “Was that the right choice?”
I never tried to write a command-line tool for React apps, and neither has Christopher. We were chatting on Messenger about this idea, and we decided to work together on it for a week as a hackathon project.
We knew that such projects traditionally haven’t been very successful in the React ecosystem. Christopher told me that multiple “React CLI” projects have started and failed at Facebook. The community tools with similar goals also exist, but so far they have not yet gained enough traction.
Still, we decided it was worth another shot. Christopher and I created a very rough proof of concept on the weekend, and Kevin soon joined us.
We invited some of the community members to collaborate with us, and we have spent this week working on this tool. We hope that you’ll enjoy using it! Let us know what you think.
We would like to express our gratitude to Max Stoiber, Jonny Buchanan, Ean Platter, Tyler McGinnis, Kent C. Dodds, and Eric Clemmons for their early feedback, ideas, and contributions.
What does this «react-scripts eject» command do?
What does the npm run eject command do? I do understand what other commands do like start, build, test. But no idea about eject.
5 Answers 5
create-react-app encapsulates all of the npm modules it is using internally, so that your package.json will be very clean and simple without you having to worry about it.
However, if you want to start doing more complex things and installing modules that may interact with modules create-react-app is using under the hood, those new modules need to know what is available and not, meaning you need to have create-react-app un-abstract them.
That, in essence, is what react-scripts eject does. It will stop hiding what it’s got installed under the hood and instead eject those things into your project’s package.json for everyone to see.
If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
Alternatives to Ejecting
Ejecting lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to fork react-scripts and any other packages you need. This article dives into how to do it in depth. You can find more discussion in this issue.















