Guest User

Untitled

a guest
Aug 21st, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. # Hello World in Typescript with Webpack
  2.  
  3. This walkthrough demonstrates how to setup a typescript project with a webpack server using npm.
  4.  
  5. ### Pre-requisites
  6. You need to have node.js / npm installed on your local machine.
  7.  
  8. ### Steps
  9. 1. Create a new ``project`` folder and navigate into it through cmd
  10.  
  11. ```
  12. > mkdir project
  13. > cd project
  14. ```
  15.  
  16. 2. Inside of the ``project`` folder, run the following command and fill out the prompts. This creates a ``package.json`` file for your project.
  17.  
  18. ```
  19. > npm init
  20. ```
  21.  
  22. 3. Install ``typescript`` if not already done.
  23. * `npm i typescript -g` to install globally
  24. * `npm i typescript --save-dev` to install locally for this project
  25. 4. Create your typescript compiler using one of the two commands below. This creates a ``tsconfig.json`` file with default properties populated.
  26. * `tsc --init` to init using globally installed typescript
  27. * `npx tsc --init` to init using local project typescript
  28. 5. Create a new sub-directory in your ``project`` directory called ``src``.
  29.  
  30. ```
  31. > mkdir src
  32. ```
  33.  
  34. 6. Create a new ``main.ts`` file using any text-editor or js IDE within your ``project`` directory. Paste the following (placeholder/example) code in the ``main.ts`` file and save it.
  35.  
  36. ```typescript
  37. const world = 'David';
  38.  
  39. export function hello(word: string = world): string {
  40. return `Hello ${world}! `;
  41. }
  42.  
  43. (function () {
  44. console.log(hello());
  45. }) ();
  46. ```
  47.  
  48. 7. Install webpack, webpack-dev-server, webpack-cli, and ts-loader via npm
  49.  
  50. ```
  51. npm install webpack webpack-dev-server webpack-cli ts-loader --save-dev
  52. ```
  53.  
  54. 8. Create a new ``webpack.config.js`` file in your main ``project`` directory.
  55.  
  56. 9. Open ``webpack.config.js`` in a text-editor or js IDE, paste the following code, and save it.
  57.  
  58. ```typescript
  59. module.exports = {
  60. entry: './src/index.ts',
  61. output: {
  62. filename: 'bundle.js',
  63. path: __dirname
  64. },
  65. module: {
  66. rules: [
  67. {
  68. test: /\.tsx?$/,
  69. loader: 'ts-loader',
  70. exclude: /node_modules/,
  71. },
  72. ]
  73. },
  74. resolve: {
  75. extensions: [".tsx", ".ts", ".js"]
  76. },
  77. };
  78. ```
  79.  
  80. 10. Open up ``package.json`` and add the following line to the ``scripts`` section, then save:
  81.  
  82. ```json
  83. "start": "webpack-dev-server"
  84. ```
  85.  
  86. 11. Run ``> npm start`` from cmd in order to serve the project.
Add Comment
Please, Sign In to add comment