webpack: the core of webpack, can compile ts files to js files and bundle the generated js files.
webpack-cli: a command line interface for webpack.
webpack-dev-server: a webpack development server, that will: starts webpack, watches files for changes, trigger webpack recompile on change, serves files.
typescript: it is recommended to have specific typescript version installed per project, so you make sure that the project uses the same versions regardless of the global version installed.
ts-loader: webpack uses ts-loader (which in turn uses tsc under the hood) to compile ts files to js files.
{"compilerOptions":{"target":"es5","module":"es2015","outDir":"./dist","sourceMap":true// "rootDir": "./src", /** should be controlled by webpack */}}
add webpack.config.js at the root of the project:
module.exports={entry:"./src/index.ts"/** entry point of your project, where webpack will start to look for files to bundle */,output:{/** output configuration, where webpack will put the bundled files */filename:"bundle.js",path:__dirname+"/dist",},module:{/** module configuration, tells webpack what to do with the files it find */rules:[{// tstest:/\.ts?$//** regex to match the files that webpack will process */,use:"ts-loader"/** use ts-loader to compile ts files to js files */,exclude:/node_modules//** exclude node_modules from the bundle */,},],},resolve:{/** resolve configuration, tells webpack how to find modules */extensions:[".ts",".js"]/** extensions that webpack will look for when importing modules */,},devtools:"inline-source-map"/** source-map is a tool that allows you to see the original code in the bundled code */,mode:"development",/** development or production, production is faster and less verbose */,devServer:{/** devserver configuration, tells webpack how to serve the files */static:{directory:path.join(__dirname),/** directory to serve index.html file from */},compress:false,port:9000,devMiddleware:{publicPath:"/dist/",/** path to generated files */writeToDisk:true,/** write generated files to disk */},},};
using webpack you must remove file extensions from import statements, so that webpack can find the correct file to bundle.
update package.json:
{"Scripts":{"build":"webpack --mode production --config webpack.prod.js",// compile ts files to js files, and bundle them"start:dev":"webpack-dev-server --mode development --config webpack.dev.js"// compile ts files to js files, and bundle them and serve them}}
webpack.config.plugins: extra extensions that will be applied to the entire project level.
webpack.config.module: rules that will be applied to the modules level.
clean-webpack-plugin: cleans the dist folder before each build. npm i -D clean-webpack-plugin
// webpack.config.jsconstCleanWebpackPlugin=require("clean-webpack-plugin");//imports don't work in webpack.config.js, but require doesmodule.exports={// ...plugins:[newCleanWebpackPlugin({}),// clean the dist folder before each build],};