Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's what I'm trying to achieve:

dist
  |- worker.js
src
  |- worker.ts // Compiles to js file in dist folder

I attempted this by using webpack's `DefinePlugin` in my `vue.config.js` like this:

const webpack = require('webpack')

module.exports = {
    configureWebpack: {
        plugins: [
            new webpack.DefinePlugin({
                entry: `${__dirname}/src/worker.ts`,
                module: {
                    rules: [
                        {
                            test: /worker\.ts$/,
                            use: 'ts-loader',
                            exclude: /node-modules/
                        }
                    ]
                },
                resolve: {
                    extensions: ['.ts']
                },
                output: {
                    filename: 'worker.js',
                    path: `${__dirname}/dist`
                }
            })
        ],
        resolve: {
            alias: {
                vue$: 'vue/dist/vue.esm-bundler.js'
            }
        }
    }
}

However, running `npm run build` doesn't include the `worker.ts` file in the `dist` folder at all, not even as a chunk. Any suggestions on how to make this work or if it's even possible? Appreciate any help!

Answer №1

After experimenting with different tools, I found success using esbuild. This tool allowed me to write my web worker in Typescript while easily incorporating classes and functions from my Vue app. What impressed me the most was how quickly it compiled. By simply adding the node ./esbuild.js command to my npm run dev and npm run build scripts, esbuild seamlessly compiled to the public folder prior to the Vue app building process. Take a look at my esbuild.js file below.

const esbuild = require('esbuild')
const { nodeExternalsPlugin } = require('esbuild-node-externals')

const config = {
    entryPoints: ['./src/worker.ts'],
    outfile: 'public/worker.js',
    bundle: true,
    minify: false,
    logLevel: 'silent',
    plugins: [nodeExternalsPlugin()]
}

esbuild.build(config).catch(() => process.exit(1))

If you have any questions or need assistance setting this up, feel free to reach out. I'd be more than happy to help!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

Adding JSON data to an array with a click - a step-by-step guide

As I dive into working with React and integrating API JSON data into my project, I've encountered a small hurdle. I've implemented a function that allows users to enter a search query, resulting in a list of devices associated with their input be ...

Apply a specific style conditionally using Angular's ng-repeat directive

Currently, I am utilizing ng-repeat to iterate through a list of divs and manually adding items to the JSON that is rendering these divs. My goal is to position the last div that I add in the JSON at the location where the mouse cursor is, while keeping th ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

The vuex module has replaced the state field "foo" with another field of the same name located at "foo"

There is a warning showing up in the console that says: [vuex] state field "foo" was replaced by another module with the same name at "foo" Can you explain what this warning indicates and how I may have made an error? ...

What is the best way to transform an array of lists into a neatly organized state?

I recently received a list of breweries from an API call and I am trying to format it into my React state container. Here is what I have so far: state = { breweries: [ {name: Foo, long: 45, lat: -39.239}, ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...

Experiencing complications with an Angular 2 router

When a user logs into the system, they are greeted with a navigation bar featuring options like Dashboard, Customers, and Product. Below is an excerpt from my routes file: app.routing.ts export const router: Routes = [ { path: '', redir ...

Develop a function for locating a web element through XPath using JavaScriptExecutor

I have been working on developing a method in Java Script to find web elements using XPath as the locator strategy. I am seeking assistance in completing the code, the snippet of which is provided below: path = //input[@id='image'] def getElem ...

Learning how to merge two observable streams in Angular2 by utilizing RxJS and the powerful .flatMap method

Within my Angular2 app, I have created an Observable in a Service called ContentService. Here is a simplified version of the code: @Injectable() export class ContentService { constructor(private http:Http, private apiService:ApiService) { th ...

What is the best way to manage classNames dynamically in React with Material-UI?

I am wondering how to dynamically add and remove classes from an img tag. My goal is to change the image automatically every 2 seconds, similar to Instagram's signup page. I am struggling to achieve this using the material-ui approach. Below is a snip ...

What is the best way to refresh the slick jQuery plugin for sliders and carousels?

I am currently facing an issue with two buttons that have the same function. The purpose of these buttons is to retrieve data from an API, convert it to HTML, and then append it to a <div> using jQuery. Finally, the data is displayed using the slick ...

How should I integrate my JS authentication function in Rshiny to enable the app to utilize the outcome?

Currently, I have an Rshiny application set to be published on the server but in order to ensure that a specific user has access, we require an API authentication token. The process of authentication is handled within JS tags outside of the application, wh ...

Having trouble setting $scope after redirecting to a partial template via routing

Looking to create a website that loads all necessary templates upon the initial visit. Currently, I only have one partial template but plan to add more in the future. Despite having just this one template, I'm struggling with binding the data from my ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

Using ngTable within an AngularJS application

While working on my angularjs application, I encountered an issue with ngtable during the grunt build process. It seems that the references are missing, resulting in the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module pa ...