diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c288c9c30a..88b086e1a1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # rollup changelog +## 1.27.14 +*2019-12-22* + +### Bug Fixes +* Update references to official rollup plugins in error messages (#3297, #3298) + +### Pull Requests +* [#3286](https://github.com/rollup/rollup/pull/3286): Update link to JavaScript API documentation (@romankaravia) +* [#3294](https://github.com/rollup/rollup/pull/3294): Update deprecated references to the node-resolve plugin in the documentation (@Vlad-Shcherbina) +* [#3297](https://github.com/rollup/rollup/pull/3297): Update references to rollup-plugin-json (@cprecioso) +* [#3298](https://github.com/rollup/rollup/pull/3298): Update references to official rollup plugins (@cprecioso) + ## 1.27.13 *2019-12-14* diff --git a/README.md b/README.md index 557106ebb44..303e43db255 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Rollup is a module bundler for JavaScript which compiles small pieces of code in ## Quick Start Guide -Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/#command-line-reference) with an optional configuration file, or else through its [JavaScript API](https://rollupjs.org/#javascript-api). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/). +Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/#command-line-reference) with an optional configuration file, or else through its [JavaScript API](https://rollupjs.org/guide/en/#javascript-api). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/). ### Commands @@ -97,7 +97,7 @@ Because Rollup includes the bare minimum, it results in lighter, faster, and les ### Importing CommonJS -Rollup can import existing CommonJS modules [through a plugin](https://github.com/rollup/rollup-plugin-commonjs). +Rollup can import existing CommonJS modules [through a plugin](https://github.com/rollup/plugins/tree/master/packages/commonjs). ### Publishing ES Modules diff --git a/browser/path.ts b/browser/path.ts index 19be8664082..ecae1fa030f 100644 --- a/browser/path.ts +++ b/browser/path.ts @@ -28,7 +28,7 @@ export function dirname(path: string) { } export function extname(path: string) { - const match = /\.[^.]+$/.exec(basename(path) as string); + const match = /\.[^.]+$/.exec(basename(path)!); if (!match) return ''; return match[0]; } @@ -58,7 +58,7 @@ export function relative(from: string, to: string) { } export function resolve(...paths: string[]) { - let resolvedParts = (paths.shift() as string).split(/[/\\]/); + let resolvedParts = paths.shift()!.split(/[/\\]/); paths.forEach(path => { if (isAbsolute(path)) { diff --git a/cli/logging.ts b/cli/logging.ts index 0cc1206d3cd..5902ff9204c 100644 --- a/cli/logging.ts +++ b/cli/logging.ts @@ -15,8 +15,8 @@ export function handleError(err: RollupError, recover = false) { let description = err.message || err; if (err.name) description = `${err.name}: ${description}`; const message = - ((err as { plugin?: string }).plugin - ? `(plugin ${(err as { plugin?: string }).plugin}) ${description}` + (err.plugin + ? `(plugin ${(err).plugin}) ${description}` : description) || err; stderr(tc.bold.red(`[!] ${tc.bold(message.toString())}`)); @@ -26,7 +26,7 @@ export function handleError(err: RollupError, recover = false) { } if (err.loc) { - stderr(`${relativeId((err.loc.file || err.id) as string)} (${err.loc.line}:${err.loc.column})`); + stderr(`${relativeId((err.loc.file || err.id)!)} (${err.loc.line}:${err.loc.column})`); } else if (err.id) { stderr(relativeId(err.id)); } diff --git a/cli/run/build.ts b/cli/run/build.ts index e8454e20580..8182b9cce72 100644 --- a/cli/run/build.ts +++ b/cli/run/build.ts @@ -1,7 +1,7 @@ import ms from 'pretty-ms'; import tc from 'turbocolor'; import * as rollup from '../../src/node-entry'; -import { InputOptions, OutputOptions, RollupBuild, SourceMap } from '../../src/rollup/types'; +import { InputOptions, OutputOptions, RollupBuild } from '../../src/rollup/types'; import relativeId from '../../src/utils/relativeId'; import { handleError, stderr } from '../logging'; import SOURCEMAPPING_URL from '../sourceMappingUrl'; @@ -19,9 +19,9 @@ export default function build( const start = Date.now(); const files = useStdout ? ['stdout'] - : outputOptions.map(t => relativeId(t.file || (t.dir as string))); + : outputOptions.map(t => relativeId(t.file || t.dir!)); if (!silent) { - let inputFiles: string = undefined as any; + let inputFiles: string | undefined; if (typeof inputOptions.input === 'string') { inputFiles = inputOptions.input; } else if (inputOptions.input instanceof Array) { @@ -31,7 +31,7 @@ export default function build( .map(name => (inputOptions.input as Record)[name]) .join(', '); } - stderr(tc.cyan(`\n${tc.bold(inputFiles)} → ${tc.bold(files.join(', '))}...`)); + stderr(tc.cyan(`\n${tc.bold(inputFiles!)} → ${tc.bold(files.join(', '))}...`)); } return rollup @@ -54,8 +54,7 @@ export default function build( } else { source = file.code; if (output.sourcemap === 'inline') { - source += `\n//# ${SOURCEMAPPING_URL}=${(file - .map as SourceMap).toUrl()}\n`; + source += `\n//# ${SOURCEMAPPING_URL}=${file.map!.toUrl()}\n`; } } if (outputs.length > 1) @@ -66,7 +65,7 @@ export default function build( }); } - return Promise.all(outputOptions.map(output => bundle.write(output) as Promise)).then( + return Promise.all(outputOptions.map(output => bundle.write(output))).then( () => bundle ); }) diff --git a/docs/00-introduction.md b/docs/00-introduction.md index a05623b2567..daf2abc7233 100755 --- a/docs/00-introduction.md +++ b/docs/00-introduction.md @@ -12,6 +12,8 @@ Rollup is a module bundler for JavaScript which compiles small pieces of code in npm install --global rollup ``` +⚠️ If you are using TypeScript, we recommend you explicitly list the `@types` packages you want to use using the [`types` property in the "tsconfig.json" file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types), or set it to `[]`. Rollup has a dependency on `@types/node`, which means (without this change) these types will automatically be available in your app even when some of them should not be available based on the `target` you are using. + ### Quick start Rollup can be used either through a [command line interface](guide/en/#command-line-reference) with an optional configuration file, or else through its [JavaScript API](guide/en/#javascript-api). Run `rollup --help` to see the available options and parameters. @@ -80,7 +82,7 @@ Because Rollup includes the bare minimum, it results in lighter, faster, and les #### Importing CommonJS -Rollup can import existing CommonJS modules [through a plugin](https://github.com/rollup/rollup-plugin-commonjs). +Rollup can import existing CommonJS modules [through a plugin](https://github.com/rollup/plugins/tree/master/packages/commonjs). #### Publishing ES Modules diff --git a/docs/01-command-line-reference.md b/docs/01-command-line-reference.md index 9f1c1bb3be0..d9026b457d6 100755 --- a/docs/01-command-line-reference.md +++ b/docs/01-command-line-reference.md @@ -155,7 +155,7 @@ export default Promise.all([ You *must* use a configuration file in order to do any of the following: - bundle one project into multiple output files -- use Rollup plugins, such as [rollup-plugin-node-resolve](https://github.com/rollup/rollup-plugin-node-resolve) and [rollup-plugin-commonjs](https://github.com/rollup/rollup-plugin-commonjs) which let you load CommonJS modules from the Node.js ecosystem +- use Rollup plugins, such as [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve) and [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs) which let you load CommonJS modules from the Node.js ecosystem To use Rollup with a configuration file, pass the `--config` or `-c` flags. diff --git a/docs/04-tutorial.md b/docs/04-tutorial.md index ec4061266d8..34febe4b35d 100755 --- a/docs/04-tutorial.md +++ b/docs/04-tutorial.md @@ -173,7 +173,7 @@ So far, we've created a simple bundle from an entry point and a module imported For that, we use *plugins*, which change the behaviour of Rollup at key points in the bundling process. A list of awesome plugins is maintained on [the Rollup Awesome List](https://github.com/rollup/awesome). -For this tutorial, we'll use [rollup-plugin-json](https://github.com/rollup/rollup-plugin-json), which allows Rollup to import data from a JSON file. +For this tutorial, we'll use [@rollup/plugin-json](https://github.com/rollup/plugins/tree/master/packages/json), which allows Rollup to import data from a JSON file. Create a file in the project root called `package.json`, and add the following content: @@ -187,10 +187,10 @@ Create a file in the project root called `package.json`, and add the following c } ``` -Install rollup-plugin-json as a development dependency: +Install @rollup/plugin-json as a development dependency: ``` -npm install --save-dev rollup-plugin-json +npm install --save-dev @rollup/plugin-json ``` (We're using `--save-dev` rather than `--save` because our code doesn't actually depend on the plugin when it runs – only when we're building the bundle.) @@ -210,7 +210,7 @@ Edit your `rollup.config.js` file to include the JSON plugin: ```js // rollup.config.js -import json from 'rollup-plugin-json'; +import json from '@rollup/plugin-json'; export default { input: 'src/main.js', @@ -252,7 +252,7 @@ Edit your `rollup.config.js` file to add a second minified output. As format, we ```js // rollup.config.js -import json from 'rollup-plugin-json'; +import json from '@rollup/plugin-json'; import {terser} from 'rollup-plugin-terser'; export default { diff --git a/docs/06-faqs.md b/docs/06-faqs.md index eaa8142bac4..d582ce2e4df 100755 --- a/docs/06-faqs.md +++ b/docs/06-faqs.md @@ -12,7 +12,7 @@ Tree-shaking, also known as "live code inclusion," is the process of eliminating #### How do I use Rollup in Node.js with CommonJS modules? -Rollup strives to implement the specification for ES modules, not necessarily the behaviors of Node.js, NPM, `require()`, and CommonJS. Consequently, loading of CommonJS modules and use of Node's module location resolution logic are both implemented as optional plugins, not included by default in the Rollup core. Just `npm install` the [commonjs](https://github.com/rollup/rollup-plugin-commonjs) and [node-resolve](https://github.com/rollup/rollup-plugin-node-resolve) plugins and then enable them using a `rollup.config.js` file and you should be all set. If the modules import JSON files, you will also need the [json](https://github.com/rollup/rollup-plugin-json) plugin. +Rollup strives to implement the specification for ES modules, not necessarily the behaviors of Node.js, NPM, `require()`, and CommonJS. Consequently, loading of CommonJS modules and use of Node's module location resolution logic are both implemented as optional plugins, not included by default in the Rollup core. Just `npm install` the [commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs) and [node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve) plugins and then enable them using a `rollup.config.js` file and you should be all set. If the modules import JSON files, you will also need the [json](https://github.com/rollup/plugins/tree/master/packages/json) plugin. #### Why isn't node-resolve a built-in feature? diff --git a/docs/07-tools.md b/docs/07-tools.md index 011716040ec..73216284885 100755 --- a/docs/07-tools.md +++ b/docs/07-tools.md @@ -41,19 +41,19 @@ the-answer (imported by main.js) The resulting `bundle.js` will still work in Node.js, because the `import` declaration gets turned into a CommonJS `require` statement, but `the-answer` does *not* get included in the bundle. For that, we need a plugin. -#### rollup-plugin-node-resolve +#### @rollup/plugin-node-resolve -The [rollup-plugin-node-resolve](https://github.com/rollup/rollup-plugin-node-resolve) plugin teaches Rollup how to find external modules. Install it… +The [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve) plugin teaches Rollup how to find external modules. Install it… ``` -npm install --save-dev rollup-plugin-node-resolve +npm install --save-dev @rollup/plugin-node-resolve ``` …and add it to your config file: ```js // rollup.config.js -import resolve from 'rollup-plugin-node-resolve'; +import resolve from '@rollup/plugin-node-resolve'; export default { input: 'src/main.js', @@ -68,13 +68,13 @@ export default { This time, when you `npm run build`, no warning is emitted — the bundle contains the imported module. -#### rollup-plugin-commonjs +#### @rollup/plugin-commonjs Some libraries expose ES modules that you can import as-is — `the-answer` is one such module. But at the moment, the majority of packages on NPM are exposed as CommonJS modules instead. Until that changes, we need to convert CommonJS to ES2015 before Rollup can process them. -The [rollup-plugin-commonjs](https://github.com/rollup/rollup-plugin-commonjs) plugin does exactly that. +The [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs) plugin does exactly that. -Note that `rollup-plugin-commonjs` should go *before* other plugins that transform your modules — this is to prevent other plugins from making changes that break the CommonJS detection. +Note that `@rollup/plugin-commonjs` should go *before* other plugins that transform your modules — this is to prevent other plugins from making changes that break the CommonJS detection. ### Peer dependencies @@ -92,7 +92,7 @@ Here is the config file: ```js // rollup.config.js -import resolve from 'rollup-plugin-node-resolve'; +import resolve from '@rollup/plugin-node-resolve'; export default { input: 'src/main.js', @@ -138,14 +138,14 @@ Many developers use [Babel](https://babeljs.io/) in their projects in order to u The easiest way to use both Babel and Rollup is with [rollup-plugin-babel](https://github.com/rollup/rollup-plugin-babel). First, install the plugin: ``` -npm i -D rollup-plugin-babel rollup-plugin-node-resolve +npm i -D rollup-plugin-babel @rollup/plugin-node-resolve ``` Add it to `rollup.config.js`: ```js // rollup.config.js -import resolve from 'rollup-plugin-node-resolve'; +import resolve from '@rollup/plugin-node-resolve'; import babel from 'rollup-plugin-babel'; export default { @@ -221,7 +221,7 @@ The syntax is very similar to the configuration file, but the properties are spl ```js const gulp = require('gulp'); const rollup = require('rollup'); -const rollupTypescript = require('rollup-plugin-typescript'); +const rollupTypescript = require('@rollup/plugin-typescript'); gulp.task('build', () => { return rollup.rollup({ @@ -245,7 +245,7 @@ You may also use the `async/await` syntax: ```js const gulp = require('gulp'); const rollup = require('rollup'); -const rollupTypescript = require('rollup-plugin-typescript'); +const rollupTypescript = require('@rollup/plugin-typescript'); gulp.task('build', async function () { const bundle = await rollup.rollup({ diff --git a/docs/08-troubleshooting.md b/docs/08-troubleshooting.md index ac4f35679cb..07066415bf0 100644 --- a/docs/08-troubleshooting.md +++ b/docs/08-troubleshooting.md @@ -52,7 +52,7 @@ Occasionally you will see an error message like this: Import declarations must have corresponding export declarations in the imported module. For example, if you have `import a from './a.js'` in a module, and a.js doesn't have an `export default` declaration, or `import {foo} from './b.js'`, and b.js doesn't export `foo`, Rollup cannot bundle the code. -This error frequently occurs with CommonJS modules converted by [rollup-plugin-commonjs](https://github.com/rollup/rollup-plugin-commonjs), which makes a reasonable attempt to generate named exports from the CommonJS code but won't always succeed, because the freewheeling nature of CommonJS is at odds with the rigorous approach we benefit from in JavaScript modules. It can be solved by using the [namedExports](https://github.com/rollup/rollup-plugin-commonjs#custom-named-exports) option, which allows you to manually fill in the information gaps. +This error frequently occurs with CommonJS modules converted by [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs), which makes a reasonable attempt to generate named exports from the CommonJS code but won't always succeed, because the freewheeling nature of CommonJS is at odds with the rigorous approach we benefit from in JavaScript modules. It can be solved by using the [namedExports](https://github.com/rollup/plugins/tree/master/packages/commonjs#custom-named-exports) option, which allows you to manually fill in the information gaps. ### Error: "this is undefined" @@ -89,6 +89,6 @@ export default { }; ``` -If you *do* want to include the module in your bundle, you need to tell Rollup how to find it. In most cases, this is a question of using [rollup-plugin-node-resolve](https://github.com/rollup/rollup-plugin-node-resolve). +If you *do* want to include the module in your bundle, you need to tell Rollup how to find it. In most cases, this is a question of using [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve). Some modules, like `events` or `util`, are built in to Node.js. If you want to include those (for example, so that your bundle runs in the browser), you may need to include [rollup-plugin-node-builtins](https://github.com/calvinmetcalf/rollup-plugin-node-builtins). diff --git a/docs/999-big-list-of-options.md b/docs/999-big-list-of-options.md index 49ef0472435..0059c5841d0 100755 --- a/docs/999-big-list-of-options.md +++ b/docs/999-big-list-of-options.md @@ -262,8 +262,8 @@ See [Using plugins](guide/en/#using-plugins) for more information on how to use ```js // rollup.config.js -import resolve from 'rollup-plugin-node-resolve'; -import commonjs from 'rollup-plugin-commonjs'; +import resolve from '@rollup/plugin-node-resolve'; +import commonjs from '@rollup/plugin-commonjs'; const isProduction = process.env.NODE_ENV === 'production'; @@ -325,7 +325,7 @@ Type: `{ [chunkAlias: string]: string[] } | ((id: string) => string | void)` Allows the creation of custom shared common chunks. When using the object form, each property represents a chunk that contains the listed modules and all their dependencies if they are part of the module graph unless they are already in another manual chunk. The name of the chunk will be determined by the property key. -Note that it is not necessary for the listed modules themselves to be be part of the module graph, which is useful if you are working with `rollup-plugin-node-resolve` and use deep imports from packages. For instance +Note that it is not necessary for the listed modules themselves to be be part of the module graph, which is useful if you are working with `@rollup/plugin-node-resolve` and use deep imports from packages. For instance ``` manualChunks: { diff --git a/package-lock.json b/package-lock.json index 9edc582c2aa..cc360c9f50f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "rollup", - "version": "1.27.13", + "version": "1.27.14", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 84c39c8a3ae..cef45c103d3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "rollup", - "version": "1.27.13", + "version": "1.27.14", "description": "Next-generation ES module bundler", "main": "dist/rollup.js", "module": "dist/rollup.es.js", diff --git a/src/Chunk.ts b/src/Chunk.ts index 550f3bb4d34..96941bc4f5a 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -89,7 +89,7 @@ const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx']; function getGlobalName( module: ExternalModule, - globals: GlobalsOption, + globals: GlobalsOption | undefined, graph: Graph, hasExports: boolean ) { @@ -130,7 +130,7 @@ export default class Chunk { if (!facadedModule.facadeChunk) { facadedModule.facadeChunk = chunk; } - chunk.dependencies = [facadedModule.chunk as Chunk]; + chunk.dependencies = [facadedModule.chunk!]; chunk.dynamicDependencies = []; chunk.facadeModule = facadedModule; for (const exportName of facadedModule.getAllExportNames()) { @@ -662,7 +662,7 @@ export default class Chunk { if (dep instanceof ExternalModule && !dep.renormalizeRenderPath) continue; const renderedDependency = this.renderedDeclarations.dependencies[i]; - const depId = dep instanceof ExternalModule ? renderedDependency.id : (dep.id as string); + const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id!; if (dep instanceof Chunk) renderedDependency.namedExportsMode = dep.exportMode !== 'default'; renderedDependency.id = this.getRelativePath(depId); } @@ -673,7 +673,7 @@ export default class Chunk { const hasExports = this.renderedDeclarations.exports.length !== 0 || this.renderedDeclarations.dependencies.some( - dep => (dep.reexports && dep.reexports.length !== 0) as boolean + dep => (dep.reexports && dep.reexports.length !== 0)! ); let usesTopLevelAwait = false; @@ -700,19 +700,19 @@ export default class Chunk { } const magicString = finalise( - this.renderedSource as MagicStringBundle, + this.renderedSource!, { accessedGlobals, dependencies: this.renderedDeclarations.dependencies, exports: this.renderedDeclarations.exports, hasExports, indentString: this.indentString, - intro: addons.intro as string, + intro: addons.intro!, isEntryModuleFacade: this.graph.preserveModules || (this.facadeModule !== null && this.facadeModule.isEntryPoint), namedExportsMode: this.exportMode !== 'default', - outro: addons.outro as string, + outro: addons.outro!, usesTopLevelAwait, varOrConst: options.preferConst ? 'const' : 'var', warn: this.graph.warn.bind(this.graph) @@ -741,8 +741,8 @@ export default class Chunk { let file: string; if (options.file) file = resolve(options.sourcemapFile || options.file); - else if (options.dir) file = resolve(options.dir, this.id as string); - else file = resolve(this.id as string); + else if (options.dir) file = resolve(options.dir, this.id!); + else file = resolve(this.id!); const decodedMap = magicString.generateDecodedMap({}); map = collapseSourcemaps( @@ -751,7 +751,7 @@ export default class Chunk { decodedMap, this.usedModules, chunkSourcemapChain, - options.sourcemapExcludeSources as boolean + options.sourcemapExcludeSources! ); map.sources = map.sources.map(sourcePath => normalize( @@ -810,7 +810,7 @@ export default class Chunk { } let dependency: Chunk | ExternalModule; if (depModule instanceof Module) { - dependency = depModule.chunk as Chunk; + dependency = depModule.chunk!; } else { if (!(depModule.used || depModule.moduleSideEffects)) { continue; @@ -887,11 +887,11 @@ export default class Chunk { for (const { node, resolution } of module.dynamicImports) { if (!resolution) continue; if (resolution instanceof Module) { - if (resolution.chunk !== this && isChunkRendered(resolution.chunk as Chunk)) { - const resolutionChunk = resolution.facadeChunk || (resolution.chunk as Chunk); + if (resolution.chunk !== this && isChunkRendered(resolution.chunk!)) { + const resolutionChunk = resolution.facadeChunk || resolution.chunk!; node.renderFinalResolution( code, - `'${this.getRelativePath(resolutionChunk.id as string)}'`, + `'${this.getRelativePath(resolutionChunk.id!)}'`, format ); } @@ -915,7 +915,7 @@ export default class Chunk { private finaliseImportMetas(format: string, outputPluginDriver: PluginDriver): void { for (const [module, code] of this.renderedModuleSources) { for (const importMeta of module.importMetas) { - importMeta.renderFinalMechanism(code, this.id as string, format, outputPluginDriver); + importMeta.renderFinalMechanism(code, this.id!, format, outputPluginDriver); } } } @@ -937,7 +937,7 @@ export default class Chunk { // skip local exports if (!module || module.chunk === this) continue; if (module instanceof Module) { - exportChunk = module.chunk as Chunk; + exportChunk = module.chunk!; importName = exportChunk.getVariableExportName(variable); needsLiveBinding = variable.isReassigned; } else { @@ -970,7 +970,7 @@ export default class Chunk { imported: variable.module instanceof ExternalModule ? variable.name - : ((variable.module as Module).chunk as Chunk).getVariableExportName(variable), + : variable.module!.chunk!.getVariableExportName(variable), local: variable.getName() }); } @@ -996,10 +996,10 @@ export default class Chunk { if (options.format === 'umd' || options.format === 'iife') { globalName = getGlobalName( dep, - options.globals as GlobalsOption, + options.globals, this.graph, exportsNames || exportsDefault - ) as string; + )!; } } @@ -1071,7 +1071,7 @@ export default class Chunk { } private getRelativePath(targetPath: string): string { - const relativePath = normalize(relative(dirname(this.id as string), targetPath)); + const relativePath = normalize(relative(dirname(this.id!), targetPath)); return relativePath.startsWith('../') ? relativePath : './' + relativePath; } @@ -1096,7 +1096,7 @@ export default class Chunk { const namespace = resolution.getOrCreateNamespace(); node.setResolution('named', namespace); } else { - node.setResolution((resolution.chunk as Chunk).exportMode); + node.setResolution(resolution.chunk!.exportMode); } } else { node.setResolution('auto'); @@ -1167,7 +1167,7 @@ export default class Chunk { if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { - (variable.module.chunk as Chunk).exports.add(variable); + variable.module.chunk!.exports.add(variable); } } } @@ -1191,7 +1191,7 @@ export default class Chunk { if ((variable.module as Module).chunk !== this) { this.imports.add(variable); if (variable.module instanceof Module) { - (variable.module.chunk as Chunk).exports.add(variable); + variable.module.chunk!.exports.add(variable); } } } diff --git a/src/ExternalModule.ts b/src/ExternalModule.ts index 5511a26d84f..0830e18176e 100644 --- a/src/ExternalModule.ts +++ b/src/ExternalModule.ts @@ -30,7 +30,7 @@ export default class ExternalModule { this.moduleSideEffects = moduleSideEffects; const parts = id.split(/[\\/]/); - this.variableName = makeLegal(parts.pop() as string); + this.variableName = makeLegal(parts.pop()!); this.nameSuggestions = Object.create(null); this.declarations = Object.create(null); diff --git a/src/Graph.ts b/src/Graph.ts index 68fbf33f3f4..b5f20987a65 100644 --- a/src/Graph.ts +++ b/src/Graph.ts @@ -9,13 +9,10 @@ import ExternalModule from './ExternalModule'; import Module, { defaultAcornOptions } from './Module'; import { ModuleLoader, UnresolvedModule } from './ModuleLoader'; import { - ExternalOption, GetManualChunk, InputOptions, ManualChunksOption, ModuleJSON, - ModuleSideEffectsOption, - PureModulesOption, RollupCache, RollupWarning, RollupWatcher, @@ -103,31 +100,29 @@ export default class Graph { for (const key of Object.keys(cache)) cache[key][0]++; } } - this.preserveModules = options.preserveModules as boolean; - this.strictDeprecations = options.strictDeprecations as boolean; + this.preserveModules = options.preserveModules!; + this.strictDeprecations = options.strictDeprecations!; - this.cacheExpiry = options.experimentalCacheExpiry as number; + this.cacheExpiry = options.experimentalCacheExpiry!; if (options.treeshake !== false) { - this.treeshakingOptions = options.treeshake - ? { - annotations: (options.treeshake as TreeshakingOptions).annotations !== false, - moduleSideEffects: (options.treeshake as TreeshakingOptions).moduleSideEffects, - propertyReadSideEffects: - (options.treeshake as TreeshakingOptions).propertyReadSideEffects !== false, - pureExternalModules: (options.treeshake as TreeshakingOptions).pureExternalModules, - tryCatchDeoptimization: - (options.treeshake as TreeshakingOptions).tryCatchDeoptimization !== false, - unknownGlobalSideEffects: - (options.treeshake as TreeshakingOptions).unknownGlobalSideEffects !== false - } - : { - annotations: true, - moduleSideEffects: true, - propertyReadSideEffects: true, - tryCatchDeoptimization: true, - unknownGlobalSideEffects: true - }; + this.treeshakingOptions = + options.treeshake && options.treeshake !== true + ? { + annotations: options.treeshake.annotations !== false, + moduleSideEffects: options.treeshake.moduleSideEffects, + propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false, + pureExternalModules: options.treeshake.pureExternalModules, + tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false, + unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false + } + : { + annotations: true, + moduleSideEffects: true, + propertyReadSideEffects: true, + tryCatchDeoptimization: true, + unknownGlobalSideEffects: true + }; if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') { this.warnDeprecation( `The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, @@ -145,7 +140,7 @@ export default class Graph { this.pluginDriver = new PluginDriver( this, - options.plugins as Plugin[], + options.plugins!, this.pluginCache, options.preserveSymlinks === true, watcher @@ -182,7 +177,7 @@ export default class Graph { acornPluginsToInject.push(injectImportMeta, injectExportNsFrom); if (options.experimentalTopLevelAwait) { - (this.acornOptions as any).allowAwaitOutsideFunction = true; + this.acornOptions.allowAwaitOutsideFunction = true; } const acornInjectPlugins = options.acornInjectPlugins; @@ -193,19 +188,15 @@ export default class Graph { ? [acornInjectPlugins] : []) ); - this.acornParser = acorn.Parser.extend(...acornPluginsToInject) as any; + this.acornParser = acorn.Parser.extend(...acornPluginsToInject); this.moduleLoader = new ModuleLoader( this, this.moduleById, this.pluginDriver, - options.external as ExternalOption, + options.external!, (typeof options.manualChunks === 'function' && options.manualChunks) as GetManualChunk | null, - (this.treeshakingOptions - ? this.treeshakingOptions.moduleSideEffects - : null) as ModuleSideEffectsOption, - (this.treeshakingOptions - ? this.treeshakingOptions.pureExternalModules - : false) as PureModulesOption + (this.treeshakingOptions ? this.treeshakingOptions.moduleSideEffects : null)!, + (this.treeshakingOptions ? this.treeshakingOptions.pureExternalModules : false)! ); } @@ -366,9 +357,7 @@ export default class Graph { if (warning.plugin) str += `(${warning.plugin} plugin) `; if (warning.loc) - str += `${relativeId(warning.loc.file as string)} (${warning.loc.line}:${ - warning.loc.column - }) `; + str += `${relativeId(warning.loc.file!)} (${warning.loc.line}:${warning.loc.column}) `; str += warning.message; return str; diff --git a/src/Module.ts b/src/Module.ts index 6124b2dce5d..790af80d82f 100644 --- a/src/Module.ts +++ b/src/Module.ts @@ -131,7 +131,7 @@ function tryParse(module: Module, Parser: typeof acorn.Parser, acornOptions: aco } catch (err) { let message = err.message.replace(/ \(\d+:\d+\)$/, ''); if (module.id.endsWith('.json')) { - message += ' (Note that you need rollup-plugin-json to import JSON files)'; + message += ' (Note that you need @rollup/plugin-json to import JSON files)'; } else if (!module.id.endsWith('.js')) { message += ' (Note that you need plugins to import files that are not JavaScript)'; } @@ -158,7 +158,7 @@ function handleMissingExport( message: `'${exportName}' is not exported by ${relativeId(importedModule)}`, url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module` }, - importerStart as number + importerStart! ); } @@ -566,7 +566,7 @@ export default class Module { const fileName = this.id; this.magicString = new MagicString(code, { - filename: (this.excludeFromSourcemap ? null : fileName) as string, // don't include plugin helpers in sourcemap + filename: (this.excludeFromSourcemap ? null : fileName)!, // don't include plugin helpers in sourcemap indentExclusionRanges: [] }); this.removeExistingSourceMap(); @@ -578,8 +578,7 @@ export default class Module { addExport: this.addExport.bind(this), addImport: this.addImport.bind(this), addImportMeta: this.addImportMeta.bind(this), - annotations: (this.graph.treeshakingOptions && - this.graph.treeshakingOptions.annotations) as boolean, + annotations: (this.graph.treeshakingOptions && this.graph.treeshakingOptions.annotations)!, code, // Only needed for debugging deoptimizationTracker: this.graph.deoptimizationTracker, error: this.error.bind(this), @@ -599,14 +598,14 @@ export default class Module { nodeConstructors, preserveModules: this.graph.preserveModules, propertyReadSideEffects: (!this.graph.treeshakingOptions || - this.graph.treeshakingOptions.propertyReadSideEffects) as boolean, + this.graph.treeshakingOptions.propertyReadSideEffects)!, traceExport: this.getVariableForExportName.bind(this), traceVariable: this.traceVariable.bind(this), treeshake: !!this.graph.treeshakingOptions, tryCatchDeoptimization: (!this.graph.treeshakingOptions || - this.graph.treeshakingOptions.tryCatchDeoptimization) as boolean, + this.graph.treeshakingOptions.tryCatchDeoptimization)!, unknownGlobalSideEffects: (!this.graph.treeshakingOptions || - this.graph.treeshakingOptions.unknownGlobalSideEffects) as boolean, + this.graph.treeshakingOptions.unknownGlobalSideEffects)!, usesTopLevelAwait: false, warn: this.warn.bind(this), warnDeprecation: this.graph.warnDeprecation.bind(this.graph) @@ -647,7 +646,7 @@ export default class Module { if (name in this.importDescriptions) { const importDeclaration = this.importDescriptions[name]; - const otherModule = importDeclaration.module as Module | ExternalModule; + const otherModule = importDeclaration.module!; if (otherModule instanceof Module && importDeclaration.name === '*') { return otherModule.getOrCreateNamespace(); diff --git a/src/ModuleLoader.ts b/src/ModuleLoader.ts index 9c6e21f8256..faafbc9ac50 100644 --- a/src/ModuleLoader.ts +++ b/src/ModuleLoader.ts @@ -338,11 +338,11 @@ export class ModuleLoader { const exportAllModule = this.modulesById.get(id); if (exportAllModule instanceof ExternalModule) continue; - for (const name in (exportAllModule as Module).exportsAll) { + for (const name in exportAllModule!.exportsAll) { if (name in module.exportsAll) { - this.graph.warn(errNamespaceConflict(name, module, exportAllModule as Module)); + this.graph.warn(errNamespaceConflict(name, module, exportAllModule!)); } else { - module.exportsAll[name] = (exportAllModule as Module).exportsAll[name]; + module.exportsAll[name] = exportAllModule!.exportsAll[name]; } } } diff --git a/src/ast/nodes/CallExpression.ts b/src/ast/nodes/CallExpression.ts index e510d5e1ab7..705362ffe88 100644 --- a/src/ast/nodes/CallExpression.ts +++ b/src/ast/nodes/CallExpression.ts @@ -164,7 +164,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt const trackedExpressions = context.accessed.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenAccessedAtPath(path, context); + return this.returnExpression!.hasEffectsWhenAccessedAtPath(path, context); } hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext): boolean { @@ -172,7 +172,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt const trackedExpressions = context.assigned.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenAssignedAtPath(path, context); + return this.returnExpression!.hasEffectsWhenAssignedAtPath(path, context); } hasEffectsWhenCalledAtPath( @@ -186,11 +186,7 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt ).getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenCalledAtPath( - path, - callOptions, - context - ); + return this.returnExpression!.hasEffectsWhenCalledAtPath(path, callOptions, context); } include(context: InclusionContext, includeChildrenRecursively: IncludeChildren) { @@ -208,8 +204,8 @@ export default class CallExpression extends NodeBase implements DeoptimizableEnt this.callee.include(context, false); } this.callee.includeCallArguments(context, this.arguments); - if (!(this.returnExpression as ExpressionEntity).included) { - (this.returnExpression as ExpressionEntity).include(context, false); + if (!this.returnExpression!.included) { + this.returnExpression!.include(context, false); } } diff --git a/src/ast/nodes/ExportAllDeclaration.ts b/src/ast/nodes/ExportAllDeclaration.ts index b7cb6b7c7b7..d33eb26c1d4 100644 --- a/src/ast/nodes/ExportAllDeclaration.ts +++ b/src/ast/nodes/ExportAllDeclaration.ts @@ -18,10 +18,7 @@ export default class ExportAllDeclaration extends NodeBase { } render(code: MagicString, _options: RenderOptions, nodeRenderOptions?: NodeRenderOptions) { - code.remove( - (nodeRenderOptions as NodeRenderOptions).start as number, - (nodeRenderOptions as NodeRenderOptions).end as number - ); + code.remove(nodeRenderOptions!.start!, nodeRenderOptions!.end!); } } diff --git a/src/ast/nodes/Identifier.ts b/src/ast/nodes/Identifier.ts index 9a94c48f8e1..2187d0952d0 100644 --- a/src/ast/nodes/Identifier.ts +++ b/src/ast/nodes/Identifier.ts @@ -78,7 +78,7 @@ export default class Identifier extends NodeBase implements PatternNode { if (path.length === 0 && !this.scope.contains(this.name)) { this.disallowImportReassignment(); } - (this.variable as Variable).deoptimizePath(path); + this.variable!.deoptimizePath(path); } getLiteralValueAtPath( @@ -87,7 +87,7 @@ export default class Identifier extends NodeBase implements PatternNode { origin: DeoptimizableEntity ): LiteralValueOrUnknown { if (!this.bound) this.bind(); - return (this.variable as Variable).getLiteralValueAtPath(path, recursionTracker, origin); + return this.variable!.getLiteralValueAtPath(path, recursionTracker, origin); } getReturnExpressionWhenCalledAtPath( @@ -96,11 +96,7 @@ export default class Identifier extends NodeBase implements PatternNode { origin: DeoptimizableEntity ) { if (!this.bound) this.bind(); - return (this.variable as Variable).getReturnExpressionWhenCalledAtPath( - path, - recursionTracker, - origin - ); + return this.variable!.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin); } hasEffects(): boolean { @@ -137,7 +133,7 @@ export default class Identifier extends NodeBase implements PatternNode { } includeCallArguments(context: InclusionContext, args: (ExpressionNode | SpreadElement)[]): void { - (this.variable as Variable).includeCallArguments(context, args); + this.variable!.includeCallArguments(context, args); } render( diff --git a/src/ast/nodes/IfStatement.ts b/src/ast/nodes/IfStatement.ts index 1edcc537e04..615fb1c3951 100644 --- a/src/ast/nodes/IfStatement.ts +++ b/src/ast/nodes/IfStatement.ts @@ -63,9 +63,7 @@ export default class IfStatement extends StatementBase implements DeoptimizableE ? this.alternate === null || !this.alternate.included : !this.consequent.included) ) { - const singleRetainedBranch = (this.testValue - ? this.consequent - : this.alternate) as StatementNode; + const singleRetainedBranch = (this.testValue ? this.consequent : this.alternate)!; code.remove(this.start, singleRetainedBranch.start); code.remove(singleRetainedBranch.end, this.end); removeAnnotations(this, code); diff --git a/src/ast/nodes/ImportDeclaration.ts b/src/ast/nodes/ImportDeclaration.ts index 6a7de851669..450381bad86 100644 --- a/src/ast/nodes/ImportDeclaration.ts +++ b/src/ast/nodes/ImportDeclaration.ts @@ -24,10 +24,7 @@ export default class ImportDeclaration extends NodeBase { } render(code: MagicString, _options: RenderOptions, nodeRenderOptions?: NodeRenderOptions) { - code.remove( - (nodeRenderOptions as NodeRenderOptions).start as number, - (nodeRenderOptions as NodeRenderOptions).end as number - ); + code.remove(nodeRenderOptions!.start!, nodeRenderOptions!.end!); } } diff --git a/src/ast/nodes/Literal.ts b/src/ast/nodes/Literal.ts index 29f575f52bb..7672d684bbc 100644 --- a/src/ast/nodes/Literal.ts +++ b/src/ast/nodes/Literal.ts @@ -16,7 +16,7 @@ import { NodeBase } from './shared/Node'; export type LiteralValue = string | boolean | null | number | RegExp | undefined; -export default class Literal extends NodeBase { +export default class Literal extends NodeBase { type!: NodeType.tLiteral; value!: T; @@ -33,7 +33,7 @@ export default class Literal extends NodeBase { ) { return UnknownValue; } - return this.value as any; + return this.value; } getReturnExpressionWhenCalledAtPath(path: ObjectPath) { diff --git a/src/ast/nodes/MemberExpression.ts b/src/ast/nodes/MemberExpression.ts index 099a1c3a274..ce0dd89a6e8 100644 --- a/src/ast/nodes/MemberExpression.ts +++ b/src/ast/nodes/MemberExpression.ts @@ -89,23 +89,17 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE const path = getPathIfNotComputed(this); const baseVariable = path && this.scope.findVariable(path[0].key); if (baseVariable && baseVariable.isNamespace) { - const resolvedVariable = this.resolveNamespaceVariables( - baseVariable, - (path as PathWithPositions).slice(1) - ); + const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path!.slice(1)); if (!resolvedVariable) { super.bind(); } else if (typeof resolvedVariable === 'string') { this.replacement = resolvedVariable; } else { if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) { - resolvedVariable.module.suggestName((path as PathWithPositions)[0].key); + resolvedVariable.module.suggestName(path![0].key); } this.variable = resolvedVariable; - this.scope.addNamespaceMemberAccess( - getStringFromPath(path as PathWithPositions), - resolvedVariable - ); + this.scope.addNamespaceMemberAccess(getStringFromPath(path!), resolvedVariable); } } else { super.bind(); @@ -181,7 +175,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE this.property.hasEffects(context) || this.object.hasEffects(context) || (this.context.propertyReadSideEffects && - this.object.hasEffectsWhenAccessedAtPath([this.propertyKey as ObjectPathKey], context)) + this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!], context)) ); } @@ -190,20 +184,14 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.variable !== null) { return this.variable.hasEffectsWhenAccessedAtPath(path, context); } - return this.object.hasEffectsWhenAccessedAtPath( - [this.propertyKey as ObjectPathKey, ...path], - context - ); + return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey!, ...path], context); } hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext): boolean { if (this.variable !== null) { return this.variable.hasEffectsWhenAssignedAtPath(path, context); } - return this.object.hasEffectsWhenAssignedAtPath( - [this.propertyKey as ObjectPathKey, ...path], - context - ); + return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey!, ...path], context); } hasEffectsWhenCalledAtPath( @@ -215,7 +203,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context); } return this.object.hasEffectsWhenCalledAtPath( - [this.propertyKey as ObjectPathKey, ...path], + [this.propertyKey!, ...path], callOptions, context ); @@ -254,7 +242,7 @@ export default class MemberExpression extends NodeBase implements DeoptimizableE if (this.variable || this.replacement) { let replacement = this.variable ? this.variable.getName() : this.replacement; if (isCalleeOfDifferentParent) replacement = '0, ' + replacement; - code.overwrite(this.start, this.end, replacement as string, { + code.overwrite(this.start, this.end, replacement!, { contentOnly: true, storeName: true }); diff --git a/src/ast/nodes/MetaProperty.ts b/src/ast/nodes/MetaProperty.ts index 25bd4aebe1d..7a9d68674fe 100644 --- a/src/ast/nodes/MetaProperty.ts +++ b/src/ast/nodes/MetaProperty.ts @@ -114,7 +114,7 @@ export default class MetaProperty extends NodeBase { fileName, format, moduleId: this.context.module.id, - referenceId: referenceId || assetReferenceId || (chunkReferenceId as string), + referenceId: referenceId || assetReferenceId || chunkReferenceId!, relativePath } ]); diff --git a/src/ast/nodes/ObjectExpression.ts b/src/ast/nodes/ObjectExpression.ts index 338b8b546ac..c0c2097bf7d 100644 --- a/src/ast/nodes/ObjectExpression.ts +++ b/src/ast/nodes/ObjectExpression.ts @@ -137,7 +137,7 @@ export default class ObjectExpression extends NodeBase implements DeoptimizableE } else { this.expressionsToBeDeoptimized.set(key, [origin]); } - return (propertyMap[key].exactMatchRead as Property).getLiteralValueAtPath( + return propertyMap[key].exactMatchRead!.getLiteralValueAtPath( path.slice(1), recursionTracker, origin @@ -181,7 +181,7 @@ export default class ObjectExpression extends NodeBase implements DeoptimizableE } else { this.expressionsToBeDeoptimized.set(key, [origin]); } - return (propertyMap[key].exactMatchRead as Property).getReturnExpressionWhenCalledAtPath( + return propertyMap[key].exactMatchRead!.getReturnExpressionWhenCalledAtPath( path.slice(1), recursionTracker, origin diff --git a/src/ast/nodes/Property.ts b/src/ast/nodes/Property.ts index 6354bc9522b..a154f47a2ac 100644 --- a/src/ast/nodes/Property.ts +++ b/src/ast/nodes/Property.ts @@ -93,8 +93,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { trackedExpressions.add(this); return ( this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) || - (path.length > 0 && - (this.returnExpression as ExpressionEntity).hasEffectsWhenAccessedAtPath(path, context)) + (path.length > 0 && this.returnExpression!.hasEffectsWhenAccessedAtPath(path, context)) ); } return this.value.hasEffectsWhenAccessedAtPath(path, context); @@ -105,10 +104,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { const trackedExpressions = context.assigned.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenAssignedAtPath( - path, - context - ); + return this.returnExpression!.hasEffectsWhenAssignedAtPath(path, context); } if (this.kind === 'set') { const trackedExpressions = context.assigned.getEntities(path); @@ -131,11 +127,7 @@ export default class Property extends NodeBase implements DeoptimizableEntity { ).getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.returnExpression as ExpressionEntity).hasEffectsWhenCalledAtPath( - path, - callOptions, - context - ); + return this.returnExpression!.hasEffectsWhenCalledAtPath(path, callOptions, context); } return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context); } diff --git a/src/ast/nodes/SwitchCase.ts b/src/ast/nodes/SwitchCase.ts index 376f72cb521..8baef42daeb 100644 --- a/src/ast/nodes/SwitchCase.ts +++ b/src/ast/nodes/SwitchCase.ts @@ -40,13 +40,7 @@ export default class SwitchCase extends NodeBase { ? this.test.end : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7; const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1; - renderStatementList( - this.consequent, - code, - consequentStart, - (nodeRenderOptions as NodeRenderOptions).end as number, - options - ); + renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions!.end!, options); } else { super.render(code, options); } diff --git a/src/ast/nodes/TaggedTemplateExpression.ts b/src/ast/nodes/TaggedTemplateExpression.ts index 079b883e955..64eb23c98f3 100644 --- a/src/ast/nodes/TaggedTemplateExpression.ts +++ b/src/ast/nodes/TaggedTemplateExpression.ts @@ -16,19 +16,20 @@ export default class TaggedTemplateExpression extends NodeBase { bind() { super.bind(); if (this.tag.type === NodeType.Identifier) { - const variable = this.scope.findVariable((this.tag as Identifier).name); + const name = (this.tag as Identifier).name; + const variable = this.scope.findVariable(name); if (variable.isNamespace) { this.context.error( { code: 'CANNOT_CALL_NAMESPACE', - message: `Cannot call a namespace ('${(this.tag as Identifier).name}')` + message: `Cannot call a namespace ('${name}')` }, this.start ); } - if ((this.tag as Identifier).name === 'eval') { + if (name === 'eval') { this.context.warn( { code: 'EVAL', diff --git a/src/ast/nodes/VariableDeclaration.ts b/src/ast/nodes/VariableDeclaration.ts index 88208238f17..f8955a56258 100644 --- a/src/ast/nodes/VariableDeclaration.ts +++ b/src/ast/nodes/VariableDeclaration.ts @@ -22,7 +22,7 @@ function areAllDeclarationsIncludedAndNotExported(declarations: VariableDeclarat for (const declarator of declarations) { if (!declarator.included) return false; if (declarator.id.type === NodeType.Identifier) { - if ((declarator.id.variable as Variable).exportName) return false; + if (declarator.id.variable!.exportName) return false; } else { const exportedVariables: Variable[] = []; declarator.id.addExportedVariables(exportedVariables); @@ -138,7 +138,7 @@ export default class VariableDeclaration extends NodeBase { this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0) ); - let actualContentEnd, renderedContentEnd; + let actualContentEnd: number | undefined, renderedContentEnd: number; if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) { renderedContentEnd = this.start + this.kind.length; } else { @@ -176,11 +176,10 @@ export default class VariableDeclaration extends NodeBase { if (options.format === 'system' && node.init !== null) { if (node.id.type !== NodeType.Identifier) { node.id.addExportedVariables(systemPatternExports); - } else if ((node.id.variable as Variable).exportName) { + } else if (node.id.variable!.exportName) { code.prependLeft( code.original.indexOf('=', node.id.end) + 1, - ` exports('${(node.id.variable as Variable).safeExportName || - (node.id.variable as Variable).exportName}',` + ` exports('${node.id.variable!.safeExportName || node.id.variable!.exportName}',` ); nextSeparatorString += ')'; } @@ -205,7 +204,7 @@ export default class VariableDeclaration extends NodeBase { actualContentEnd = contentEnd; renderedContentEnd = end; hasRenderedContent = true; - lastSeparatorPos = separator as number; + lastSeparatorPos = separator!; separatorString = nextSeparatorString; } if (hasRenderedContent) { @@ -213,7 +212,7 @@ export default class VariableDeclaration extends NodeBase { code, separatorString, lastSeparatorPos, - actualContentEnd as number, + actualContentEnd!, renderedContentEnd, !isNoStatement, systemPatternExports diff --git a/src/ast/scopes/ReturnValueScope.ts b/src/ast/scopes/ReturnValueScope.ts index 51975004fec..8647cd299ba 100644 --- a/src/ast/scopes/ReturnValueScope.ts +++ b/src/ast/scopes/ReturnValueScope.ts @@ -13,7 +13,7 @@ export default class ReturnValueScope extends ParameterScope { getReturnExpression(): ExpressionEntity { if (this.returnExpression === null) this.updateReturnExpression(); - return this.returnExpression as ExpressionEntity; + return this.returnExpression!; } private updateReturnExpression() { diff --git a/src/ast/values.ts b/src/ast/values.ts index 3f563c5928d..f2c179ac2c8 100644 --- a/src/ast/values.ts +++ b/src/ast/values.ts @@ -440,7 +440,7 @@ const literalStringMembers: MemberDescriptions = assembleMemberDescriptions( objectMembers ); -export function getLiteralMembersForValue(value: T) { +export function getLiteralMembersForValue(value: T) { switch (typeof value) { case 'boolean': return literalBooleanMembers; @@ -467,7 +467,7 @@ export function hasMemberEffectWhenCalled( ) return true; if (!members[memberName].callsArgs) return false; - for (const argIndex of members[memberName].callsArgs as number[]) { + for (const argIndex of members[memberName].callsArgs!) { if ( callOptions.args[argIndex] && callOptions.args[argIndex].hasEffectsWhenCalledAtPath( @@ -490,6 +490,6 @@ export function getMemberReturnExpressionWhenCalled( ): ExpressionEntity { if (typeof memberName !== 'string' || !members[memberName]) return UNKNOWN_EXPRESSION; return members[memberName].returnsPrimitive !== null - ? (members[memberName].returnsPrimitive as ExpressionEntity) - : new (members[memberName].returns as any)(); + ? members[memberName].returnsPrimitive! + : new members[memberName].returns!(); } diff --git a/src/ast/variables/LocalVariable.ts b/src/ast/variables/LocalVariable.ts index 56e21339be2..f72e5aa2a73 100644 --- a/src/ast/variables/LocalVariable.ts +++ b/src/ast/variables/LocalVariable.ts @@ -128,7 +128,7 @@ export default class LocalVariable extends Variable { const trackedExpressions = context.accessed.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context)) as boolean; + return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context))!; } hasEffectsWhenAssignedAtPath(path: ObjectPath, context: HasEffectsContext) { @@ -138,7 +138,7 @@ export default class LocalVariable extends Variable { const trackedExpressions = context.assigned.getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context)) as boolean; + return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context))!; } hasEffectsWhenCalledAtPath( @@ -153,8 +153,7 @@ export default class LocalVariable extends Variable { ).getEntities(path); if (trackedExpressions.has(this)) return false; trackedExpressions.add(this); - return (this.init && - this.init.hasEffectsWhenCalledAtPath(path, callOptions, context)) as boolean; + return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context))!; } include(context: InclusionContext) { diff --git a/src/finalisers/amd.ts b/src/finalisers/amd.ts index c0cff6626f4..2a2ebcefa8b 100644 --- a/src/finalisers/amd.ts +++ b/src/finalisers/amd.ts @@ -84,8 +84,8 @@ export default function amd( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t ); if (exportBlock) magicString.append(n + n + exportBlock); diff --git a/src/finalisers/cjs.ts b/src/finalisers/cjs.ts index 67dc2d31dd8..08475600fc0 100644 --- a/src/finalisers/cjs.ts +++ b/src/finalisers/cjs.ts @@ -89,8 +89,8 @@ export default function cjs( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t, `module.exports${_}=${_}` ); diff --git a/src/finalisers/iife.ts b/src/finalisers/iife.ts index 7fc5a6b0950..789a8ddfb58 100644 --- a/src/finalisers/iife.ts +++ b/src/finalisers/iife.ts @@ -1,5 +1,5 @@ import { Bundle as MagicStringBundle } from 'magic-string'; -import { GlobalsOption, OutputOptions } from '../rollup/types'; +import { OutputOptions } from '../rollup/types'; import { error } from '../utils/error'; import { isLegal } from '../utils/identifierHelpers'; import { FinaliserOptions } from './index'; @@ -55,7 +55,7 @@ export default function iife( if (namedExportsMode && hasExports) { if (extend) { - deps.unshift(`${thisProp(name as string)}${_}=${_}${thisProp(name as string)}${_}||${_}{}`); + deps.unshift(`${thisProp(name!)}${_}=${_}${thisProp(name!)}${_}||${_}{}`); args.unshift('exports'); } else { deps.unshift('{}'); @@ -74,13 +74,7 @@ export default function iife( } if (isNamespaced && hasExports) { - wrapperIntro = - setupNamespace( - name as string, - 'this', - options.globals as GlobalsOption, - options.compact as boolean - ) + wrapperIntro; + wrapperIntro = setupNamespace(name!, 'this', options.globals, options.compact) + wrapperIntro; } let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`; @@ -99,8 +93,8 @@ export default function iife( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t ); if (exportBlock) magicString.append(n + n + exportBlock); diff --git a/src/finalisers/shared/getExportBlock.ts b/src/finalisers/shared/getExportBlock.ts index 266bd7e6efe..70fcda4ac29 100644 --- a/src/finalisers/shared/getExportBlock.ts +++ b/src/finalisers/shared/getExportBlock.ts @@ -4,8 +4,8 @@ export default function getExportBlock( exports: ChunkExports, dependencies: ChunkDependencies, namedExportsMode: boolean, - interop: boolean, - compact: boolean, + interop: boolean | undefined, + compact: boolean | undefined, t: string, mechanism = 'return ' ) { diff --git a/src/finalisers/shared/setupNamespace.ts b/src/finalisers/shared/setupNamespace.ts index bfa78ee82fe..0f1c1425908 100644 --- a/src/finalisers/shared/setupNamespace.ts +++ b/src/finalisers/shared/setupNamespace.ts @@ -4,8 +4,8 @@ import { property } from './sanitize'; export default function setupNamespace( name: string, root: string, - globals: GlobalsOption, - compact: boolean + globals: GlobalsOption | undefined, + compact: boolean | undefined ) { const parts = name.split('.'); if (globals) { @@ -28,8 +28,8 @@ export default function setupNamespace( export function assignToDeepVariable( deepName: string, root: string, - globals: GlobalsOption, - compact: boolean, + globals: GlobalsOption | undefined, + compact: boolean | undefined, assignment: string ): string { const _ = compact ? '' : ' '; @@ -42,7 +42,7 @@ export function assignToDeepVariable( let acc = root; let deepAssignment = parts .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`)) - .concat(`${acc}${property(last as string)}`) + .concat(`${acc}${property(last!)}`) .join(`,${_}`) .concat(`${_}=${_}${assignment}`); if (parts.length > 0) { diff --git a/src/finalisers/umd.ts b/src/finalisers/umd.ts index e9e9f3e1b26..9374338e57a 100644 --- a/src/finalisers/umd.ts +++ b/src/finalisers/umd.ts @@ -63,11 +63,11 @@ export default function umd( cjsDeps.unshift(`exports`); globalDeps.unshift( assignToDeepVariable( - options.name as string, + options.name!, globalVar, options.globals as GlobalsOption, - options.compact as boolean, - `${options.extend ? `${globalProp(options.name as string, globalVar)}${_}||${_}` : ''}{}` + options.compact!, + `${options.extend ? `${globalProp(options.name!, globalVar)}${_}||${_}` : ''}{}` ) ); @@ -92,10 +92,10 @@ export default function umd( if (!namedExportsMode && hasExports) { factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable( - options.name as string, + options.name!, globalVar, - options.globals as GlobalsOption, - options.compact as boolean, + options.globals, + options.compact, `${factoryVar}(${globalDeps.join(`,${_}`)})` )};`; } else if (namedExportsMode) { @@ -106,22 +106,21 @@ export default function umd( } iifeExport = `(function${_}()${_}{${n}` + - `${t}${t}var current${_}=${_}${safeAccess(options.name as string, globalVar, _)};${n}` + + `${t}${t}var current${_}=${_}${safeAccess(options.name!, globalVar, _)};${n}` + `${t}${t}${factory}${n}` + `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` + - `${globalProp( - options.name as string, - globalVar - )}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` + + `${globalProp(options.name!, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${ + options.compact ? '' : '; ' + }};${n}` + `${t}}())`; } else { iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`; if (!namedExportsMode && hasExports) { iifeExport = assignToDeepVariable( - options.name as string, + options.name!, globalVar, options.globals as GlobalsOption, - options.compact as boolean, + options.compact!, iifeExport ); } @@ -158,8 +157,8 @@ export default function umd( exports, dependencies, namedExportsMode, - options.interop as boolean, - options.compact as boolean, + options.interop, + options.compact, t ); if (exportBlock) magicString.append(n + n + exportBlock); diff --git a/src/rollup/index.ts b/src/rollup/index.ts index cdffe752c5e..69e32e99d1a 100644 --- a/src/rollup/index.ts +++ b/src/rollup/index.ts @@ -28,7 +28,6 @@ import { OutputOptions, Plugin, RollupBuild, - RollupCache, RollupOutput, RollupWatcher, WarningHandler @@ -160,7 +159,7 @@ function assignChunksToBundle( const chunk = chunks[i]; const facadeModule = chunk.facadeModule; - outputBundle[chunk.id as string] = { + outputBundle[chunk.id!] = { code: undefined as any, dynamicImports: chunk.getDynamicImportIds(), exports: chunk.getExportNames(), @@ -201,7 +200,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom chunks = await graph.build( inputOptions.input as string | string[] | Record, inputOptions.manualChunks, - inputOptions.inlineDynamicImports as boolean + inputOptions.inlineDynamicImports! ); } catch (err) { const watchFiles = Object.keys(graph.watchFiles); @@ -265,7 +264,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom chunk.preRender(outputOptions, inputBase); } if (!optimized && inputOptions.experimentalOptimizeChunks) { - optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize as number, inputBase); + optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize!, inputBase); optimized = true; } assignChunkIds( @@ -281,7 +280,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom await Promise.all( chunks.map(chunk => { - const outputChunk = outputBundleWithPlaceholders[chunk.id as string] as OutputChunk; + const outputChunk = outputBundleWithPlaceholders[chunk.id!] as OutputChunk; return chunk .render(outputOptions, addons, outputChunk, outputPluginDriver) .then(rendered => { @@ -318,7 +317,7 @@ export default async function rollup(rawInputOptions: GenericConfigObject): Prom const cache = useCache ? graph.getCache() : undefined; const result: RollupBuild = { - cache: cache as RollupCache, + cache: cache!, generate: ((rawOutputOptions: GenericConfigObject) => { const { outputOptions, outputPluginDriver } = getOutputOptionsAndPluginDriver( rawOutputOptions @@ -402,8 +401,7 @@ function createOutput(outputBundle: Record outputBundle[fileName]) .filter(outputFile => Object.keys(outputFile).length > 0) as ( | OutputChunk - | OutputAsset - )[]).sort((outputFileA, outputFileB) => { + | OutputAsset)[]).sort((outputFileA, outputFileB) => { const fileTypeA = getSortingFileType(outputFileA); const fileTypeB = getSortingFileType(outputFileB); if (fileTypeA === fileTypeB) return 0; @@ -418,10 +416,7 @@ function writeOutputFile( outputOptions: OutputOptions, outputPluginDriver: PluginDriver ): Promise { - const fileName = resolve( - outputOptions.dir || dirname(outputOptions.file as string), - outputFile.fileName - ); + const fileName = resolve(outputOptions.dir || dirname(outputOptions.file!), outputFile.fileName); let writeSourceMapPromise: Promise; let source: string | Buffer; if (outputFile.type === 'asset') { @@ -468,8 +463,8 @@ function normalizeOutputOptions( config: { output: { ...rawOutputOptions, - ...(rawOutputOptions.output as Object), - ...(inputOptions.output as Object) + ...(rawOutputOptions.output as object), + ...(inputOptions.output as object) } } }); diff --git a/src/utils/FileEmitter.ts b/src/utils/FileEmitter.ts index 88e34a8bb3d..b051b5ebb6c 100644 --- a/src/utils/FileEmitter.ts +++ b/src/utils/FileEmitter.ts @@ -1,4 +1,3 @@ -import Chunk from '../Chunk'; import Graph from '../Graph'; import Module from '../Module'; import { FilePlaceholder, OutputBundleWithPlaceholders } from '../rollup/types'; @@ -132,7 +131,7 @@ function getAssetFileName(file: ConsumedAsset, referenceId: string): string { } function getChunkFileName(file: ConsumedChunk): string { - const fileName = file.fileName || (file.module && (file.module.facadeChunk as Chunk).id); + const fileName = file.fileName || (file.module && file.module.facadeChunk!.id); if (!fileName) return error(errChunkNotGeneratedForFileName(file.fileName || file.name)); return fileName; } diff --git a/src/utils/PluginContext.ts b/src/utils/PluginContext.ts index 62bbdf64191..f89ec229f37 100644 --- a/src/utils/PluginContext.ts +++ b/src/utils/PluginContext.ts @@ -194,7 +194,7 @@ export function getPluginContexts( }); deprecationWarningShown = true; } - return (watcher as RollupWatcher).on(event, handler); + return watcher!.on(event, handler); } return { diff --git a/src/utils/PluginDriver.ts b/src/utils/PluginDriver.ts index fc080e7f3e8..a95c3992414 100644 --- a/src/utils/PluginDriver.ts +++ b/src/utils/PluginDriver.ts @@ -207,7 +207,7 @@ export class PluginDriver { args: Args, replaceContext?: ReplaceContext ): Promise { - let promise: Promise = Promise.resolve() as any; + let promise: Promise = Promise.resolve(); for (let i = 0; i < this.plugins.length; i++) promise = promise.then(() => this.runHook(hookName, args as any[], i, false, replaceContext) diff --git a/src/utils/collapseSourcemaps.ts b/src/utils/collapseSourcemaps.ts index c20a8348fab..edd9c4191cb 100644 --- a/src/utils/collapseSourcemaps.ts +++ b/src/utils/collapseSourcemaps.ts @@ -205,7 +205,7 @@ export function collapseSourcemaps( map: DecodedSourceMap, modules: Module[], bundleSourcemapChain: DecodedSourceMapOrMissing[], - excludeContent: boolean + excludeContent: boolean | undefined ) { const linkMap = getLinkMap(bundle.graph); const moduleSources = modules diff --git a/src/utils/deconflictChunk.ts b/src/utils/deconflictChunk.ts index 2cf63c1f9e9..7519bf763bc 100644 --- a/src/utils/deconflictChunk.ts +++ b/src/utils/deconflictChunk.ts @@ -93,14 +93,13 @@ function deconflictImportsOther( variable.setRenderNames(module.variableName, null); } } else { - const chunk = (module as Module).chunk as Chunk; + const chunk = module!.chunk!; if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) { variable.setRenderNames(null, chunk.variableName); } else { - variable.setRenderNames( - chunk.variableName, - chunk.getVariableExportName(variable) as string | null - ); + variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable) as + | string + | null); } } } diff --git a/src/utils/executionOrder.ts b/src/utils/executionOrder.ts index 1343def8f59..e5b1f75c288 100644 --- a/src/utils/executionOrder.ts +++ b/src/utils/executionOrder.ts @@ -73,7 +73,7 @@ function getCyclePath(id: string, parentId: string, parents: { [id: string]: str let curId = parentId; while (curId !== id) { path.push(relativeId(curId)); - curId = parents[curId] as string; + curId = parents[curId]!; if (!curId) break; } path.push(path[0]); diff --git a/src/utils/getIndentString.ts b/src/utils/getIndentString.ts index fb63f21e94d..32fd4c8cc47 100644 --- a/src/utils/getIndentString.ts +++ b/src/utils/getIndentString.ts @@ -19,7 +19,7 @@ function guessIndentString(code: string) { // Otherwise, we need to guess the multiple const min = spaced.reduce((previous, current) => { - const numSpaces = (/^ +/.exec(current) as RegExpExecArray)[0].length; + const numSpaces = /^ +/.exec(current)![0].length; return Math.min(numSpaces, previous); }, Infinity); diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 3e4610ca9b6..1363ce535e4 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -102,7 +102,7 @@ export function renderStatementList( }) : currentNode.render(code, options); } else { - treeshakeNode(currentNode, code, currentNodeStart as number, nextNodeStart); + treeshakeNode(currentNode, code, currentNodeStart!, nextNodeStart); } } else { currentNode.render(code, options); diff --git a/src/utils/timers.ts b/src/utils/timers.ts index 6683c39c93b..ad886db561e 100644 --- a/src/utils/timers.ts +++ b/src/utils/timers.ts @@ -128,7 +128,7 @@ export function initialiseTimers(inputOptions: InputOptions) { setTimeHelpers(); timeStart = timeStartImpl; timeEnd = timeEndImpl; - inputOptions.plugins = (inputOptions.plugins as Plugin[]).map(getPluginWithTimers); + inputOptions.plugins = inputOptions.plugins!.map(getPluginWithTimers); } else { timeStart = NOOP; timeEnd = NOOP; diff --git a/src/utils/transform.ts b/src/utils/transform.ts index 3e16df29471..9c83aa32f45 100644 --- a/src/utils/transform.ts +++ b/src/utils/transform.ts @@ -126,12 +126,12 @@ export default function transform( return pluginContext.error(err); }, emitAsset(name: string, source?: string | Buffer) { - const emittedFile = { type: 'asset' as 'asset', name, source }; + const emittedFile = { type: 'asset' as const, name, source }; emittedFiles.push({ ...emittedFile }); return graph.pluginDriver.emitFile(emittedFile); }, emitChunk(id, options) { - const emittedFile = { type: 'chunk' as 'chunk', id, name: options && options.name }; + const emittedFile = { type: 'chunk' as const, id, name: options && options.name }; emittedFiles.push({ ...emittedFile }); return graph.pluginDriver.emitFile(emittedFile); }, @@ -175,7 +175,7 @@ export default function transform( return new SourceMap({ ...combinedMap, file: null as any, - sourcesContent: combinedMap.sourcesContent as string[] + sourcesContent: combinedMap.sourcesContent! }); } }; @@ -186,7 +186,7 @@ export default function transform( if (!customTransformCache && setAssetSourceErr) throw setAssetSourceErr; return { - ast: ast as any, + ast: ast!, code, customTransformCache, moduleSideEffects, diff --git a/src/watch/fileWatchers.ts b/src/watch/fileWatchers.ts index b2d231fdba9..52f968e9309 100644 --- a/src/watch/fileWatchers.ts +++ b/src/watch/fileWatchers.ts @@ -15,7 +15,7 @@ export function addTask( isTransformDependency: boolean ) { if (!watchers.has(chokidarOptionsHash)) watchers.set(chokidarOptionsHash, new Map()); - const group = watchers.get(chokidarOptionsHash) as Map; + const group = watchers.get(chokidarOptionsHash)!; const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group); if (!watcher.fsWatcher) { @@ -26,7 +26,7 @@ export function addTask( } export function deleteTask(id: string, target: Task, chokidarOptionsHash: string) { - const group = watchers.get(chokidarOptionsHash) as Map; + const group = watchers.get(chokidarOptionsHash)!; const watcher = group.get(id); if (watcher) watcher.deleteTask(target, group); } diff --git a/src/watch/index.ts b/src/watch/index.ts index 799e2cfb7ff..958dfcd19f8 100644 --- a/src/watch/index.ts +++ b/src/watch/index.ts @@ -141,7 +141,7 @@ export class Task { this.outputs = outputOptions; this.outputFiles = this.outputs.map(output => { - if (output.file || output.dir) return path.resolve(output.file || (output.dir as string)); + if (output.file || output.dir) return path.resolve(output.file || output.dir!); return undefined as any; }); diff --git a/test/function/samples/error-parse-json/_config.js b/test/function/samples/error-parse-json/_config.js index e9a3c2fe6a6..62dbc19fa45 100644 --- a/test/function/samples/error-parse-json/_config.js +++ b/test/function/samples/error-parse-json/_config.js @@ -5,7 +5,7 @@ module.exports = { 'throws with an extended error message when failing to parse a file with ".json" extension', error: { code: 'PARSE_ERROR', - message: 'Unexpected token (Note that you need rollup-plugin-json to import JSON files)', + message: 'Unexpected token (Note that you need @rollup/plugin-json to import JSON files)', parserError: { loc: { column: 8,