Home > Blockchain >  webpack: transpile web workers in public folder
webpack: transpile web workers in public folder

Time:01-23

I'm next js for my project and it uses webpack 5 to compile typescript codes

I have several web worker scripts inside my public folder under path "/workers/**/*.worker.js"

I was wondering if I can write them in typescript too or at least use babel to transpile them for es5 (for old browsers)

I know that anything under the "public" folder is served as is and as a file (like a CDN)

can I add a "workers" folder to my project and load them in the public path with webpack and next js?

CodePudding user response:

thanks to @nalin-ranjan I've come up with the solution

in my "next.config.js" I added a rule to my webpack config:

module.exports = {
  webpack: (config) => {
    config.module.rules.push({
      test: /\.worker\.ts$/,
      type: 'asset/resource',
      generator: {
        filename: 'static/[hash:5].[name].js',
      },
      use: [
        {
          loader: 'ts-loader',
          options: {
            transpileOnly: true,
            configFile: __dirname   '/worker.tsconfig.json',
          },
        },
      ],
    })
    return config
  },
}

with this rule, I could require my workers and use them as URLs and transpile typescript

also, I had to add a new "tsconfig" that had "isolatedModules" option disabled (because web workers are not modules). for that, I created an identical tsconfig file to next.js but disabled isolatedModules. the reason being that next.js forbids you to disable isolatedModules and resets it back

  •  Tags:  
  • Related