Is it possible to write webpack config in typescript?
I saw, when searching, that there are typings for webpack. So it seems I can write webpack.config.js in typescript? But how can I do that?
Solution 1:
You can use TS as your config file (webpack.config.ts)
There is a clear clue for that, see Source Code
The ** interpret** module used there is a list of extension files and their loaders.
In the highlighted code webpack generates an array of all possible extension for the default files.
For example, give webpack.config you will get an array with
- webpack.config.ts
- webpack.config.js
- ...... and so on
For this to work you need to install one of the packages that support loading your extension.
For example, TS has some node packages that enable you to require('something.ts') and the package will do the work.
The interpret package states that one of these packages is required
ts-node, typescript-node, typescript-register, typescript-require
So npm/yarn ts-node then just put a webpack.config.ts file and it will just work!
EDIT: Webpack documentation now has dedicated section on configuration languages which includes TypeScript, CoffeeScript and Babel & JSX
Solution 2:
If you are using vscode as editor (or maybe others which support the JSDoc typing syntax) and you're only interested in typechecking your file to guide completion on your configuration object, you can do it like so:
In vscode you can do this as such:
npm i -D @types/webpack
- add type annotation comments to your
webpack.config.js
file, as such:
webpack.config.js:
// @ts-check
module.exports = /** @type { import('webpack').Configuration } */ ({
...
});
Solution 3:
Webpack 4
When using webpack v4, you have to install typings for webpack (npm install --save @types/webpack
).
Webpack 5
When using webpack v5, you don't need to install external typings because webpack 5 already ships with TypeScript definitions. It's actually recommended to remove @types/webpack
when you have them installed: https://webpack.js.org/blog/2020-10-10-webpack-5-release/#typescript-typings
Webpack Configuration
Here is an example of a webpack config written purely in TypeScript (that's why it's file name also ends on .ts
):
webpack.config.ts
import {Configuration} from 'webpack';
const config: Configuration = {
mode: 'development',
module: {
rules: [
{
exclude: /(node_modules)/,
loader: 'babel-loader',
test: /\.[tj]sx?$/,
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
};
export default config;
Documentation
If you are interested in all the possibilities of how to configure webpack, then the 6 ways to configure Webpack article may help you.