{"id":127686,"date":"2022-09-01T13:30:59","date_gmt":"2022-09-01T17:30:59","guid":{"rendered":"https:\/\/blog.logrocket.com\/?p=127686"},"modified":"2024-06-04T17:05:21","modified_gmt":"2024-06-04T21:05:21","slug":"using-webpack-typescript","status":"publish","type":"post","link":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/","title":{"rendered":"Using webpack with TypeScript"},"content":{"rendered":"<!DOCTYPE html>\n<html><p>Used in many modern projects, webpack is an amazing tool that optimizes application resources so that they work more efficiently and effectively on any device. webpack helps to compile and bundle modules into a single file, reducing HTTP requests and improving application performance as a result.<\/p><img loading=\"lazy\" decoding=\"async\" width=\"730\" height=\"487\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png\" class=\"attachment-full size-full wp-post-image\" alt=\"Typescript Webpack\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack-300x200.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\">\n<p>With webpack, TypeScript code is compiled into a JavaScript file that is browser-friendly. With webpack loaders, you can also convert SASS and LESS files into a single CSS bundle file.<\/p>\n<p>In this article, we\u2019ll learn how to use webpack to compile TypeScript to JavaScript, bundle source code into a single JavaScript file, and use a source map for debugging. We\u2019ll also explore how to use webpack plugins.<\/p>\n<p>To follow along with this tutorial, you\u2019ll need the following:<\/p>\n<ul>\n<li>npm<\/li>\n<li>Node.js: If you already have Node.js installed, ensure it\u2019s \u2265v8.x.<\/li>\n<li>Any code editor of your choice; I\u2019ll use <a href=\"https:\/\/code.visualstudio.com\/\">Visual Studio Code<\/a><\/li>\n<li>Basic knowledge of TypeScript<\/li>\n<\/ul>\n<p>Let\u2019s get started!<\/p>\n<hr>\n<p id=\"tableofcontents\"><em>Jump ahead:<\/em><\/p>\n<ul>\n<li><a href=\"#webpack-loaders\">webpack loaders<\/a><\/li>\n<li><a href=\"#setting-up-webpack-typescript\">Setting up webpack and TypeScript<\/a><\/li>\n<li><a href=\"#webpack-configuration\">webpack configuration<\/a><\/li>\n<li><a href=\"#typescript-configuration\">TypeScript configuration<\/a><\/li>\n<li><a href=\"#package-configuration\">Package configuration<\/a><\/li>\n<li><a href=\"#creating-html-pages-html-webpack-plugin\">Creating HTML pages with <code>HtmlWebpackPlugin<\/code><\/a><\/li>\n<li><a href=\"#bundling-css-mini-css-extract-plugin\">Bundling CSS With <code>MiniCssExtractPlugin<\/code><\/a><\/li>\n<li><a href=\"#css-minify\">Minifying CSS<\/a><\/li>\n<li><a href=\"#minifying-javascript\">Minifying JavaScript<\/a><\/li>\n<li><a href=\"#using-copy-webpack-plugin\">Using <code>Copywebpackplugin<\/code><\/a><\/li>\n<li><a href=\"#debugging-source-map\">Debugging with a source map<\/a><\/li>\n<\/ul>\n<hr>\n<h2 id=\"webpack-loaders\">webpack loaders<\/h2>\n<p>By default, webpack only understands JavaScript files, treating every imported file as a module. webpack cannot compile or bundle non-JavaScript files, therefore, it uses a loader.<\/p>\n<p>Loaders tell webpack how to compile and bundle static assets. They are used for compiling TypeScript modules into JavaScript, handling application styles, and even linting your code with ESLint.<\/p>\n<p>A <a href=\"https:\/\/webpack.js.org\/loaders\/\">few webpack loaders<\/a> include ts-loader, css-loader, style-loader, and more; we\u2019ll discuss them later in this tutorial.<\/p>\n<h2 id=\"setting-up-webpack-typescript\">Setting up webpack and TypeScript<\/h2>\n<p>Let\u2019s start by setting up our project. First, you should have TypeScript installed on your computer. To install TypeScript globally, use the command below:<\/p>\n<pre class=\"language-bash hljs\">npm install -g typescript\n<\/pre>\n<p>Installing TypeScript globally eliminates the need to install TypeScript each time you start a new project.<\/p>\n<p>Next, we\u2019ll install the webpack and <a href=\"https:\/\/www.npmjs.com\/package\/ts-loader\">ts-loader<\/a> packages as dependencies in our project:<\/p>\n<pre class=\"language-bash hljs\">npm init -y\nnpm install -D webpack webpack-cli ts-loader webpack-dev-server<\/pre>\n<h2 id=\"webpack-configuration\">webpack configuration<\/h2>\n<p>By default, webpack does not need a configuration file. It will assume that the entry point for your project is <code>src\/index.js<\/code> and will output the minified and optimized result in <code>dist<\/code>\/<code>main.js<\/code> during production.<\/p>\n<p>If you want to use plugins or loaders, then you\u2019ll need to use the webpack configuration file, allowing you to&nbsp;specify how webpack will work with your project, which files to compile, and where the output bundle file will be.<\/p>\n<p>Let\u2019s add the webpack configuration file to our project. From the project root folder, create a <code>webpack.config.js<\/code> file with the following configurations:<\/p>\n<pre class=\"language-json hljs\">const path = require('path');\n\nmodule.exports = {\n  entry: '.\/src\/index.ts',\n  module: {\n    rules: [\n      {\n        test: \/\\.ts?$\/,\n        use: 'ts-loader',\n        exclude: \/node_modules\/,\n      },\n    ],\n  },\n  resolve: {\n    extensions: ['.tsx', '.ts', '.js'],\n  },\n  output: {\n    filename: 'bundle.js',\n    path: path.resolve(__dirname, 'dist'),\n  },\n  devServer: {\n    static: path.join(__dirname, \"dist\"),\n    compress: true,\n    port: 4000,\n  },\n};<\/pre>\n<p>Let\u2019s review some of the webpack configuration options. For one, the <code>entry<\/code> option is the starting point for the application, where webpack begins to build a dependency graph. webpack will proceed to other modules based on the entry file.<\/p>\n<p>The <code>output<\/code> option tells webpack where to save bundle files and allows you to name the bundle file. Finally, the <code>module<\/code> option tells webpack how to process modules with specific rules using loaders.<\/p>\n<h2 id=\"typescript-configuration\">TypeScript configuration<\/h2>\n<p>The TypeScript configuration file controls how TypeScript will be compiled to JavaScript and specifies the various compiler options required for transpiling TypeScript.<\/p>\n<p>From the project root folder, create the <code>tsconfig.json<\/code> file and add the following configurations:<\/p>\n<pre class=\"language-json hljs\">{\n    \"compilerOptions\": {\n        \"noImplicitAny\": true,\n        \"target\": \"ES5\",\n        \"module\": \"ES2015\"\n    }\n}\n<\/pre>\n<p>The <code>target<\/code> option is the version of JavaScript you want to transpile TypeScript to, while <code>module<\/code> is the format of the import statement used. You can set the module to CommonJS, ES6, or UMD since webpack will handle all module systems.<\/p>\n<h2 id=\"package-configuration\">Package configuration<\/h2>\n<p>Now, we need to add a webpack script that will run the <code>webpack.config.js<\/code> file for us.<\/p>\n<p>To add the webpack script, open the <code>package.json<\/code> file and add the following scripts to the script option:<\/p>\n<pre class=\"language-json hljs\">\"develop\": \"webpack-dev-server --mode development\",\n\"build\" : \"webpack --mode production\"<\/pre>\n<p>The <code>package.json<\/code> file will now contain the following configuration settings:<\/p>\n<pre class=\"language-json hljs\">{\n    \"name\": \"webpack-setup\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"src\/index.ts\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" &amp;&amp; exit 1\",\n    \"develop\": \"webpack-dev-server --mode development\",\n    \"build\": \"webpack --mode production\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"css-loader\": \"^6.7.1\",\n    \"html-webpack-plugin\": \"^5.5.0\",\n    \"mini-css-extract-plugin\": \"^2.6.1\",\n    \"ts-loader\": \"^9.4.1\",\n    \"webpack\": \"^5.74.0\",\n    \"webpack-cli\": \"^4.10.0\",\n    \"webpack-dev-server\": \"^4.11.1\"\n  }\n}<\/pre>\n<p>Now, let\u2019s create a simple TypeScript program that will subtract&nbsp;two numbers. Inside the <code>src<\/code> folder, create an <code>index.ts<\/code> file and add the following TypeScript code:<\/p>\n<pre class=\"language-typescript hljs\">import { subtract } from \".\/app\";\n\nfunction init() {\n    const form = document.querySelector(\"form\");\n    form?.addEventListener(\"submit\", submitHandler);\n  }\n\n  function submitHandler(e: Event) {\n    e.preventDefault();\n    const num1 = document.querySelector(\"input[name='firstnumber']\") as HTMLInputElement;\n    const num2 = document.querySelector(\"input[name='secondnumber']\") as HTMLInputElement;\n    const result = subtract(Number(num1.value), Number(num2.value));\n    const resultElement = document.querySelector(\"p\");\n    if (resultElement) {\n      resultElement.textContent = result.toString();\n    }\n  }\n\n  init();\n<\/pre>\n<p>Next, create another <code>app.ts<\/code> file and add the following code:<\/p>\n<pre>export function subtract(firstnumber: number, secondnumber: number): number {\n  return firstnumber - secondnumber;\n}\n<\/pre>\n<p>Running the <code>develop<\/code> script will start the app in development mode:<\/p>\n<pre>npm run develop \n<\/pre>\n<p>Running the <code>build<\/code> script will run the app in production mode:<\/p>\n<pre>npm run build<\/pre>\n<p>After running the build command, webpack will transpile the two TypeScript files into JavaScript code and generate a <code>bundle.js<\/code> file inside the <code>dist<\/code> folder.<\/p>\n<h2 id=\"creating-html-pages-html-webpack-plugin\">Creating HTML pages with <code>HtmlWebpackPlugin<\/code><\/h2>\n<p>The <code>HtmlWebpackPlugin<\/code> allows webpack to generate a standard HTML page that will serve the generated bundle files.<\/p>\n<p>When the filename of the bundle changes or is hashed, <code>HTMLWebpackPlugin<\/code> updates the filenames on the HTML page. First, to install <code>HtmlWebpackPlugin<\/code>, run the command below:<\/p>\n<pre class=\"language-bash hljs\">npm install html-webpack-plugin --save-dev<\/pre>\n<p>Next, we need to import and add <code>HtmlWebpackPlugin<\/code> to the webpack configuration plugin option as follows:<\/p>\n<pre class=\"language-javascript hljs\">const HtmlWebpackPlugin = require(\"html-webpack-plugin\");\nconst path = require('path');\n\nmodule.exports = {\n  entry: '.\/src\/index.ts',\n  module: {\n    rules: [\n      {\n        test: \/\\.ts?$\/,\n        use: 'ts-loader',\n        exclude: \/node_modules\/,\n      }\n    ],\n  },\n  resolve: {\n    extensions: ['.tsx', '.ts', '.js'],\n  },\n  output: {\n    filename: 'bundle.js',\n    path: path.resolve(__dirname, 'dist'),\n  },\n\n  plugins: [\n    new HtmlWebpackPlugin({\n        title: 'our project', \n        template: 'src\/custom.html' }) \n   ],\n\n  devServer: {\n    static: path.join(__dirname, \"dist\"),\n    compress: true,\n    port: 4000,\n  },\n};\n<\/pre>\n<p>The template is a custom HTML file generated by <code>HtmlWebpackPlugin<\/code> to be injected into the HTML page. To create the custom HTML, inside the <code>src<\/code> folder, create a <code>custom.html<\/code> file and add the following HTML code:<\/p>\n<pre class=\"language-html hljs\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n  &lt;head&gt;\n    &lt;meta charset=\"utf-8\" \/&gt;\n  &lt;\/head&gt;\n  &lt;body&gt;\n    &lt;div class=\"cal\"&gt;\n      &lt;center&gt;\n     &lt;form&gt;&lt;br&gt;\n      &lt;p&gt;Result : &lt;span id=\"display\"&gt;&lt;\/span&gt;&lt;\/p&gt;\n      &lt;input type=\"number\" class=\"input\" placeholder=\"Enter first number\" name=\"firstnumber\" value=\"1\" min=\"1\" min=\"9\" \/&gt;&lt;br&gt;\n      &lt;input type=\"number\" class=\"input\" placeholder=\"Enter second number\" name=\"secondnumber\" value=\"1\" min=\"1\" min=\"9\" \/&gt;&lt;br&gt;&lt;br&gt;\n      &lt;button type=\"submit\" class=\"button\"&gt;Subtract&lt;\/button&gt;\n    &lt;\/form&gt;\n  &lt;\/center&gt;\n  &lt;\/div&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n<p>You don\u2019t have to include the script or link tags in the custom HTML; <code>HtmlWebpackPlugin<\/code> will take care of that by linking the bundle file URL with the generated page.<\/p>\n<p>Running the app in production mode will generate the <code>index.html<\/code> HTML page inside the <code>dist<\/code> folder.<\/p>\n<h2 id=\"bundling-css-mini-css-extract-plugin\">Bundling CSS with <code>MiniCSSExtractPlugin<\/code><\/h2>\n<p>css-loader tells webpack how to work with the CSS module. It interprets <code>@import<\/code> and <code>URL()<\/code> as <code>import\/require()<\/code> and resolves them. css-loader enables webpack to compile all CSS files and convert them into JavaScript format.<\/p>\n<p>Bundling CSS files with style-loader makes HTML page styles unresponsive until the <code>Bundle.js<\/code> is completely loaded. The style-loader injects CSS into the DOM, but the bundled JavaScript file has to load completely before the styles are injected. To solve this, we can use <code><a href=\"https:\/\/webpack.js.org\/plugins\/mini-css-extract-plugin\/\">MiniCssExtractPlugin<\/a><\/code>.<\/p>\n<p>The <code>MiniCssExtractPlugin<\/code> extracts CSS files and bundles them into a single <code>bundle.css<\/code> file. This is useful for reducing the size of your CSS assets and avoiding unnecessary HTTP requests to load them.<\/p>\n<p>We can install css-loader and <code>MiniCssExtractPlugin<\/code> by running the commands below in the terminal:<\/p>\n<pre class=\"language-bash hljs\">npm install css-loader --save-dev\nnpm install mini-css-extract-plugin --save-dev<\/pre>\n<p>Now, let\u2019s add the css-loader and <code>MiniCssExtractPlugin<\/code> to the <code>webpack.config.js<\/code> file.<\/p>\n<p>At the top of the <code>webpack.config.js<\/code> file, import the <code>MiniCssExtractPlugin<\/code> module using the code below:<\/p>\n<pre class=\"language-html hljs\">const MiniCssExtractPlugin = require(\"mini-css-extract-plugin\");\n<\/pre>\n<p>Then, we\u2019ll add a new rule to the <code>rules<\/code> property as follows:<\/p>\n<pre class=\"language-javascript hljs\">\u2026\n{\n        test: \/\\.css$\/,\n        use: [MiniCssExtractPlugin.loader, \"css-loader\"]\n}\n\u2026\n<\/pre>\n<p>When css-loader compiles all the CSS files into JavaScript, <code>MiniCssExtractPlugin.loader<\/code> loads the CSS into the CSS bundle file.<\/p>\n<p>Next, we\u2019ll add <code>MiniCssExtractPlugin<\/code> to the plugin option as follows:<\/p>\n<pre class=\"language-javascript hljs\">plugins: [\n    new HtmlWebpackPlugin({\n        title: 'our project', \/\/ Load a custom template (lodash by default)\n        template: 'src\/custom.html' }),\n    new MiniCssExtractPlugin({\n      filename:\"bundle.css\"})\n  ]\n<\/pre>\n<p>Now that we\u2019ve configured <code>css-loader<\/code> and <code>MiniCssExtractPlugin<\/code>, let\u2019s create a CSS file and import it into <code>index.ts<\/code>. Inside the <code>src<\/code> folder, create an <code>index.css<\/code> file and add the following CSS code:<\/p>\n<pre class=\"language-css hljs\">form {\n    background-color:pink;\n    margin-top:100px;\n    border-radius:40px;\n}\n.cal{\n    width:550px;\n    height:300px;\n    margin-left:400px;\n}\n\n.button{\n    border-radius:10px;\n    margin-top:20px;\n    margin-bottom:20px;\n}\n.input{\n    border-radius:10px;\n    margin-top:40px;\n}\n<\/pre>\n<p>Inside <code>index.ts<\/code>, import the CSS style as follows:<\/p>\n<pre class=\"language-typescript hljs\">import styles \".\/main.css\"\n<\/pre>\n<p>Running <code>npm run build<\/code> will bundle the CSS and apply it to <code>index.html<\/code>. When you start the app in development mode and open <code>http:\/\/localhost:4000<\/code> on the browser, it should look like the following image:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-142391 size-full\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/bundled-css-previewed-localhost.png\" alt=\"Bundled CSS Previewed Localhost\" width=\"730\" height=\"456\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/bundled-css-previewed-localhost.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/09\/bundled-css-previewed-localhost-300x187.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<h2 id=\"css-minify\">Minifying CSS<\/h2>\n<p>We can use the <a href=\"https:\/\/webpack.js.org\/plugins\/css-minimizer-webpack-plugin\/\"><code>css-minimizer-webpack-plugin<\/code><\/a> to reduce the size of CSS files by removing unused CSS rules and keeping only the necessary ones.<\/p>\n<p><code>css-minimizer-webpack-plugin<\/code> analyzes the compiled CSS file and finds any unused styles. This plugin will then remove these unused styles from your final CSS file, thereby reducing its size.<\/p>\n<p>Run the installation command below to install <code>css-minimizer-webpack-plugin<\/code>:<\/p>\n<pre class=\"language-bash hljs\">npm install css-minimizer-webpack-plugin --save-dev\n<\/pre>\n<p>Let\u2019s add <code>css-minimizer-webpack-plugin<\/code> to the webpack configuration. First, import the plugin as follows:<\/p>\n<pre class=\"language-bash hljs\">const CssMinimizerPlugin = require(\"css-minimizer-webpack-plugin\");\n<\/pre>\n<p>Then, we\u2019ll add a new optimization property to the webpack configuration as follows:<\/p>\n<pre>optimization: {\n    minimizer: [\n      new CssMinimizerPlugin()\n    ],\n  }\n<\/pre>\n<p>When we run the build command, <code>bundle.css<\/code> will be minified but <code>bundle.js<\/code> will not. The default <code>bundle.js<\/code> minimizer has been overridden with the minimizer option that we set. To solve this, we need to minify the JavaScript using <code>TerserWebpackPlugin<\/code>.<\/p>\n<h2 id=\"minifying-javascript\">Minifying JavaScript<\/h2>\n<p>In the current version of webpack at the time of writing, v5.74.0 and later, you don\u2019t have to install the <a href=\"https:\/\/webpack.js.org\/plugins\/terser-webpack-plugin\/\"><code>TerserWebpackPlugin<\/code><\/a> since it\u2019s included out of the box. First, we have to import <code>TerserWebpackPlugin<\/code>:<\/p>\n<pre class=\"language-javascript hljs\">const TerserPlugin = require(\"terser-webpack-plugin\");\n<\/pre>\n<p>Then, add <code>TerserPlugin<\/code> to the minimizer option as follows:<\/p>\n<pre class=\"language-javascript hljs\">optimization: {\n    minimizer: [\n      new CssMinimizerPlugin(),\n     new TerserPlugin()\n    ],\n  }\n<\/pre>\n<p>If you run the <code>build<\/code> script and look at the bundle files in the <code>dist<\/code> folder, you\u2019ll see that both JavaScript and CSS are minified.<\/p>\n<h2 id=\"using-copy-webpack-plugin\">Using <code>Copywebpackplugin<\/code><\/h2>\n<p>We can configure webpack to copy application assets from the development folder into the build folder <code>dist<\/code> using <code><a href=\"https:\/\/webpack.js.org\/plugins\/copy-webpack-plugin\/\">CopyWebpackPlugin<\/a><\/code>. This plugin can copy files like images, videos, and other assets into the <code>dist<\/code> folder.<\/p>\n<p>Install <code>CopyWebpackPlugin<\/code> using the command below:<\/p>\n<pre class=\"language-bash hljs\">npm install copy-webpack-plugin --save-dev\n<\/pre>\n<p>Now, let\u2019s add <code>CopyWebpackPlugin<\/code> to the webpack configuration. Import the plugin as follows:<\/p>\n<pre class=\"language-bash hljs\">const CopyPlugin = require(\"copy-webpack-plugin\");\n<\/pre>\n<p>Next, we\u2019ll add <code>CopyWebpackPlugin<\/code> to the plugin option. The <code>from<\/code> property is the folder that we\u2019ll copy from, and the <code>to<\/code> property is the folder in <code>dist<\/code> directory to copy all files to:<\/p>\n<pre class=\"language-json hljs\">...\nplugins: [\nnew HtmlWebpackPlugin({\n        title: 'our project', \/\/ Load a custom template (lodash by default)\n        template: 'src\/custom.html' }),\n    new MiniCssExtractPlugin({\n      filename:\"bundle.css\"}),\n    new CopyPlugin({\n      patterns: [\n        { from: \"src\/img\", to: \"img\" }\n      ]\n    }),\n  ]\n\n...\n\n<\/pre>\n<p>Create a new <code>img<\/code> folder and add images in it. Once the build command is run, the images will be copied to <code>dist\/img<\/code>.<\/p>\n<h2 id=\"debugging-source-map\">Debugging with a source map<\/h2>\n<p>When we <code>build<\/code> to the bundle by compiling TypeScript files into JavaScript files, we might need to debug and test the bundle file using our browser\u2019s DevTool.<\/p>\n<p>When you\u2019re debugging your code on a browser\u2019s DevTool, you\u2019ll notice that only the bundle files appear. Whenever there is an error in our TypeScript code, it\u2019ll only be indicated in the bundle file, making it hard to trace errors back to TypeScript for correction. However, with a source map, we can easily debug TypeScript using our DevTool:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-127715 size-full\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-debug-devtool.png\" alt=\"Typescript Debug Devtool\" width=\"730\" height=\"367\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-debug-devtool.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-debug-devtool-300x151.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<p>Source maps display the original source file, making it easy for us to debug TypeScript and fix bundles and minified JavaScript code.<\/p>\n<p>Source map <code>.map<\/code> files contain details of both the original source files and the bundle files. DevTools uses this file to map the original source file with the bundle file.<\/p>\n<p>To generate <code>.map<\/code> files for the bundle files, we need to configure both webpack and TypeScript. In the TypeScript configuration file, add <code>sourceMap<\/code> to the compiler option and set its value to <code>true<\/code>:<\/p>\n<pre class=\"language-json hljs\">{\n    \"compilerOptions\": {\n        \"noImplicitAny\": true,\n        \"target\": \"ES5\",\n        \"module\": \"ES2015\",\n        \"sourceMap\": true\n    }\n}\n<\/pre>\n<p>Next, we\u2019ll add the <code>devtool<\/code> property to the webpack configuration and set it to <code>true<\/code>, telling webpack to generate an appropriate source map for each bundle file:<\/p>\n<pre class=\"language-json hljs\">module.exports = {\n  devtool: 'source-map',\n   ...\n}\n<\/pre>\n<p>When you run the build command, you\u2019ll be able to debug the original source code directly:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-127718 size-full\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/debug-source-code-build-tool.png\" alt=\"Debug Source Code Build Tool\" width=\"730\" height=\"412\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/debug-source-code-build-tool.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/debug-source-code-build-tool-300x169.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>As TypeScript\u2019s popularity continues to grow, webpack has become an important option for developers looking to optimize their projects. With webpack plugins, we can optimize TypeScript application resources.<\/p>\n<p>In this tutorial, we walked through the step-by-step process of setting up webpack with TypeScript. We also learned how to optimize TypeScript applications using webpack plugins, and we explored debugging our TypeScript code with a source map.<\/p>\n<\/html>\n","protected":false},"excerpt":{"rendered":"<p>Walk through the step-by-step process of setting up webpack with TypeScript and learn how to optimize TypeScript applications using webpack plugins.<\/p>\n","protected":false},"author":156415866,"featured_media":127701,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2147999,1],"tags":[2109715],"class_list":["post-127686","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dev","category-uncategorized","tag-typescript"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.1.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Using webpack with TypeScript - LogRocket Blog<\/title>\n<meta name=\"description\" content=\"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Using webpack with TypeScript - LogRocket Blog\" \/>\n<meta property=\"og:description\" content=\"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/\" \/>\n<meta property=\"og:site_name\" content=\"LogRocket Blog\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-01T17:30:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-06-04T21:05:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png\" \/>\n\t<meta property=\"og:image:width\" content=\"730\" \/>\n\t<meta property=\"og:image:height\" content=\"487\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Popoola Temitope\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Popoola Temitope\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/\",\"url\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/\",\"name\":\"Using webpack with TypeScript - LogRocket Blog\",\"isPartOf\":{\"@id\":\"https:\/\/blog.logrocket.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png\",\"datePublished\":\"2022-09-01T17:30:59+00:00\",\"dateModified\":\"2024-06-04T21:05:21+00:00\",\"author\":{\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/516bcff487379887a7945452a10e3257\"},\"description\":\"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.\",\"breadcrumb\":{\"@id\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#primaryimage\",\"url\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png\",\"contentUrl\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png\",\"width\":730,\"height\":487,\"caption\":\"Typescript Webpack\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/blog.logrocket.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Using webpack with TypeScript\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/blog.logrocket.com\/#website\",\"url\":\"https:\/\/blog.logrocket.com\/\",\"name\":\"LogRocket Blog\",\"description\":\"Resources to Help Product Teams Ship Amazing Digital Experiences\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/blog.logrocket.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/516bcff487379887a7945452a10e3257\",\"name\":\"Popoola Temitope\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/24d4ae2fa30ab86a03656bdf4d03ad52471ae31d4894dbb5b75c2ae379fb2447?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/24d4ae2fa30ab86a03656bdf4d03ad52471ae31d4894dbb5b75c2ae379fb2447?s=96&d=mm&r=g\",\"caption\":\"Popoola Temitope\"},\"description\":\"I'm a software developer and technical writer. I love learning about new technology and am always ready to share ideas with others.\",\"url\":\"https:\/\/blog.logrocket.com\/author\/popoolatemitope\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Using webpack with TypeScript - LogRocket Blog","description":"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/","og_locale":"en_US","og_type":"article","og_title":"Using webpack with TypeScript - LogRocket Blog","og_description":"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.","og_url":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/","og_site_name":"LogRocket Blog","article_published_time":"2022-09-01T17:30:59+00:00","article_modified_time":"2024-06-04T21:05:21+00:00","og_image":[{"width":730,"height":487,"url":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png","type":"image\/png"}],"author":"Popoola Temitope","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Popoola Temitope","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/","url":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/","name":"Using webpack with TypeScript - LogRocket Blog","isPartOf":{"@id":"https:\/\/blog.logrocket.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#primaryimage"},"image":{"@id":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#primaryimage"},"thumbnailUrl":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png","datePublished":"2022-09-01T17:30:59+00:00","dateModified":"2024-06-04T21:05:21+00:00","author":{"@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/516bcff487379887a7945452a10e3257"},"description":"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.","breadcrumb":{"@id":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blog.logrocket.com\/using-webpack-typescript\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#primaryimage","url":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png","contentUrl":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2022\/08\/typescript-webpack.png","width":730,"height":487,"caption":"Typescript Webpack"},{"@type":"BreadcrumbList","@id":"https:\/\/blog.logrocket.com\/using-webpack-typescript\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blog.logrocket.com\/"},{"@type":"ListItem","position":2,"name":"Using webpack with TypeScript"}]},{"@type":"WebSite","@id":"https:\/\/blog.logrocket.com\/#website","url":"https:\/\/blog.logrocket.com\/","name":"LogRocket Blog","description":"Resources to Help Product Teams Ship Amazing Digital Experiences","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blog.logrocket.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/516bcff487379887a7945452a10e3257","name":"Popoola Temitope","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/24d4ae2fa30ab86a03656bdf4d03ad52471ae31d4894dbb5b75c2ae379fb2447?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/24d4ae2fa30ab86a03656bdf4d03ad52471ae31d4894dbb5b75c2ae379fb2447?s=96&d=mm&r=g","caption":"Popoola Temitope"},"description":"I'm a software developer and technical writer. I love learning about new technology and am always ready to share ideas with others.","url":"https:\/\/blog.logrocket.com\/author\/popoolatemitope\/"}]}},"yoast_description":"Learn how to use webpack to compile TypeScript to JavaScript and bundle source code into a single JavaScript file.","_links":{"self":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/127686","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/users\/156415866"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/comments?post=127686"}],"version-history":[{"count":21,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/127686\/revisions"}],"predecessor-version":[{"id":188131,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/127686\/revisions\/188131"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/media\/127701"}],"wp:attachment":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/media?parent=127686"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/categories?post=127686"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/tags?post=127686"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}