Saturday 23 February 2019

How to create single page web application with typescript and webpack?

I have been creating single page applications in Angular for some time, and now I would like to create a single page application but without using the entire framework.

I would like to have one .html file, and one javascript file, which would be compiled typescript file, say index.ts. And inside index.ts I would import things from other typescript files.

Are there any projects online which are similar to what I want to achive, and is it possible to setup npm project like this at all?

Edit:

After some time, this is what I accomplished: My project structure:

├── bundle.js
├── functions.ts
├── index.html
├── index.ts
├── package.json
├── style.css
├── tsconfig.json
└── webpack.config.js

package.json

{
  "name": "rxjs6-demo",
  "version": "1.0.0",
  "main": "index.ts",
  "scripts": {
    "start": "webpack-dev-server --open"
  },
  "devDependencies": {
    "ts-loader": "^5.3.1",
    "typescript": "^3.2.2",
    "webpack": "^4.27.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10"
  },
  "dependencies": {
    "rxjs": "^6.4.0"
  }
}

tsconfig.json

{
    "compilerOptions": {
      "outDir": ".",
      "noImplicitAny": false,
      "sourceMap": true,
      "module": "es6",
      "target": "es6",
      "allowJs": true
    },
    "include": ["*.ts"],
    "exclude": []
}

webpack.config.json

module.exports = {
  entry: './index.ts',
  output: {
    filename: 'bundle.js'
  },
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: '.'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ]
  }
};

index.html

<html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <script src="bundle.js"></script>
</body>
</html>

running npm start will start a webpack-dev-server which recompiles my application each time any typescript file changes. Inside index.ts I can import stuff from other .ts files. But what I couldn't accomplish is making webpack-dev-server reload my app in the browser when html or css files change.

Any help or general suggestions about the structure of my application will be greatly appreciated.



from How to create single page web application with typescript and webpack?

No comments:

Post a Comment