Skip to content

Instantly share code, notes, and snippets.

@ccjmne
Last active November 12, 2021 17:36
Show Gist options
  • Save ccjmne/cb291c4824ddba8b8c6c9a3e509c558a to your computer and use it in GitHub Desktop.
Save ccjmne/cb291c4824ddba8b8c6c9a3e509c558a to your computer and use it in GitHub Desktop.
Use TypeScript for your webpack config

1. Create a secondary TypeScript config for webpack only

Simply create a new tsconfig-webpack.json file with the following contents:

{
  "compilerOptions": {
    "module": "commonjs",
    "resolveJsonModule": true,
    "target": "es6",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

The module value needs to be set to commonjs so long as this is what Node.js understands.

2. Use cross-env to to call webpack

Install cross-env and ts-node:

npm install --save-dev ts-node cross-env

Replace usages of webpack by:

cross-env TS_NODE_PROJECT="tsconfig-webpack.json" webpack

For instance, inside a package.json's "scripts":

"start:dev": "cross-env TS_NODE_PROJECT=\"tsconfig-webpack.json\" webpack serve --mode development",
"build:prod": "cross-env TS_NODE_PROJECT=\"tsconfig-webpack.json\" webpack --mode production"
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"target": "es6",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment