Jimp.decoders is undefined with webpack in browser with typescript. How do I fix?

56 Views Asked by At

Jimp works fine for me when not in a browser, but when using webpack and running in a browser, Jimp.decoders (and other fields from Jimp) are undefined.

To reproduce this problem, copy the following files, run "npm run debug", and open "http://localhost:4000" in your browser. You will see that the console.log in "src/index.ts" prints an undefined value for Jimp.decoders.

Thanks in advance for your help.

package.json:

{
   "name": "jimp",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "scripts": {
      "debug": "npm i && webpack-dev-server --mode development",
      "build": "npm i && webpack --mode production"
   },
   "keywords": [],
   "devDependencies": {
      "css-loader": "^6.10.0",
      "html-webpack-plugin": "^5.6.0",
      "mini-css-extract-plugin": "^2.8.0",
      "ts-loader": "^9.5.1",
      "typescript": "^5.3.3",
      "webpack": "^5.90.1",
      "webpack-cli": "^5.1.4",
      "webpack-dev-server": "^4.15.1"
   },
   "dependencies": {
      "jimp": "^0.22.10"
   }
}

webpack.config.js:

const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path');

module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
       {
         test: /\.ts?$/,
         use: 'ts-loader',
         exclude: /node_modules/,
       },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    fallback: {
      "fs": false,
      "path": false,
      "crypto": false,
      "process": false,
    },
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebpackPlugin({
        title: 'Jimp problem', 
        template: 'src/custom.html' }),
    new webpack.DefinePlugin({
      'process.browser': 'true'
    })
  ],
  devServer: {
    static: path.join(__dirname, "dist"),
    compress: true,
    port: 4000,
  },
};

tsconfig.json:

{
    "compilerOptions": {
        "target": "ES5",
        "module": "ES2015",
        "moduleResolution":"node",
        "noImplicitAny": true,
        "allowSyntheticDefaultImports": true,
    }
}

src/index.ts:

import Jimp from "jimp";

console.log(`Jimp.decoders: ${Jimp.decoders}`);

src/custom.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Jimp Test Case</h2>
<p>
See the console output.  Why is Jimp.decoders undefined?
</body>
</html>

I tried various permutations of settings for webpack, typescript, etc but can't find one that works.

0

There are 0 best solutions below