Skip to content

Commit 4ec63ba

Browse files
committed
feat(hook): add hook that can rewrite output paths before files are emitted.
1 parent 626c6d3 commit 4ec63ba

File tree

15 files changed

+376
-53
lines changed

15 files changed

+376
-53
lines changed

README.md

Lines changed: 122 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,20 @@ In comparison with the [official plugin](https://github.com/rollup/rollup-plugin
7777
- [Typescript, Babel, and Browserslist example](#typescript-babel-and-browserslist-example)
7878
- [Pure Typescript with CustomTransformers](#pure-typescript-with-customtransformers)
7979
- [Advanced example of using Typescript, Babel, and Browserslists together](#advanced-example-of-using-typescript-babel-and-browserslists-together)
80+
- [Hooks](#hooks)
81+
- [The `outputPath` hook](#the-outputpath-hook)
82+
- [Full list of plugin options](#full-list-of-plugin-options)
83+
- [`transpiler`](#transpiler)
84+
- [`babelConfig`](#babelconfig)
85+
- [`tsconfig`](#tsconfig)
86+
- [`browserslist`](#browserslist)
87+
- [`cwd`](#cwd)
88+
- [`transformers`](#transformers)
89+
- [`include`](#include)
90+
- [`exclude`](#exclude)
91+
- [`transpileOnly`](#transpileonly)
92+
- [`fileSystem`](#filesystem)
93+
- [`hook`](#hook)
8094
- [Ignored/overridden options](#ignoredoverridden-options)
8195
- [Ignored/overridden Typescript options](#ignoredoverridden-typescript-options)
8296
- [Ignored/overridden Babel options](#ignoredoverridden-babel-options)
@@ -349,9 +363,7 @@ This example shows how you can use this plugin to accomplish quite advanced thin
349363

350364
```javascript
351365
const IS_PRODUCTION = (process.env.NODE_ENV = "production");
352-
const BUNDLE_TARGET = process.env.NODE_ENV;
353-
const BROWSERSLIST_MODERN = ["since 2015", "not dead", "> 5%"];
354-
const BROWSERSLIST_LEGACY = ["defaults"];
366+
const BUNDLE_TARGET = process.env.BUNDLE_TARGET;
355367
const APP_ROOT = "/some/project/root/folder";
356368
const awesomeFrameworkTransformers = getAwesomeFrameworkCustomTransformers();
357369

@@ -377,6 +389,113 @@ ts({
377389
});
378390
```
379391

392+
## Hooks
393+
394+
`rollup-plugin-ts` provides a few hooks that allow you to hook into and augment the internal behavior of the plugin.
395+
396+
These can be provided in the plugin options for the `hook` property:
397+
398+
```typescript
399+
ts({
400+
hook: {
401+
// Add hooks here
402+
}
403+
});
404+
```
405+
406+
The next few subsections describe the different hooks that can be provided
407+
408+
### The `outputPath` hook
409+
410+
Type: `(path: string, kind: "declaration" | "declarationMap") => string | undefined`
411+
412+
The `outputPath` hook can be used to rewrite the location on the filesystem that assets produced by `rollup-plugin-ts` are written to.
413+
It is invoked immediately before assets such as _declarations_ or _declaration maps_ are emitted.
414+
415+
The hook is invoked with the output path as well as the kind of asset the path represents as arguments.
416+
If you return a `string` from the hook, the alternative location will be used instead. If you return undefined, the current path will be used.
417+
418+
```typescript
419+
ts({
420+
hook: {
421+
outputPath: (path, kind) => rewritePathSomehow(path, kind)
422+
}
423+
});
424+
```
425+
426+
For example, the `path` may be `/some/path/index.d.ts`, and `kind` be `declaration`, and you might want to rewrite this to `/some/path/my-typings.d.ts`.
427+
428+
## Full list of plugin options
429+
430+
The plugin options are documented in more detail across this README, but the full list of options is:
431+
432+
#### `transpiler`
433+
434+
Type: `"typescript" | "babel"`
435+
436+
Can be any of `"babel"` or `"typescript"` (default: `"typescript"`).
437+
See [this section](#combining-typescript-with-babel) and [this section](#when-combined-with-babel-what-does-typescript-do-and-what-does-babel-do) for details on how `rollup-plugin-ts` works when `"babel"` is being used as a transpiler.
438+
439+
#### `babelConfig`
440+
441+
Type: `string | Partial<IBabelInputOptions>`
442+
443+
This option will only be respected when `"babel"` is being used as the `transpiler` and can be used to provide a [Babel config](https://babeljs.io/docs/en/options) or a path to one.
444+
445+
#### `tsconfig`
446+
447+
Type: `string | Partial<CompilerOptions> | Partial<Record<keyof CompilerOptions, string | number | boolean>> | ParsedCommandLine | TsConfigResolver | TsConfigResolverWithFileName`
448+
449+
Provide the Typescript [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to use, or a path to a `tsconfig` with this property.
450+
See [this section](#using-it-with-just-typescript) for details on the many ways this property can be configured.
451+
452+
#### `browserslist`
453+
454+
Type: `false | string[] | string | BrowserslistConfig`
455+
456+
Provide the [Browserslist](https://github.com/browserslist/browserslist) to use, or a path to a `.browserslistrc` with this property.
457+
See [this section](#combining-typescript-with-a-browserslist) for details on the many ways this property can be configured.
458+
459+
#### `cwd`
460+
461+
Type: `string`
462+
463+
Use this property to overwrite whatever is considered the root directory. The default value is `process.cwd()`.
464+
465+
#### `transformers`
466+
467+
Type: `(CustomTransformers | CustomTransformersFunction)[] | CustomTransformers | CustomTransformersFunction`
468+
469+
Use this property to provide Typescript [`CustomTransformers`](https://github.com/Microsoft/TypeScript/pull/13940).
470+
See [this section](#using-customtransformers) for more details on how to configure this property.
471+
472+
#### `include`
473+
474+
Type: `string[]|string`
475+
476+
This option takes a minimatch pattern or an array of minimatch patterns and only transforms files with filenames that the pattern matches.
477+
478+
#### `exclude`
479+
480+
Type: `string[]|string`
481+
482+
This option takes a minimatch pattern or an array of minimatch patterns and only transforms files with filenames that the pattern doesn't match.
483+
484+
#### `transpileOnly`
485+
486+
Type: `boolean`
487+
488+
If this option is `true`, diagnostics won't be generated. This will improve performance since Typescript but ignores all syntactical and semantic errors or warnings that may arise.
489+
490+
#### `fileSystem`
491+
492+
Optionally the [FileSystem](https://github.com/wessberg/rollup-plugin-ts/blob/master/src/util/file-system/file-system.ts) to use. This is useful for example when you want to provide a virtual FileSystem to read from or write to.
493+
494+
#### `hook`
495+
496+
Use this property to get hooks into the internals of `rollup-plugin-ts`.
497+
See [this section](#hooks) for more details.
498+
380499
## Ignored/overridden options
381500

382501
Typescript and Babel are powerful tools in their own right. Combined with Rollup, they become even more powerful.

package.json

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -49,42 +49,42 @@
4949
],
5050
"license": "MIT",
5151
"devDependencies": {
52-
"@wessberg/rollup-plugin-ts": "^1.1.63",
52+
"@wessberg/rollup-plugin-ts": "^1.1.64",
5353
"@wessberg/scaffold": "^1.0.19",
5454
"@wessberg/ts-config": "^0.0.41",
55-
"ava": "2.3.0",
56-
"husky": "^3.0.4",
57-
"np": "^5.0.3",
55+
"ava": "2.4.0",
56+
"husky": "^3.0.7",
57+
"np": "^5.1.0",
5858
"prettier": "^1.18.2",
5959
"pretty-quick": "^1.11.1",
60-
"rollup": "^1.20.3",
60+
"rollup": "^1.22.0",
6161
"standard-changelog": "^2.0.13",
62-
"ts-node": "8.3.0",
63-
"tslint": "^5.19.0",
64-
"typescript": "^3.6.2"
62+
"ts-node": "8.4.1",
63+
"tslint": "^5.20.0",
64+
"typescript": "^3.6.3"
6565
},
6666
"dependencies": {
67-
"@babel/core": "^7.5.5",
67+
"@babel/core": "^7.6.2",
6868
"@babel/plugin-proposal-async-generator-functions": "^7.2.0",
6969
"@babel/plugin-proposal-json-strings": "^7.2.0",
70-
"@babel/plugin-proposal-object-rest-spread": "^7.5.5",
70+
"@babel/plugin-proposal-object-rest-spread": "^7.6.2",
7171
"@babel/plugin-proposal-optional-catch-binding": "^7.2.0",
72-
"@babel/plugin-proposal-unicode-property-regex": "^7.4.4",
72+
"@babel/plugin-proposal-unicode-property-regex": "^7.6.2",
7373
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
74-
"@babel/plugin-transform-runtime": "^7.5.5",
75-
"@babel/preset-env": "^7.5.5",
76-
"@babel/runtime": "^7.5.5",
74+
"@babel/plugin-transform-runtime": "^7.6.2",
75+
"@babel/preset-env": "^7.6.2",
76+
"@babel/runtime": "^7.6.2",
7777
"@types/mkdirp": "^0.5.2",
78-
"@types/node": "^12.7.2",
78+
"@types/node": "^12.7.8",
7979
"@types/resolve": "0.0.8",
80-
"@wessberg/browserslist-generator": "1.0.23",
80+
"@wessberg/browserslist-generator": "1.0.26",
8181
"@wessberg/stringutil": "^1.0.18",
82-
"browserslist": "4.6.6",
82+
"browserslist": "4.7.0",
8383
"find-up": "^4.1.0",
84-
"magic-string": "^0.25.3",
84+
"magic-string": "^0.25.4",
8585
"mkdirp": "^0.5.1",
8686
"resolve": "^1.12.0",
87-
"rollup-pluginutils": "^2.8.1",
87+
"rollup-pluginutils": "^2.8.2",
8888
"slash": "^3.0.0",
8989
"tslib": "^1.10.0"
9090
},

rollup.config.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ export default {
2626
...builtinModules,
2727
...Object.keys(packageJson.dependencies),
2828
...Object.keys(packageJson.devDependencies),
29-
...Object.keys(packageJson.peerDependencies)
29+
...Object.keys(packageJson.peerDependencies),
30+
"@babel/core/lib/config/files/configuration",
31+
"@babel/core/lib/config/files/package"
3032
]
3133
};

src/plugin/i-typescript-plugin-options.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ export interface TsConfigResolverWithFileName {
2222

2323
export type TsConfigResolver = TsConfigResolverWithFileName["hook"];
2424

25+
export type OutputPathKind = "declaration" | "declarationMap";
26+
export type OutputPathHook = (path: string, kind: OutputPathKind) => string | undefined;
27+
28+
export interface HookRecord {
29+
outputPath: OutputPathHook;
30+
}
31+
2532
export interface ITypescriptPluginBaseOptions {
2633
transpiler: Transpiler;
2734
tsconfig?:
@@ -38,6 +45,7 @@ export interface ITypescriptPluginBaseOptions {
3845
exclude: string[] | string;
3946
transpileOnly?: boolean;
4047
fileSystem: FileSystem;
48+
hook: Partial<HookRecord>;
4149
}
4250

4351
export interface ITypescriptPluginTypescriptOptions extends ITypescriptPluginBaseOptions {

src/plugin/typescript-plugin.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ export default function typescriptRollupPlugin(pluginInputOptions: Partial<Types
392392
const generateMap = Boolean(parsedCommandLineResult.parsedCommandLine.options.declarationMap);
393393

394394
const chunkToOriginalFileMap: Map<string, string[]> = new Map(
395-
chunks.map<[string, string[]]>(chunk => [join(declarationOutDir, normalize(chunk.fileName)), Object.keys(chunk.modules).map(normalize)])
395+
chunks.map<[string, string[]]>(chunk => [join(outDir, normalize(chunk.fileName)), Object.keys(chunk.modules).map(normalize)])
396396
);
397397
const moduleNames = [
398398
...new Set(
@@ -431,6 +431,7 @@ export default function typescriptRollupPlugin(pluginInputOptions: Partial<Types
431431
outDir,
432432
cwd,
433433
outputOptions,
434+
pluginOptions,
434435
languageService,
435436
languageServiceHost,
436437
emitCache,

src/service/transformer/declaration-bundler/util/module-specifier/normalize-module-specifier.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ export function normalizeModuleSpecifier({
3434
const normalizedAbsoluteModuleSpecifierText = getChunkFilename(absoluteModuleSpecifierText, supportedExtensions, chunkToOriginalFileMap);
3535

3636
// Potentially rewrite the ModuleSpecifier text to refer to one of the generated chunk filenames (which may not be the same or named the same)
37-
const normalizedModuleSpecifier = stripExtension(
38-
ensureHasLeadingDotAndPosix(relative(dirname(absoluteOutFileName), normalizedAbsoluteModuleSpecifierText))
37+
const normalizedModuleSpecifier = ensureHasLeadingDotAndPosix(
38+
stripExtension(relative(dirname(absoluteOutFileName), normalizedAbsoluteModuleSpecifierText)),
39+
false
3940
);
4041

4142
return {

src/service/transformer/declaration-tree-shaker/after-declarations/after-declarations.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ import {mergeImports} from "../util/merge-imports/merge-imports";
77
import {mergeExports} from "../util/merge-exports/merge-exports";
88
import {normalize} from "path";
99

10-
export function afterDeclarations({relativeOutFileName}: IDeclarationTreeShakerOptions): TransformerFactory<SourceFile> {
10+
export function afterDeclarations({declarationFilename}: IDeclarationTreeShakerOptions): TransformerFactory<SourceFile> {
1111
return context => {
1212
return sourceFile => {
1313
// If the SourceFile is not part of the local module names, remove all statements from it and return immediately
14-
if (normalize(sourceFile.fileName) !== normalize(relativeOutFileName)) return updateSourceFileNode(sourceFile, [], true);
14+
if (normalize(sourceFile.fileName) !== normalize(declarationFilename)) return updateSourceFileNode(sourceFile, [], true);
1515

1616
// Prepare a cache
1717
const cache: ReferenceCache = {
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export interface IDeclarationTreeShakerOptions {
22
relativeOutFileName: string;
3+
declarationFilename: string;
34
}

src/util/emit-declarations/i-emit-declarations-options.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {LanguageService} from "typescript";
33
import {IncrementalLanguageService} from "../../service/language-service/incremental-language-service";
44
import {IEmitCache} from "../../service/cache/emit-cache/i-emit-cache";
55
import {FileSystem} from "../file-system/file-system";
6+
import {TypescriptPluginOptions} from "../../plugin/i-typescript-plugin-options";
67

78
export interface IEmitDeclarationsOptions {
89
pluginContext: PluginContext;
@@ -15,6 +16,7 @@ export interface IEmitDeclarationsOptions {
1516
moduleNames: string[];
1617
localModuleNames: string[];
1718
entryFileNames: string[];
19+
pluginOptions: TypescriptPluginOptions;
1820
outputOptions: OutputOptions;
1921
languageService: LanguageService;
2022
languageServiceHost: IncrementalLanguageService;

0 commit comments

Comments
 (0)