Thanks to visit codestin.com
Credit goes to github.com

Skip to content

build(*): change project setup #87

Merged
merged 4 commits into from
Apr 21, 2020
Merged

build(*): change project setup #87

merged 4 commits into from
Apr 21, 2020

Conversation

reme3d2y
Copy link
Contributor

@reme3d2y reme3d2y commented Apr 18, 2020

Проблема

Оказалось, что сейчас мы не можем использовать один компонент в другом 🤷‍♂️

Т.к. это монорепа и все пакеты публикуются отдельно, то мы не можем указывать в импорте относительные пути.
Вместо этого нужно указать зависимость как:
import { Input } from '@alfalab/core-components-input';

Но сейчас такой импорт становится внешней зависимостью.

В нашем же случае необходимо, чтобы:

  1. Во время разработки зависимости от других компонентов разрешались локально
  2. В билдах компонентов эти зависимости были внешними
  3. В агрегирующем пакете зависимости были локальными

В данном PR:

  • Решен вопрос с импортом компонентов через yarn workspaces
  • Теперь весь проект собирается с помощью tsc --build
  • Обновлена сборка проекта
  • Компоненты публикуются из корня пакета, а не из папки dist
  • Добавлен резолвер для сторибука
  • Выпилен babel
  • Выпилен react-scripts, т.к. он не позволяет использовать "paths" в ".tsconfig" (issue) и конфликтует с некоторыми настройками.
  • Компоненты теперь лежат в папке packages (react-scripts заставлял использовать src)
  • Настроен jest (раньше он работал через react-scripts)

Вынести в README

  • Для использования компонента внутри другого нужно:
  1. Добавить зависимость в package.json пакета
  2. Добавить в tsconfig.json пакета следующую запись:
"references": [
    { "path": "../input" }
]
  1. Импортировать зависимость через import { Input } from '@alfalab/core-components-input';

- allow use one component in another
- build via tsc
- setup jest
- update build scripts
- revert packages folder
@alfa-bot
Copy link
Collaborator

Собрана новая демка.

'error',
{ devDependencies: true, packageDir: './' },
],
'import/no-extraneous-dependencies': 'off'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пришлось пока отключить, т.к. линтер ругается на импорт компонентов.
Например:

import { Input } from '@alfalab/core-components-input';

просит добавить @alfalab/core-components-input в корневой package.json.
Хотя он не должен быть зависимостью в агрегирующем пакете.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если добавить зависимость не в корневой package.json, а в package.json пакета, то линтер успокоется.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

мне тоже так казалось. Но почему-то ошибка исчезает, только если к корневой добавить

image

bin/build.sh Outdated
# запускаю скрипт build-root-package.sh во всех подпакетах
lerna exec --parallel -- $(pwd)/bin/build-root-package.sh \$LERNA_PACKAGE_NAME

# меняю импорты из @alfalab/core-components на относительные в агрегирующем пакете
yarn replace-in-file "require(\"@alfalab/core-components-" "require(\"../" dist/**/*.js
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В агрегирующем пакете компоненты должны импортироваться друг в друга локально, а не быть внешними зависимостями. Сейчас просто делаем замену по js файлам.

Как это сделать лучше?

@@ -0,0 +1,19 @@
module.exports = {
Copy link
Contributor Author

@reme3d2y reme3d2y Apr 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Раньше запуск тестов был через react-scripts, но он начал конфликтовать с tsconfig

Поэтому отказался от react-scripts и вынес настройку jest'а.
К тому же это позволит в дальнейшем гибко настроить тестирование.

@@ -0,0 +1,13 @@
{
"include": ["src", "../../typings"],
Copy link
Contributor Author

@reme3d2y reme3d2y Apr 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

К сожалению все path-зависимые опции не работают через extends (issue) - поэтому приходится определять их в каждом файле заново.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Странно, у нас всё ок.

Ниже скрин общего конфига ТС и конфига у пакета.

image

image

Copy link
Contributor Author

@reme3d2y reme3d2y Apr 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сейчас, если не добавить typings в include:
Cannot find module './index.module.css'.
Хз, может что-то не так прописал

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

"compilerOptions": {
"skipLibCheck": true,
"target": "esnext",
"module": "commonjs",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

теперь эти настройки влияют на сборку

@alfa-bot
Copy link
Collaborator

Собрана новая демка.

@@ -1,7 +1,7 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
node_modules/
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Игнорим везде, а не только в корне

@alfa-bot
Copy link
Collaborator

Собрана новая демка.

@7rulnik
Copy link

7rulnik commented Apr 18, 2020

А разве https://classic.yarnpkg.com/en/docs/workspaces не решает проблему?

@reme3d2y
Copy link
Contributor Author

reme3d2y commented Apr 18, 2020

А разве https://classic.yarnpkg.com/en/docs/workspaces не решает проблему?

workspaces же для приватных репозиториев

Note that the private: true is required! Workspaces are not meant to be published

@7rulnik
Copy link

7rulnik commented Apr 18, 2020

Это не так, посмотри на реакт например
https://github.com/facebook/react/blob/master/package.json#L3

Подразумевается, что ты не должен паблишить корневой воркспейс, но пакеты в нём паблишить можно

@7rulnik
Copy link

7rulnik commented Apr 18, 2020

Если хочется future-proof решения, то можно посмотреть в сторону yarn@2
babel/babel#11167
Но есть проблема с lerna/lerna#2450

@alfa-bot
Copy link
Collaborator

Собрана новая демка.

lerna exec --parallel -- rm -rf ./dist/__snapshots__
# обрабатываю ts во всех подпакетах
lerna exec --parallel -- tsc --p tsconfig.json
lerna exec --parallel -- tsc --build
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Раньше компиляция ts делалась babel'ом, а генерация деклараций через tsc. Половина опций из tsconfig не использовалась.

Теперь сборкой занимается только компилятор ts

@reme3d2y
Copy link
Contributor Author

reme3d2y commented Apr 18, 2020

При использовании workspaces создаются симлинки на папки с компонентами.
В package.json было указано "main": "index.js", но index.js в папке с компонентом нет, поэтому сборка и ide не работали.

Заменил на "main": "dist/index.js".

Также, теперь публикация происходит из корня пакета, а не из папки dist

@reme3d2y reme3d2y merged commit 8fdf89f into master Apr 21, 2020
@delete-merged-branch delete-merged-branch bot deleted the change-project-setup branch April 21, 2020 11:42
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants