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

What is the best way to implement lazy loading for child components in React's Next.js?

I am exploring the concept of lazy loading for children components in React Next JS. Below is a snippet from my layout.tsx file in Next JS: import {lazy, Suspense} from "react"; import "./globals.css"; import type { Metadata } from &quo ...

Incorporating AngularFire2 in the latest Angular 11.0.5 framework

I have been attempting to utilize Firebase as a database for my angular application. Following the guidance provided in these instructions (located on the official developers Github page), I first installed npm install angularfire2 firebase --save in my p ...

Having trouble installing npx create-react-app with yarn?

When setting up my React app, I initially used npx create-react-app <app-name> with npm, even though I have yarn installed on my computer. The React app was previously installed using yarn. npm version: 8.3.0 node version: 17.3.0 yarn version: 1.22.1 ...

trouble with file paths in deno

I was attempting to use prefixes for my imports like in the example below: "paths": { "~/*": ["../../libs/*"], "@/*": ["./*"] } However, I keep encountering an error message say ...

What is the best way to represent a state with two possible fields in React using TypeScript?

There is a specific state item that can have its own value or reference another item using an ID. interface Item { itemName: string; itemValue: { valLiteral: number } | { idNumber: string }; } const indItem1: Item = { itemName: "first sample&quo ...

Encountered an issue when attempting to launch a Nest.js application on an EC2 instance

Run Command: npm run start:dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c4f594e4a594e7c0c120c120d">[email protected]</a> start:dev > cross-env NODE_ENV=development nest start --watch node:events:48 ...

Accessing a variable within a function in Angular

Recently I started working with Angular and encountered an issue while trying to access a variable inside a function. Below is the code snippet that's causing me trouble: mergeImages() { var imgurl; var canvas: HTMLCanvasElement = this.canv ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Error in typography - createStyles - 'Style<Theme, StyleProps, "root"

I'm encountering an error in a small React app. Here is a screenshot of the issue: The project uses "@material-ui/core": "4.11.3". In the codebase, there is a component named Text.tsx with its corresponding styles defined in Text.styles.tsx. The styl ...

Issue with module exports not being defined in IE11/Edge

I am experiencing difficulties with an npm module that was updated to ES2015. My application is built in ES2015, bundled by browserify, and compiled with babelify. I am currently trying to upgrade a npm module called credit-card for validation, which has ...

Launching a React Native application on a fresh machine

I've been working on a brand new react-native app, starting with Expo from the beginning. After putting everything in source control and opening it on a Mac, I encountered some warnings when running npm install: npm WARN <a href="/cdn-cgi/l/email ...

The combination of Grunt and Babel runs smoothly, but fails to produce any results

I'm fairly new to the world of grunt and npm. After diving into the documentation, I managed to create my own package.json and a Gruntfile.js. This is how my directory structure looks: / |- src |- myfile.es6 |- anotherfile.es6 |- etc. |- ...

combine two separate typescript declaration files into a single package

Can anyone help me figure out how to merge two typescript definition packages, @types/package-a and @types/package-b, into one definition package? package-a.d.ts [export package-a {...}] package-b.d.ts [exports package-b {...}] package-mine.d.ts [ export ...

Is it considered best practice to include try/catch blocks within the subscribe function in RxJs?

Imagine we have an Angular 2 application. There is a service method that returns data using post(), with a catch() statement to handle any errors. In the component, we are subscribing to the Observable's data: .subscribe( ()=> { ...

Having trouble initializing the Flask environment

Currently working on a React project, but decided to test the Flask environment first. Here's how my directories are structured: api |app |_py_cache | .flaskenv | api.py |venv My api.py file looks like this: import time ...

Tips for successfully importing $lib in SvelteKit without encountering any TypeScript errors

Is there a way to import a $lib into my svelte project without encountering typescript errors in vscode? The project is building and running smoothly. import ThemeSwitch from '$lib/ThemeSwitch/ThemeSwitch.svelte'; The error message says "Canno ...

How to Restrict the Number of Rows Displayed in an Angular 4 Table

Currently, I am faced with a situation where I have a lengthy list of entries that I need to loop through and add a row to a table for each entry. With about 2000 entries, the rendering process is slowing down considerably. Is there a way to limit the disp ...

Troubleshooting problem with installing Nebular theme on Angular 14

There was an issue resolving the dependency tree for npm with error code ERESOLVE. While trying to resolve the dependencies for [email protected], it was found that @angular/[email protected] version 14.2.0 is required at the root level, but th ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...