Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@rollup/plugin-typescript
Advanced tools
@rollup/plugin-typescript is a Rollup plugin that allows you to seamlessly integrate TypeScript into your Rollup build process. It compiles TypeScript files and includes them in your bundle, making it easier to work with TypeScript in a Rollup-based project.
Basic TypeScript Compilation
This feature allows you to compile TypeScript files into JavaScript. The code sample demonstrates a basic Rollup configuration that compiles a TypeScript file located at 'src/index.ts' and outputs a bundled JavaScript file at 'dist/bundle.js'.
const typescript = require('@rollup/plugin-typescript');
module.exports = {
input: 'src/index.ts',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
typescript()
]
};
Custom TypeScript Compiler Options
This feature allows you to specify custom TypeScript compiler options by providing a path to a custom tsconfig.json file. The code sample shows how to use a custom TypeScript configuration file named 'tsconfig.custom.json'.
const typescript = require('@rollup/plugin-typescript');
module.exports = {
input: 'src/index.ts',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
typescript({
tsconfig: 'tsconfig.custom.json'
})
]
};
Type Checking
This feature enables type checking during the build process. The code sample demonstrates how to enable type checking by setting the 'check' option to true.
const typescript = require('@rollup/plugin-typescript');
module.exports = {
input: 'src/index.ts',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
typescript({
check: true
})
]
};
rollup-plugin-typescript2 is another Rollup plugin for integrating TypeScript. It offers more advanced features like incremental builds and better error reporting compared to @rollup/plugin-typescript. However, it may have a steeper learning curve due to its additional configuration options.
ts-loader is a TypeScript loader for Webpack. While it is not a Rollup plugin, it serves a similar purpose in the Webpack ecosystem by allowing you to compile TypeScript files. It is highly configurable and integrates well with Webpack's ecosystem.
babel-plugin-transform-typescript is a Babel plugin that allows you to compile TypeScript using Babel. This can be useful if you are already using Babel for other transformations and want to keep your build process consistent. However, it does not perform type checking.
🍣 A Rollup plugin for seamless integration between Rollup and Typescript.
This plugin requires an LTS Node version (v14.0.0+) and Rollup v2.14.0+. This plugin also requires at least TypeScript 3.7.
Using npm:
npm install @rollup/plugin-typescript --save-dev
Note that both typescript
and tslib
are peer dependencies of this plugin that need to be installed separately.
See @rollup/plugin-babel.
Create a rollup.config.js
configuration file and import the plugin:
// rollup.config.js
import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/index.ts',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [typescript()]
};
Then call rollup
either via the CLI or the API.
The plugin loads any compilerOptions
from the tsconfig.json
file by default. Passing options to the plugin directly overrides those options:
...
export default {
input: './main.ts',
plugins: [
typescript({ compilerOptions: {lib: ["es5", "es6", "dom"], target: "es5"}})
]
}
The following options are unique to rollup-plugin-typescript
:
exclude
Type: String
| Array[...String]
Default: null
A picomatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default no files are ignored.
include
Type: String
| Array[...String]
Default: null
A picomatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. By default all .ts
and .tsx
files are targeted.
filterRoot
Type: String
| Boolean
Default: rootDir
?? tsConfig.compilerOptions.rootDir
?? process.cwd()
Optionally resolves the include and exclude patterns against a directory other than process.cwd()
. If a String is specified, then the value will be used as the base directory. Relative paths will be resolved against process.cwd()
first. If false
, then the patterns will not be resolved against any directory.
By default, patterns resolve against the rootDir set in your TS config file.
This can fix plugin errors when parsing files outside the current working directory (process.cwd()).
tsconfig
Type: String
| Boolean
Default: true
When set to false, ignores any options specified in the config file. If set to a string that corresponds to a file path, the specified file will be used as config file.
typescript
Type: import('typescript')
Default: peer dependency
Overrides the TypeScript module used for transpilation.
typescript({
typescript: require('some-fork-of-typescript')
});
tslib
Type: String
Default: peer dependency
Overrides the injected TypeScript helpers with a custom version.
typescript({
tslib: require.resolve('some-fork-of-tslib')
});
transformers
Type: { [before | after | afterDeclarations]: TransformerFactory[] }
Default: undefined
Allows registration of TypeScript custom transformers at any of the supported stages:
Supported transformer factories:
all built-in TypeScript custom transformer factories:
import('typescript').TransformerFactory
annotated TransformerFactory bellowimport('typescript').CustomTransformerFactory
annotated CustomTransformerFactory bellowProgramTransformerFactory represents a transformer factory allowing the resulting transformer to grab a reference to the Program instance
{
type: 'program',
factory: (program: Program) => TransformerFactory | CustomTransformerFactory
}
TypeCheckerTransformerFactory represents a transformer factory allowing the resulting transformer to grab a reference to the TypeChecker instance
{
type: 'typeChecker',
factory: (typeChecker: TypeChecker) => TransformerFactory | CustomTransformerFactory
}
typescript({
transformers: {
before: [
{
// Allow the transformer to get a Program reference in it's factory
type: 'program',
factory: (program) => {
return ProgramRequiringTransformerFactory(program);
}
},
{
type: 'typeChecker',
factory: (typeChecker) => {
// Allow the transformer to get a TypeChecker reference in it's factory
return TypeCheckerRequiringTransformerFactory(typeChecker);
}
}
],
after: [
// You can use normal transformers directly
require('custom-transformer-based-on-Context')
],
afterDeclarations: [
// Or even define in place
function fixDeclarationFactory(context) {
return function fixDeclaration(source) {
function visitor(node) {
// Do real work here
return ts.visitEachChild(node, visitor, context);
}
return ts.visitEachChild(source, visitor, context);
};
}
]
}
});
cacheDir
Type: String
Default: .rollup.cache
When compiling with incremental
or composite
options the plugin will
store compiled files in this folder. This allows the use of incremental
compilation.
typescript({
cacheDir: '.rollup.tscache'
});
noForceEmit
Type: Boolean
Default: false
Earlier version of @rollup/plugin-typescript
required that the compilerOptions
noEmit
and emitDeclarationOnly
both false to guarantee that source code was fed into the next plugin/output. This is no longer true. This option disables the plugin forcing the values of those options and instead defers to the values set in tsconfig.json
.
noForceEmit
can be very useful if you use with @rollup/plugin-babel
and @babel/preset-typescript
. Having @rollup/plugin-typescript
only do typechecking / declarations with "emitDeclarationOnly": true
while deferring to @rollup/plugin-babel
for transpilation can dramatically reduce rollup
build times for large projects.
Some of Typescript's CompilerOptions affect how Rollup builds files.
noEmitOnError
Type: Boolean
Default: false
If a type error is detected, the Rollup build is aborted when this option is set to true.
files
, include
, exclude
Type: Array[...String]
Default: []
Declaration files are automatically included if they are listed in the files
field in your tsconfig.json
file. Source files in these fields are ignored as Rollup's configuration is used instead.
These compiler options are ignored by Rollup:
noEmitHelpers
, importHelpers
: The tslib
helper module always must be used.noEmit
, emitDeclarationOnly
: Typescript needs to emit code for the plugin to work with.
@rollup/plugin-typescript
, it is no longer. To override this behavior, and defer to tsconfig.json
for these options, see the noForceEmit
optionnoResolve
: Preventing Typescript from resolving code may break compilationThough it is not recommended, it is possible to configure this plugin to handle imports of CommonJS files from TypeScript. For this, you need to specify CommonJS
as the module format and add @rollup/plugin-commonjs
to transpile the CommonJS output generated by TypeScript to ES Modules so that rollup can process it.
// rollup.config.js
import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: './main.ts',
plugins: [
typescript({ compilerOptions: { module: 'CommonJS' } }),
commonjs({ extensions: ['.js', '.ts'] }) // the ".ts" extension is required
]
};
Note that this will often result in less optimal output.
Whenever choosing to preserve JSX output to be further consumed by another transform step via tsconfig
compilerOptions
by setting jsx: 'preserve'
or overriding options, please bear in mind that, by itself, this plugin won't be able to preserve JSX output, usually failing with:
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
file.tsx (1:15)
1: export default <span>Foobar</span>
^
To prevent that, make sure to use the acorn plugin, namely acorn-jsx
, which will make Rollup's parser acorn handle JSX tokens. (See https://rollupjs.org/guide/en/#acorninjectplugins)
After adding acorn-jsx
plugin, your Rollup config would look like the following, correctly preserving your JSX output.
import jsx from 'acorn-jsx';
import typescript from '@rollup/plugin-typescript';
export default {
// … other options …
acornInjectPlugins: [jsx()],
plugins: [typescript({ compilerOptions: { jsx: 'preserve' } })]
};
Previous versions of this plugin used Typescript's transpileModule
API, which is faster but does not perform typechecking and does not support cross-file features like const enum
s and emit-less types. If you want this behaviour, you can use @rollup/plugin-sucrase instead.
output.file
When instructing Rollup to output a specific file name via the output.file
Rollup configuration, and TypeScript to output declaration files, users may encounter a situation where the declarations are nested improperly. And additionally when attempting to fix the improper nesting via use of outDir
or declarationDir
result in further TypeScript errors.
Consider the following rollup.config.js
file:
import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/index.ts',
output: {
file: 'dist/index.mjs'
},
plugins: [typescript()]
};
And accompanying tsconfig.json
file:
{
"include": ["*"],
"compilerOptions": {
"outDir": "dist",
"declaration": true
}
}
This setup will produce dist/index.mjs
and dist/src/index.d.ts
. To correctly place the declaration file, add an exclude
setting in tsconfig
and modify the declarationDir
setting in compilerOptions
to resemble:
{
"include": ["*"],
"exclude": ["dist"],
"compilerOptions": {
"outDir": "dist",
"declaration": true,
"declarationDir": "."
}
}
This will result in the correct output of dist/index.mjs
and dist/index.d.ts
.
For reference, please see the workaround this section is based on here
FAQs
Seamless integration between Rollup and TypeScript.
We found that @rollup/plugin-typescript demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.