An error occurs with webpack during postinstall when trying to load TypeScript

I have created a custom package that includes a postinstall webpack script as specified in my package.json file:

"scripts": {       
   ...
   "postinstall": "webpack"
}

The webpack configuration looks like this:

const path = require('path');

const { VueLoaderPlugin } = require('vue-loader')

module.exports = {
    target: "node",
    entry: {
        Core: path.resolve(__dirname,'src/Core.ts')
    },
    devtool: 'inline-source-map',
    output: {
      filename: "[name].js",
      chunkFilename: "[name].js",
      libraryTarget: 'commonjs',
      path: path.resolve(__dirname, "dist")
    },
    externals: {
        canvas: "commonjs canvas",
    },
    resolve: {
        extensions: [".js", ".ts"]
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
                exclude: /node_modules/
            },
            {
                test: /\.ts$/,
                use: [{
                    loader: 'ts-loader',
                    options:{
                        configFile: path.resolve(__dirname,"tsconfig.json")
                    }
                }],
                exclude: /node_modules/,
            }
        ]
    },
    mode: 'development',
    plugins: [
        new VueLoaderPlugin(),
    ],
};

Everything works fine when I run the postscript within the package itself. However, when I try to include the package in another project, I encounter a typescript error related to the ts-loader. Any insights on why this might be happening?

ERROR in ./src/Core.ts 32:0
Module parse failed: The keyword 'interface' is reserved (32:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

Answer №1

After some investigation, I was able to identify the root of my issue. Once my project loads in the npm package and the postinstall event is triggered, I noticed that my npm package lacked a readily available node_modules package to utilize ts-loader and other resources.

To address this, I had to adjust my loaders to target my project specifically rather than relying on the npm package. Below is the updated webpack configuration that reflects these changes:

const path = require('path');

const { VueLoaderPlugin } = require('vue-loader')

module.exports = {
    target: "node",
    entry: {
        Core: path.resolve(__dirname,'src/Core.ts')
    },
    devtool: 'inline-source-map',
    output: {
      filename: "[name].js",
      chunkFilename: "[name].js",
      libraryTarget: 'commonjs',
      path: path.resolve(__dirname, "dist")
    },
    externals: {
        canvas: "commonjs canvas",
    },
    resolve: {
        extensions: [".js", ".ts"]
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader'
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.ts$/,
                use: [{
                    loader: 'ts-loader',
                    options:{
                        configFile: path.resolve(__dirname,"tsconfig.json")
                    }
                }]
            }
        ]
    },
    resolveLoader: {
        modules: [path.resolve(__dirname, '../../../node_modules'), path.resolve(__dirname, './node_modules')],
        extensions: ['.ts', '.vue', '.js'],
        mainFields: ['ts-loader', 'vue-loader', 'babel-loader']
    },
    mode: 'development',
    plugins: [
        new VueLoaderPlugin(),
    ],
};

Navigating through webpack without prior knowledge was challenging, so I hope sharing this solution will assist others facing similar issues.

Answer №2

Here is a more simplistic version:

const path = require('path');

module.exports = {
  entry: {
    'my-component': './src/my-component.ts'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: "ts-loader",
        // Ensure "my-component" is not excluded from ts-loader
        exclude: /node_modules\/(?!my-component)/,
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  devtool: 'source-map',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  resolveLoader: {
    modules: [
      path.resolve(__dirname, '..'), 
      './node_modules', 
    ],
  },
};

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 Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

Encountering an unexpected identifier error in Sails JS

As a newcomer to Sails JS, I am attempting to perform CRUD operations with it. However, I am encountering an unexpected error in my index function. I am struggling to identify where the mistake lies. // Usercontroller.js file module.exports = { creat ...

Next.js is perplexing me by throwing an error about Event handlers not being able to be passed to Client Component props, even though the component clearly has "use client" at

My bundler generates a basic React component like this "use client"; "use strict";var a=Object.create;var r=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,s=Objec ...

Building a NestJS/Prisma RESTful API to retrieve data from a related field

I am diving into creating my very own Rest API using Nestjs and Prisma for the first time. This project is a basic representation of an inventory management system, keeping things simple with shelves and boxes to store items. The structure in place has tab ...

Accessing a targeted XML file within a document using Office.js in a Word Add-In

I am struggling to load the file named item1.xml from the ..\customXml folder of my document into my Word Add-In. So far, I have attempted the following: var url = Office.context.document.url + '\\customXml\\item1.xml\& ...

Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system. For instance, the user has already entered these values into the database: ["typescript", "C#", "python"] If they type one of these existing ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

Cannot access Injectable service in Angular2

In the angular2 application, there is a service named HttpClient. The purpose of this service is to include an authorization header in every request sent by the application to endpoints. import { Injectable } from '@angular/core'; import { He ...

A Typescript object that matches types and eventually returns a string when called upon

In the process of overengineering a type that can match either a string or an object whose valueOf() function, when evaluated recursively, ultimately returns a string. type Stringable = string | StringableObject; interface StringableObject { valueOf() ...

Using React Typescript to create a button component with an attached image

I am currently utilizing React with Typescript. How can I incorporate an image into my button? I've attempted to do so without any errors, but the button appears blank. What's the best way to style my button element using Emotion CSS in this ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Error encountered during npm execution: The build command was executed with the following parameters: `react-scripts --max_old_space_size=2048 build`

ERROR: npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deacbbbfbdaaf3bfb3aeb2b7b8a7f3aeacb1b4bbbdaaf3aab6acbbbb9eeef0eff0ee">[email protected]</a> build: `react- ...

Problem encountered with the @ManyToOne and @OneToMany declarations

Hello there! I recently embarked on a new project utilizing TypeScript, TypeORM, and Postgres. Everything seemed to be going smoothly until I encountered some perplexing errors related to a relationship between @ManyToOne and @OneToMany. Below are my entit ...

A guide on loading modules dynamically using React and Typescript from a server

I am working on a React / Typescript / Webpack / React-Router application that contains some large JS modules. Currently, I have two bundles (common.js and app.js) included on every page, with common.js being a CommonsChunkPlugin bundle. However, there is ...

Compiling express js with browserify is not supported

I created a simple express.js application, then attempted to consolidate it into one .js file. After using Browserify to compile everything into a single file, the browserify-compiled code failed to work properly. From my understanding, Browserify simply ...

Issue with closing the active modal in Angular TypeScript

Can you help me fix the issue with closing the modal window? I have written a function, but the button does not respond when clicked. Close Button: <button type="submit" (click)="activeModal.close()" ...

Typescript struggles to identify properties that have no business being there

In my function for formatting data, the "values" contained within this data are clearly defined. However, TypeScript is failing to recognize new properties that are invalid when mapping these values. The issue can be best understood by looking at the code ...

"Developing a stand-alone ASP.NET Core WebAPI with back-end authentication, and creating a React Redux application with front-end authentication that operate autonom

Looking to develop an ASP.NET Core Web API with authentication using ApplicationDbContext as the default database context. I prefer working with Visual Studio for the backend development. 2. Interested in building a React-Redux app with authentication for ...