Home > Software design >  Webpack not compiling package in Electron
Webpack not compiling package in Electron

Time:01-12

I'm trying to import and use a package:

import { Shortcuts } from 'shortcuts';

export function bindKeys(): void {
  try {
    Shortcuts.record((sequence: string[]) => console.log('pressed:', sequence));
  } catch (err) {
    console.error(err);
  }
}

and webpack is complaining:

TypeError: shortcuts__WEBPACK_IMPORTED_MODULE_0__.Shortcuts.record is not a function

I'm sure the package is fine, I'm installing and using the package as documented: see here -- if I check the class in the package the record() function is declared:

declare class Shortcuts {
    /**/
    record: (handler: RecordHandler) => Disposer;
    /**/
}

I'm using ts-loader to compile my TS. Here's my webpack config:

const common: Configuration = {
  mode: isDev ? 'development' : 'production',
  resolve: {
    extensions: ['.js', '.ts', '.jsx', '.tsx', '.json'],
  },
  externals: ['fsevents'],
  output: {
    publicPath: './',
    filename: '[name].js',
    assetModuleFilename: 'images/[name][ext]',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
      },
      {
        test: /\.s?css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
      {
        test: /\.png$/,
        type: 'asset/resource',
      },
    ],
  },
  stats: 'errors-only',
  watch: isDev,
  devtool: isDev ? 'source-map' : undefined,
};

And here's my tsconfig:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "esModuleInterop": true,
    "moduleResolution": "Node",
    "lib": ["DOM", "ESNext"],
    "resolveJsonModule": true,
    "jsx": "react-jsx",
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "isolatedModules": true,
    "typeRoots": [
      "./node_modules/@types",
      "./src/types"
    ],
  },
  "include": ["src/**/*"],
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}

CodePudding user response:

{ Shortcuts } is a class and needed to be instantiated. Somehow I missed that in the docs.

import { Shortcuts } from 'shortcuts';
const shortcuts = new Shortcuts();

shortcuts.add([
  {
    shortcut: '4',
    handler: (event) => {
      console.log(event);
    },
  },
]);
  • Related