How to provide global TypeScript classes via WebPack bundle in JS

前端 未结 1 531
失恋的感觉
失恋的感觉 2021-01-13 04:16

I am currently working on TypeScript. I want to replace JS with TS, but I have a lot of JS-Files, so that I only want to create new classes in TS and want to use these in my

相关标签:
1条回答
  • 2021-01-13 04:36

    You need to make use of the expose-loader in order to make your module available through the global scope.


    // File: webpack.config.js
    const path = require('path')
    
    module.exports = {
      context: path.resolve('src'),
      entry: './main.ts',
      module: {
        rules: [
          {
            test: require.resolve('./src/main.ts'),
            use: [{
              loader: 'expose-loader',
              options: 'Library'
            }, {
              loader: 'ts-loader'
            }],
            exclude: /node_modules/
          }
        ]
      },
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
      }
    }
    

    // File: main.ts
    export class Car {
        seats: number;
        passengers: string[];
    
        add(passenger: string) {
            if(this.passengers.indexOf(passenger) === -1) {
                this.passengers.push(passenger);
            }
        }
    }
    

    // File: main.js
    var car = new Library.Car()
    car.seats = 5
    car.add('Pete')
    

    Make sure the code calling the module is included after the module bundle.

    <!-- File: index.html -->
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Webpack App</title>
      </head>
      <body>
        <script type="text/javascript" src="bundle.js"></script>
        <script src="main.js"></script>
      </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题