Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use TypeScript config and improve some types #4144

Merged
merged 4 commits into from Jun 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -1,6 +1,7 @@
import MagicString from 'magic-string';
import { Plugin } from 'rollup';

export default function addCliEntry() {
export default function addCliEntry(): Plugin {
return {
buildStart() {
this.emitFile({
Expand All @@ -17,6 +18,7 @@ export default function addCliEntry() {
magicString.prepend('#!/usr/bin/env node\n\n');
return { code: magicString.toString(), map: magicString.generateMap({ hires: true }) };
}
return null;
}
};
}
@@ -1,9 +1,10 @@
import MagicString from 'magic-string';
import { Plugin } from 'rollup';

const FSEVENTS_REQUIRE = "require('fsevents')";
const REPLACEMENT = "require('../../../src/watch/fsevents-importer').getFsEvents()";

export default function conditionalFsEventsImport() {
export default function conditionalFsEventsImport(): Plugin {
let transformed = false;
return {
buildEnd(error) {
Expand Down
@@ -1,4 +1,6 @@
export default function emitModulePackageFile() {
import { Plugin } from 'rollup';

export default function emitModulePackageFile(): Plugin {
return {
generateBundle() {
this.emitFile({ fileName: 'package.json', source: `{"type":"module"}`, type: 'asset' });
Expand Down
@@ -1,4 +1,6 @@
export default function addBinShebangAndEsmImport() {
import { Plugin } from 'rollup';

export default function addBinShebangAndEsmImport(): Plugin {
let importFound = false;
return {
generateBundle() {
Expand Down
@@ -1,11 +1,12 @@
import fs from 'fs';
import license from 'rollup-plugin-license';
import { PluginImpl } from 'rollup';
import license, { Dependency, Person } from 'rollup-plugin-license';

function generateLicenseFile(dependencies) {
function generateLicenseFile(dependencies: Dependency[]) {
const coreLicense = fs.readFileSync('LICENSE-CORE.md');
const licenses = new Set();
const dependencyLicenseTexts = dependencies
.sort(({ name: nameA }, { name: nameB }) => (nameA > nameB ? 1 : -1))
.sort(({ name: nameA }, { name: nameB }) => (nameA! > nameB! ? 1 : -1))
.map(({ name, license, licenseText, author, maintainers, contributors, repository }) => {
let text = `## ${name}\n`;
if (license) {
Expand All @@ -15,7 +16,8 @@ function generateLicenseFile(dependencies) {
if (author && author.name) {
names.add(author.name);
}
for (const person of maintainers.concat(contributors)) {
// TODO there is an inconsistency in the rollup-plugin-license types
for (const person of contributors.concat(maintainers as unknown as Person[])) {
if (person && person.name) {
names.add(person.name);
}
Expand All @@ -24,7 +26,7 @@ function generateLicenseFile(dependencies) {
text += `By: ${Array.from(names).join(', ')}\n`;
}
if (repository) {
text += `Repository: ${repository.url || repository}\n`;
text += `Repository: ${(typeof repository === 'object' && repository.url) || repository}\n`;
}
if (licenseText) {
text +=
Expand Down Expand Up @@ -57,11 +59,14 @@ function generateLicenseFile(dependencies) {
}
}

export default function getLicenseHandler() {
export default function getLicenseHandler(): {
collectLicenses: PluginImpl;
writeLicense: PluginImpl;
} {
const licenses = new Map();
return {
collectLicenses() {
function addLicenses(dependencies) {
function addLicenses(dependencies: Dependency[]) {
for (const dependency of dependencies) {
licenses.set(dependency.name, dependency);
}
Expand All @@ -71,6 +76,7 @@ export default function getLicenseHandler() {
},
writeLicense() {
return {
name: 'write-license',
writeBundle() {
generateLicenseFile(Array.from(licenses.values()));
}
Expand Down
@@ -1,11 +1,12 @@
import path from 'path';
import { Plugin } from 'rollup';

const ID_CRYPTO = path.resolve('src/utils/crypto');
const ID_FS = path.resolve('src/utils/fs');
const ID_PATH = path.resolve('src/utils/path');
const ID_RESOLVEID = path.resolve('src/utils/resolveId');

export default function replaceBrowserModules() {
export default function replaceBrowserModules(): Plugin {
return {
name: 'replace-browser-modules',
resolveId: (source, importee) => {
Expand Down
14 changes: 11 additions & 3 deletions docs/01-command-line-reference.md
Expand Up @@ -28,6 +28,8 @@ You can also use other languages for your configuration files like TypeScript. T
rollup --config rollup.config.ts --configPlugin typescript
```

Also have a look at [Config Intellisense](guide/en/#config-intellisense) for more ways to use TypeScript typings in your config files.

Config files support the options listed below. Consult the [big list of options](guide/en/#big-list-of-options) for details on each option:

```javascript
Expand Down Expand Up @@ -208,7 +210,7 @@ export default commandLineArgs => {

#### Config Intellisense

Since Rollup ships with TypeScript typings, you can leverage your IDE's intellisense with jsdoc type hints:
Since Rollup ships with TypeScript typings, you can leverage your IDE's Intellisense with JSDoc type hints:

```javascript
// rollup.config.js
Expand All @@ -222,7 +224,7 @@ const config = {
export default config
```

Alternatively you can use the helper which should provide intellisense without the need for jsdoc annotations:defineConfig
Alternatively you can use the `defineConfig` helper, which should provide Intellisense without the need for JSDoc annotations:

```javascript
// rollup.config.js
Expand All @@ -233,7 +235,13 @@ export default defineConfig({
})
```

See also the [`--configPlugin`](guide/en/#--configplugin-plugin) for how to write your config in TypeScript.
Besides `RollupOptions` and the `defineConfig` helper that encapsulates this type, the following types can prove useful as well:

* `OutputOptions`: The `output` part of a config file
* `Plugin`: A plugin object that provides a `name` and some hooks. All hooks are fully typed to aid in plugin development.
* `PluginImpl`: A function that maps an options object to a plugin object. Most public Rollup plugins follow this pattern.

You can also directly write your config in TypeScript via the [`--configPlugin`](guide/en/#--configplugin-plugin) option.

### Differences to the JavaScript API

Expand Down
18 changes: 4 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 5 additions & 6 deletions package.json
Expand Up @@ -9,9 +9,9 @@
"rollup": "dist/bin/rollup"
},
"scripts": {
"build": "shx rm -rf dist && git rev-parse HEAD > .commithash && rollup -c && shx cp src/rollup/types.d.ts dist/rollup.d.ts && shx chmod a+x dist/bin/rollup",
"build:cjs": "shx rm -rf dist && rollup -c --configTest && shx cp src/rollup/types.d.ts dist/rollup.d.ts && shx chmod a+x dist/bin/rollup",
"build:bootstrap": "dist/bin/rollup -c && shx cp src/rollup/types.d.ts dist/rollup.d.ts && shx chmod a+x dist/bin/rollup",
"build": "shx rm -rf dist && git rev-parse HEAD > .commithash && rollup --config rollup.config.ts --configPlugin typescript && shx cp src/rollup/types.d.ts dist/rollup.d.ts && shx chmod a+x dist/bin/rollup",
"build:cjs": "shx rm -rf dist && rollup --config rollup.config.ts --configPlugin typescript --configTest && shx cp src/rollup/types.d.ts dist/rollup.d.ts && shx chmod a+x dist/bin/rollup",
"build:bootstrap": "dist/bin/rollup --config rollup.config.ts --configPlugin typescript && shx cp src/rollup/types.d.ts dist/rollup.d.ts && shx chmod a+x dist/bin/rollup",
"ci:lint": "npm run lint:nofix",
"ci:test": "npm run build:cjs && npm run build:bootstrap && npm run test:all",
"ci:test:only": "npm run build:cjs && npm run build:bootstrap && npm run test:only",
Expand All @@ -38,7 +38,7 @@
"test:only": "mocha test/test.js",
"test:typescript": "shx rm -rf test/typescript/dist && shx cp -r dist test/typescript/ && tsc --noEmit -p test/typescript && tsc --noEmit",
"test:browser": "mocha test/browser/index.js",
"watch": "rollup -cw"
"watch": "rollup --config rollup.config.ts --configPlugin typescript --watch"
},
"repository": "rollup/rollup",
"keywords": [
Expand All @@ -64,7 +64,6 @@
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.0.0",
"@rollup/plugin-replace": "^2.4.2",
"@rollup/plugin-typescript": "^8.2.1",
"@types/micromatch": "^4.0.1",
"@types/node": "^10.17.60",
"@types/require-relative": "^0.8.0",
Expand Down Expand Up @@ -104,7 +103,7 @@
"pretty-ms": "^7.0.1",
"require-relative": "^0.8.7",
"requirejs": "^2.3.6",
"rollup": "^2.51.2",
"rollup": "^2.52.0",
"rollup-plugin-license": "^2.5.0",
"rollup-plugin-string": "^3.0.0",
"rollup-plugin-terser": "^7.0.2",
Expand Down
26 changes: 15 additions & 11 deletions rollup.config.js → rollup.config.ts
Expand Up @@ -4,15 +4,16 @@ import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import resolve from '@rollup/plugin-node-resolve';
import { RollupOptions, WarningHandlerWithDefault } from 'rollup';
import { string } from 'rollup-plugin-string';
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript';
import addCliEntry from './build-plugins/add-cli-entry.js';
import addCliEntry from './build-plugins/add-cli-entry';
import conditionalFsEventsImport from './build-plugins/conditional-fsevents-import';
import emitModulePackageFile from './build-plugins/emit-module-package-file.js';
import esmDynamicImport from './build-plugins/esm-dynamic-import.js';
import emitModulePackageFile from './build-plugins/emit-module-package-file';
import esmDynamicImport from './build-plugins/esm-dynamic-import';
import getLicenseHandler from './build-plugins/generate-license-file';
import replaceBrowserModules from './build-plugins/replace-browser-modules.js';
import replaceBrowserModules from './build-plugins/replace-browser-modules';
import pkg from './package.json';

const commitHash = (function () {
Expand All @@ -24,7 +25,9 @@ const commitHash = (function () {
})();

const now = new Date(
process.env.SOURCE_DATE_EPOCH ? process.env.SOURCE_DATE_EPOCH * 1000 : new Date().getTime()
process.env.SOURCE_DATE_EPOCH
? 1000 * parseInt(process.env.SOURCE_DATE_EPOCH)
: new Date().getTime()
).toUTCString();

const banner = `/*
Expand All @@ -37,7 +40,7 @@ const banner = `/*
Released under the MIT License.
*/`;

const onwarn = warning => {
const onwarn: WarningHandlerWithDefault = warning => {
// eslint-disable-next-line no-console
console.error(
'Building Rollup produced warnings that need to be resolved. ' +
Expand Down Expand Up @@ -71,9 +74,9 @@ const nodePlugins = [
typescript()
];

export default command => {
export default (command: Record<string, unknown>): RollupOptions | RollupOptions[] => {
const { collectLicenses, writeLicense } = getLicenseHandler();
const commonJSBuild = {
const commonJSBuild: RollupOptions = {
// fsevents is a dependency of chokidar that cannot be bundled as it contains binary code
external: [
'buffer',
Expand Down Expand Up @@ -118,7 +121,8 @@ export default command => {
...nodePlugins,
addCliEntry(),
esmDynamicImport(),
!command.configTest && collectLicenses()
// TODO this relied on an unpublished type update
(!command.configTest && collectLicenses()) as Plugin
],
strictDeprecations: true,
treeshake
Expand All @@ -128,7 +132,7 @@ export default command => {
return commonJSBuild;
}

const esmBuild = {
const esmBuild: RollupOptions = {
...commonJSBuild,
input: { 'rollup.js': 'src/node-entry.ts' },
output: {
Expand All @@ -141,7 +145,7 @@ export default command => {
plugins: [...nodePlugins, emitModulePackageFile(), collectLicenses()]
};

const browserBuilds = {
const browserBuilds: RollupOptions = {
input: 'src/browser-entry.ts',
onwarn,
output: [
Expand Down
7 changes: 4 additions & 3 deletions src/rollup/types.d.ts
Expand Up @@ -277,7 +277,8 @@ export type RenderChunkHook = (
| Promise<{ code: string; map?: SourceMapInput } | null>
| { code: string; map?: SourceMapInput }
| string
| null;
| null
| undefined;

export type ResolveDynamicImportHook = (
this: PluginContext,
Expand Down Expand Up @@ -539,7 +540,7 @@ export interface InputOptions {
moduleContext?: ((id: string) => string | null | undefined) | { [id: string]: string };
onwarn?: WarningHandlerWithDefault;
perf?: boolean;
plugins?: Plugin[];
plugins?: (Plugin | null | false | undefined)[];
preserveEntrySignatures?: PreserveEntrySignaturesOption;
/** @deprecated Use the "preserveModules" output option instead. */
preserveModules?: boolean;
Expand Down Expand Up @@ -650,7 +651,7 @@ export interface OutputOptions {
noConflict?: boolean;
outro?: string | (() => string | Promise<string>);
paths?: OptionsPaths;
plugins?: OutputPlugin[];
plugins?: (OutputPlugin | null | false | undefined)[];
preferConst?: boolean;
preserveModules?: boolean;
preserveModulesRoot?: string;
Expand Down
4 changes: 3 additions & 1 deletion src/utils/ensureArray.ts
@@ -1,4 +1,6 @@
export function ensureArray<T>(items: (T | null | undefined)[] | T | null | undefined): T[] {
export function ensureArray<T>(
items: (T | false | null | undefined)[] | T | false | null | undefined
): T[] {
if (Array.isArray(items)) {
return items.filter(Boolean) as T[];
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/renderChunk.ts
Expand Up @@ -23,7 +23,7 @@ export default function renderChunk({
}): Promise<string> {
const renderChunkReducer = (
code: string,
result: { code: string; map?: SourceMapInput } | string | null,
result: { code: string; map?: SourceMapInput } | string | null | undefined,
plugin: Plugin
): string => {
if (result == null) return code;
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Expand Up @@ -9,10 +9,11 @@
"noUnusedLocals": true,
"noUnusedParameters": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"target": "es2018"
},
"include": ["typings/**/*.d.ts", "src", "cli", "browser"],
"include": ["typings/**/*.d.ts", "src", "cli", "browser", "rollup.config.ts"],
"exclude": ["dist", "node_modules", "test/typescript"]
}
9 changes: 9 additions & 0 deletions typings/declarations.d.ts
Expand Up @@ -5,6 +5,15 @@ declare module 'help.md' {
}

// external libs
declare module 'rollup-plugin-string' {
export const string: import('rollup').PluginImpl;
}

declare module 'rollup-plugin-typescript' {
const typescript: import('rollup').PluginImpl;
export default typescript;
}

declare module 'acorn-class-fields' {
const plugin: (BaseParser: typeof acorn.Parser) => typeof acorn.Parser;
export default plugin;
Expand Down