1

I am trying to build a server side rendering app with React, Typescript and Webpack 5.

I am using asset/resource to load images on my views, at first it threw the following error while building the client:

> Cannot find module '../../assets/images/demo.png' or its corresponding type declarations.

Declaring the modules for each one of the image extensions on a d.ts file like they suggest here fixed it. The error that appeared on vs code dissapeared and building the client work fine.

The problem is that the error persists when I compile the server with ts-node. Is there a reason why ts-node does not recognize the image extensions I defined on the d.ts file?

Here is how the file looks like:

declare module '*.png';
declare module '*.jpg';
declare module '*.svg';
declare module '*.gif';

declare module 'asset-require-hook'; // I was planning to use this to load the file names on the server side

And here is my webpack configuration:

const config = {
  entry: entryPoints,
  mode: 'development',
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, './public/assets'),
    publicPath: '/',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendor: {
          name: 'vendor',
          chunks: 'all',
          reuseExistingChunk: true,
          minChunks: Object.keys(entryPoints).length * 0.8,
          filename: '[name].js',
          test: /[\\/]node_modules[\\/]/,
        },
      }
    },
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
      },
      {
        test: /\.(s*)css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.(png|gif|jpg|svg)$/,
        type: 'asset/resource',
        generator: {
          filename: 'images/[name].[hash][ext]',
          emit: true,
        },
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin(),
  ],
}

0 Answers0