@tramvai/build 2.6.3 → 2.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +70 -84
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # @tramvai/build
2
2
 
3
- Библиотека предназначена для `production` сборки написанных на TypeScript пакетов под разные окружения:
3
+ Library for building `production` ready bundles for packages written in TypeScript targetting next environments:
4
4
 
5
5
  - NodeJS
6
- - Бандлеры (Webpack, etc.)
7
- - Браузеры
6
+ - Bundlers (Webpack, etc.)
7
+ - Browsers
8
8
 
9
- ## Подключение
9
+ ## Installation
10
10
 
11
- Необходимо установить `@tramvai/build`:
11
+ Install `@tramvai/build` first:
12
12
 
13
13
  ```bash
14
14
  yarn add @tramvai/build
15
15
  ```
16
16
 
17
- Заполнить необходимые поля в `package.json`:
17
+ Add necessary fields to `package.json`:
18
18
 
19
19
  ```json
20
20
  {
@@ -23,11 +23,11 @@ yarn add @tramvai/build
23
23
  }
24
24
  ```
25
25
 
26
- > `"main": "lib/index.js"` на основе этого поля вычисляется, что точка входа для сборки должна называться `"src/index.ts"`
26
+ > `"main": "lib/index.js"` based on that field lib calculates entry point for the build and it will be `"src/index.ts"` in this case
27
27
 
28
- > `"typings": "src/index.ts"` желательно должен указывать на точку входа, это удобно для монореп, т.к. не требует сборки пакета для его использования в других пакетах. После сборки для публикации это поле заменится на файл с собранными типами, в данном случае - `"typings": "lib/index.d.ts"`
28
+ > `"typings": "src/index.ts"` desirable to specify that field to entry point as it is useful for the monorepo projects and allows to use current package in other packages without build. After build package for publication this filed will be replaced to point to the built typedef file, in this case - `"typings": "lib/index.d.ts"`
29
29
 
30
- И в `tsconfig.json`:
30
+ And to `tsconfig.json`:
31
31
 
32
32
  ```json
33
33
  {
@@ -42,72 +42,59 @@ yarn add @tramvai/build
42
42
  "outDir": "./lib",
43
43
  "declarationDir": "./lib"
44
44
  },
45
- "include": [
46
- "./src"
47
- ]
45
+ "include": ["./src"]
48
46
  }
49
47
  ```
50
48
 
51
- Добавить в `dependencies` библиотеку [tslib](https://www.npmjs.com/package/tslib):
49
+ Add to `dependencies` library [tslib](https://www.npmjs.com/package/tslib):
52
50
 
53
51
  ```bash
54
52
  yarn add tslib
55
53
  ```
56
54
 
57
- Собрать пакет через команду `tramvai-build`:
55
+ Build package with command `tramvai-build`:
58
56
 
59
57
  ```bash
60
58
  tramvai-build --forPublish
61
59
  ```
62
60
 
63
- > с флагом `--forPublish` tramvai-build заменяет некоторые поля в `package.json` на необходимые для корректного использования библиотеки в приложениях, например `"typings": "src/index.ts"` заменяется на `"typings": "lib/index.d.ts"`
61
+ > with flag `--forPublish` tramvai-build replaces some fields in `package.json` in order to make built package usable in the end apps, for example `"typings": "src/index.ts"` replaces by `"typings": "lib/index.d.ts"`
64
62
 
65
63
  ## Explanation
66
64
 
67
- Основное предназначение библиотеки - эффективная `production` сборка TypeScript пакетов с помощью [rollup](https://rollupjs.org/),
68
- также поддерживается [watch](https://rollupjs.org/guide/en/#rollupwatch) режим.
65
+ The main purpose for the lib is the effective `production` build for TypeScript package using [rollup](https://rollupjs.org/), with [watch](https://rollupjs.org/guide/en/#rollupwatch) mode support.
69
66
 
70
- Такие сборки, особенно при наличии большого количества пакетов в монорепозитории, могут занимать слишком много времени, и не подойдут для эффективной и удобной разработки.
71
- По этой причине, для `development` окружения рекомендуется использовать [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html), с фичами [project references](https://www.typescriptlang.org/docs/handbook/project-references.html) и [incremental build](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#faster-subsequent-builds-with-the---incremental-flag).
67
+ Such builds, especially for monorepositories with big number of packages, can take a long time and are not very comfortable to work. Thats why, for the `development` environment it is preferred to use [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) with [project references](https://www.typescriptlang.org/docs/handbook/project-references.html) and [incremental build](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#faster-subsequent-builds-with-the---incremental-flag).
72
68
 
73
- Рекомендуемый и автоматически генерируемый `package.json` для `@tramvai/build` позволяет приложениям использовать пакеты собранные и через `tsc`, и через `@tramvai/build`, без дополнительных действий.
69
+ Recommended and automatically generated `package.json` for `@tramvai/build` allows apps to use packages that were built either with `tsc`, or with `@tramvai/build` without any additional steps.
74
70
 
75
- Все собранные бандлы содержат код стандарта `ES2019`, ожидается то их будет резолвить бандлер (Webpac, etc.), для которого уже настроена транспиляция через `babel` пакетов в `node_modules`, написанных на современном JS, в код стандарта `ES5`.
71
+ All of the built bundles will contain `ES2019` standard code, it is expected that they will be bundled to `ES5` using bundler (Webpack, etc.) with configured transpilation through `babel` for packages inside `node_modules`, written in modern JS.
76
72
 
77
- ### Бандл под NodeJS в CommonJS формате
73
+ ### NodeJS bundle in CommonJs format
78
74
 
79
- NodeJS до 12 версии не поддерживает ES модули, либо поддерживает их под специальным флагом.
80
- `@tramvai/build` генерирует бандл с кодом стандарта `ES2019`, в формате `CommonJS`, автоматически,
81
- название итогового бандла берется из поля `main` в `package.json`, например `lib/index.js`.
75
+ NodeJS before 12 version hasn't supported ES modules or supported it only behind special flag. `@tramvai/build` generates bundle in `ES2019` standard in `CommonJS` format automatically. Name of the result bundle is taken from field `main` in `package.json`, e.g. `lib/index.js`.
82
76
 
83
- При сборке нашего пакета в приложении через `webpack` с опцией `target: 'node'`, этот бандл скорее всего не будет использован,
84
- т.к. в приоритете будет бандл из поля `module`.
77
+ When bundling package in the app using `webpack` with option `target: 'node'` this `CommonJS` bundle probably will not be used as webpack will prefer to use `module` field while resolving source code.
85
78
 
86
- > Ожидается, что этот бандл, из поля `"main"`, будет резолвить только NodeJS, а бандлеры (Webpac, etc.) предпочтут бандл из поля `"module"`
79
+ > It is expected that bundle from field `"main"` will be resolved only by `NodeJS` itself while bundlers will use bundle from field `"module"`
87
80
 
88
- ### Бандл под бандлеры (Webpack, etc.) в формате ES modules
81
+ ### Bundle for bundlers (Webpack, etc.) in ES modules format
89
82
 
90
- Современные бандлеры (Webpac, etc.) поддерживают ES модули, и нестандартное поле `"module"` в `package.json`.
91
- `@tramvai/build` генерирует бандл с кодом стандарта `ES2019`, в формате `ES modules`, автоматически,
92
- название итогового бандла вычисляется из поля `main` в `package.json`, и добавляется суффикс `.es` например `lib/index.es.js`.
83
+ Modern bundlers support ES modules and non-standard field `"module"` in `package.json`. `@tramvai/build` generates bundle in `ES2019` standard in `ES modules` format automatically. Name of the result bundle is calculates from field `main` in `package.json` by adding postfix `.es` e.g. `lib/index.es.js`.
93
84
 
94
- Если сборка произведена через `tramvai-build --forPublish`, в `package.json` добавится поле `"module": "lib/index.es.js"`.
85
+ If build was called with flag `--forPublish` to `package.json` will be added new field `"module": "lib/index.es.js"`.
95
86
 
96
- При сборке нашего пакета в приложении через `webpack` с опцией `target: 'node'`, бандл из поля `module` будет иметь больший приоритет, чем поле `main`.
87
+ When bundling package in the app through `webpack` with option `target: 'node'` bundle from field `module` will have higher priority over bundle from `main`.
97
88
 
98
- > Генерируется код стандарта `ES2019`, т.к. ожидается, что этот бандл, из поля `"module"`, будут резолвить бандлер (Webpac, etc.), для которого уже настроена транспиляция через `babel` пакетов в `node_modules`, написанных на современном JS, в код стандарта `ES5`.
99
- > Почему мы не советуем оставлять `ES2019` код? Оказалось, что код в `ES5` работает заметно быстрее на NodeJS сервере. При этом, размер итогового бандла на сервере не имеет значения.
89
+ > `ES2019` code standard is generated as it is expected that bundle from field `"module"` will be resolved by bundler with configured transpilation through `babel` for packages inside `node_modules`, written in modern JS. Why we still prefer to use `ES5` code over `ES2019`? Apparently, code in `ES5` is still notably faster on NodeJS server. In the same time output bundle size is not important on server.
100
90
 
101
- ### Бандл для браузеров
91
+ ### Bundle for browsers
102
92
 
103
- Современные бандлеры (Webpac, etc.) поддерживают ES модули, и нестандартное поле `"browser"` в `package.json`.
104
- При наличии поля `browser` в `package.json`, `@tramvai/build` генерирует бандл с кодом стандарта `ES2019`, в формате `ES modules`.
93
+ Modern bundlers support ES modules and non-standard field `"browser"` in `package.json`. When field `browser` in specified in `package.json`, `@tramvai/build` will generate bundle in `ES2019` standard in `ES modules` format.
105
94
 
106
- Если поле `browser` в `package.json` является строкой, то из этого файла вычисляется точка входа для `browser` бандла, и его новое название.
107
- Например, при `"browser": "lib/browser.js"`, точкой входа будет `src/browser.ts`, а бандл будет называться `lib/browser.js`.
95
+ If field `browser` in `package.json` is defined as a string then this string determines entry point to `browser` bundle and its name. E.g. when `"browser": "lib/browser.js"` entry point will be `src/browser.ts` and bundle will have a name `lib/browser.js`.
108
96
 
109
- Иначе, если поле `browser` является объектом и сборка произведена через `tramvai-build --forPublish`, название вычисляется из поля `main` в `package.json`, и добавляется суффикс `.browser`, например `lib/index.browser.js`.
110
- Далее в поле `browser` добавится свойство, указывающее сборщикам приложений, какой бандл резолвить для браузерной сборки, вместо поля `module`:
97
+ Otherwise, if field `browser` is defined as an object and build was called with flag `--forPublish` then name is defined by the field `main` in `package.json` with adding postfix `.browser` e.g. `lib/index.browser.js`. After that to field `browser` new property will be added as pointer for bundlers to bundle for the browser, instead of the field `module`:
111
98
 
112
99
  ```json
113
100
  {
@@ -118,46 +105,45 @@ NodeJS до 12 версии не поддерживает ES модули, ли
118
105
  }
119
106
  ```
120
107
 
121
- > Спецификация поля [browser](https://github.com/defunctzombie/package-browser-field-spec)
122
- > Генерируется код стандарта `ES2019`, т.к. ожидается, что этот бандл, из поля `"browser"`, будут резолвить бандлер (Webpac, etc.), для которого уже настроена транспиляция через `babel` пакетов в `node_modules`, написанных на современном JS, в код согласно актуальному browserslist конфигу.
108
+ > Specification for the field [browser](https://github.com/defunctzombie/package-browser-field-spec)
123
109
 
124
- При сборке нашего пакета в приложении через `webpack` с опцией `target: 'web'`, бандл из поля `browser` будет иметь больший приоритет, чем поле `module`.
110
+ > `ES2019` code standard is generated as it is expected that bundle from `"browser"` field will be resolved by bundler with configured transpilation through `babel` for packages inside `node_modules` written in modern JS to the code according to the `browserslist` config.
125
111
 
126
- ### Копирование статических файлов
112
+ When building our package in the app with `webpack` with option `target: 'web'` bundle from field `browser` will be prioritized over field `module`.
127
113
 
128
- При каждом билде автоматически копируются все файлы, кроме JS/TS скриптов и JSON, например CSS, изображения, шрифты, и сохраняются исходные пути до файлов (`src/css/style.css` -> `lib/css/style.css`).
129
- Копирование можно отключить, собирая пакет с флагом `copyStaticAssets`:
114
+ ### Copy static assets
115
+
116
+ For every build, all of the non JS/TS/JSON files (e.g. CSS, fonts, images) are copied to the output bundle preserving their relative paths (e.g. `src/css/style.css` -> `lib/css/style.css`). You can disable such copying by using flag `copyStaticAssets`:
130
117
 
131
118
  ```bash
132
119
  tramvai-build --copyStaticAssets false
133
120
  ```
134
121
 
135
- ### Сборка и копирование миграций
122
+ ### Build and copy migrations
136
123
 
137
- При наличии файлов в папке `migrations`, они считаются исходниками миграций.
138
- Эти файлы компилируются в `.js` и копируются в папку `__migrations__`.
124
+ When directory `migrations` has any code files they are considered as migration files. These files will be compiled to `.js` and copied to directory `__migrations__`.
139
125
 
140
126
  ## CLI
141
127
 
142
- ### Разовая сборка
128
+ ### Single build
143
129
 
144
130
  ```bash
145
131
  tramvai-build
146
132
  ```
147
133
 
148
- ### Сборка в watch режиме
134
+ ### Build in watch mode
149
135
 
150
136
  ```bash
151
137
  tramvai-build --watch
152
138
  ```
153
139
 
154
- ### Копирование статических файлов
140
+ ### Copy static assets
155
141
 
156
142
  ```bash
157
143
  tramvai-copy
158
144
  ```
159
145
 
160
- ### Доступные флаги
146
+ ### Available flags
161
147
 
162
148
  ```bash
163
149
  tramvai-build --help
@@ -167,7 +153,7 @@ tramvai-build --help
167
153
 
168
154
  ### TramvaiBuild
169
155
 
170
- `TramvaiBuild` позволяет конфигурировать утилиту для дальнейшего использования.
156
+ `TramvaiBuild` is used to configure build process for following usage.
171
157
 
172
158
  ```ts
173
159
  import { TramvaiBuild } from '@tramvai/build';
@@ -175,13 +161,13 @@ import { TramvaiBuild } from '@tramvai/build';
175
161
  new TramvaiBuild(options);
176
162
  ```
177
163
 
178
- **Доступные опции:**
164
+ **Available options:**
179
165
 
180
166
  @inline src/options.h.ts
181
167
 
182
- ### Сборка
168
+ ### Build
183
169
 
184
- Метод `TramvaiBuild.start` позволяет собрать пакет, разово или в `watch` режиме, в зависимости от конфигурации экземпляра `TramvaiBuild`:
170
+ Method `TramvaiBuild.start` builds package either single time or in `watch` mode depending on configuration of `TramvaiBuild`:
185
171
 
186
172
  ```ts
187
173
  import { TramvaiBuild } from '@tramvai/build';
@@ -189,9 +175,9 @@ import { TramvaiBuild } from '@tramvai/build';
189
175
  new TramvaiBuild(options).start();
190
176
  ```
191
177
 
192
- ### Копирование статических файлов
178
+ ### Copy static files
193
179
 
194
- Метод `TramvaiBuild.copy` позволяет разово копировать статические файлы в `output` директорию:
180
+ Method `TramvaiBuild.copy` copies static assets to the `output` directory:
195
181
 
196
182
  ```ts
197
183
  import { TramvaiBuild } from '@tramvai/build';
@@ -201,10 +187,9 @@ new TramvaiBuild(options).copy();
201
187
 
202
188
  ## How to
203
189
 
204
- ### Как собрать отдельный бандл для браузерной сборки?
190
+ ### Build separate bundle for browsers
205
191
 
206
- Допустим, у нас есть две точки входа, серверная - `src/server.ts`, и клиентская - `src/browser.ts`.
207
- В таком случае, необходимо настроить поле `browser` в `package.json` таким образом:
192
+ Let's say we have to entry points. One is for the server - `src/server.ts` and for the client - `src/browser.ts`. In this case we should set field `browser` in `package.json` the next way:
208
193
 
209
194
  ```json
210
195
  {
@@ -213,7 +198,7 @@ new TramvaiBuild(options).copy();
213
198
  }
214
199
  ```
215
200
 
216
- После сборки для публикации мы получим такой `package.json`:
201
+ After build for publication we will get next `package.json`:
217
202
 
218
203
  ```json
219
204
  {
@@ -224,10 +209,9 @@ new TramvaiBuild(options).copy();
224
209
  }
225
210
  ```
226
211
 
227
- ### Как заменить отдельный модуль для браузерной сборки?
212
+ ### Replace specific module for browser bundle
228
213
 
229
- Допустим, у нас есть одна точка входа - `src/index.ts`, а модуль `src/external.ts` мы хотим заменить на `src/external.browser.ts`.
230
- В таком случае, необходимо настроить поле `browser` в `package.json` таким образом:
214
+ Let's say we have one entry point - `src/index.ts` and a module `src/external.ts` we want to replace by `src/external.browser.ts`. In this case we should set field `browser` in `package.json` the next way:
231
215
 
232
216
  ```json
233
217
  {
@@ -238,27 +222,27 @@ new TramvaiBuild(options).copy();
238
222
  }
239
223
  ```
240
224
 
241
- После сборки для публикации мы получим такой `package.json`:
225
+ After build for publication we will get next `package.json`:
242
226
 
243
227
  ```json
244
228
  {
245
229
  "main": "lib/index.js",
246
230
  "browser": {
247
231
  "./lib/external.js": "./lib/external.browser.js",
248
- "./lib/index.es.js": "./lib/index.browser.js",
232
+ "./lib/index.es.js": "./lib/index.browser.js"
249
233
  },
250
234
  "typings": "lib/index.d.ts",
251
235
  "module": "lib/index.es.js"
252
236
  }
253
237
  ```
254
238
 
255
- ### Как собирать все пакеты в монорепе при разработке, в watch режиме?
239
+ ### Build all of the packages in monorepo in watch mode
256
240
 
257
- @TODO + ссылка на `@tinkoff/fix-ts-references`
241
+ @TODO + link to `@tinkoff/fix-ts-references`
258
242
 
259
- ### Как сделать чтобы модуль импортировался только при определенных условиях, а иначе игнорировался при сборке?
243
+ ### Import module only under some circumstances or put module to separate chunk
260
244
 
261
- Вместо статичных импортов можно использовать динамический import или require. В этом случае, импортированный модуль будет собран в отдельный чанк и будет добавлен в сборку вебпаком при необходимости, причем при использовании динамического импорта также будет создан отдельный чанк после сборки вебпака, при использовании require отдельного чанка не будет.
245
+ Instead of static imports you can use dynamic import or require. In this case imported module will be build in the separate chunk. Later this chunk can be added by bundler to the generated bundle and if dynamic import was used it will be separate chunk as well after bundlers build, but when using require separate chunk will not be generated.
262
246
 
263
247
  ```tsx
264
248
  let func = noop;
@@ -270,9 +254,9 @@ if (process.env.NODE_ENV !== 'production') {
270
254
  export { func };
271
255
  ```
272
256
 
273
- ### Как использовать json файлы в пакете?
257
+ ### Use JSON in package
274
258
 
275
- По умолчанию в корневом `tsconfig.json` включена опция `resolveJsonModule` которая позволяет импортировать json-файлы также как и обычный код используя `import`, причем всё будет работать с типизацией и tree-shaking при публикации пакета. Для того чтобы ts не ругался на такие импорты необходимо в `tsconfig.json` пакета добавить новое вхождение в поле `includes`:
259
+ By default in root `tsconfig.json` option `resolveJsonModule` is enabled. It is allows to import json-files the same way as usual source code using `import`, moreover typecheck and tree-shaking will work to json as well when publishing package. To disable ts errors for json imports add to `tsconfig.json` of the package new entry to field `includes`:
276
260
 
277
261
  ```json
278
262
  {
@@ -280,9 +264,9 @@ export { func };
280
264
  }
281
265
  ```
282
266
 
283
- ### Как использовать файлы других расширений в пакете (например .css)?
267
+ ### Use assets file in the package (e.g. css, svg)
284
268
 
285
- Такие файлы не используются в сборке или явно в коде, и ts такие файлы игнорирует. Для правильной работы пакета потребуется дополнительная настройка, а именно прописать в `package.json` пакета скрипт `tramvai-copy`:
269
+ These files are not used in bundle or source code and ts will ignore them. For proper package usage additional setup should be done. Add script `tramvai-copy` to `package.json`:
286
270
 
287
271
  ```json
288
272
  {
@@ -292,11 +276,11 @@ export { func };
292
276
  }
293
277
  ```
294
278
 
295
- Цель этого скрипта в копировании файлов не относящихся к исходному коду в директорию сборки. Само копирование происходит либо при установке зависимостей в корне репозитория, либо при непосредственной публикации пакетов. Так как в некоторых кейсах по какой-либо причине директория сборки может быть удалена то возможно потребуется перезапуск команды `tramvai-copy` для данных пакетов.
279
+ This script will copy not related files to source code to the output directory. Copying itself happens either on dependencies install in the repository root or on package publishing. As for some reasons output directory might be deleted it may be needed to rerun `tramvai-copy` command for package.
296
280
 
297
- ### Как использовать css-модули в пакете?
281
+ ### Use css-modules
298
282
 
299
- Для того, чтобы typescript не ругался на импорты css-модулей, в папку `src` внутри пакета нужно добавить файл `typings.d.ts` с определением:
283
+ In order to disable typescript errors for css-modules imports add new file `typings.d.ts` to the `src` folder with the next content:
300
284
 
301
285
  ```tsx
302
286
  declare module '*.css' {
@@ -305,10 +289,12 @@ declare module '*.css' {
305
289
  }
306
290
  ```
307
291
 
308
- Для копирования css во время dev-сборки нужно изменить команду:
292
+ To copy css while deb-build change next command:
309
293
 
310
294
  ```json
311
295
  "watch": "tramvai-copy && tsc -w"
312
296
  ```
313
297
 
314
- Такие импорты никак не преобразуются, для правильной сборки нужно использовать `@tramvai/cli` или другие решения для css-модулей. При сборке корректность импортов не проверяется, так что проверяйте пакет перед публикацией.
298
+ Such imports are not compiled. To use it properly you can use `@tramvai/cli` for building app or any other solution for the css-modules.
299
+
300
+ > When building correctness of imports for the css is not checking so check your package manually before publication.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tramvai/build",
3
- "version": "2.6.3",
3
+ "version": "2.6.4",
4
4
  "description": "Rollup wrapper, build multiple bundles for different module systems",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {