3

I'm building a project from scratch on React + TypeScript and using the Webpack Dev server. I want to use relative paths to components, which will be not strict for a more flexible development.

In my App.tsx, I'm trying to import component:

import EntityTypes from "components/EntityTypes/EntityTypes";

and getting an error

Module not found: Error: Can't resolve 'components/EntityTypes/EntityTypes' in '/home/eugene/prj/work/crud-react/src'

File by this path exists (/src/components/EntityTypes/EntityTypes.js) and exports the class like

export default EntityTypes;

My tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    "noImplicitAny": false,
    "module": "commonjs",
    "target": "es5",
    "lib": [
      "es2015",
      "es2017",
      "dom"
    ],
    "removeComments": true,
    "allowSyntheticDefaultImports": false,
    "jsx": "react",
    "allowJs": true,
    "baseUrl": ".",
    "paths": {
      "components/*": [
        "src/components/*"
      ]
    }
  }
}

webpack.config.js:

const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );
module.exports = {
    context: __dirname,
    entry: './src/index.js',
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    output: {
        path: path.resolve( __dirname, 'dist' ),
        filename: 'main.js',
        publicPath: '/',
    },
    devServer: {
        historyApiFallback: true
    },
    module: {
        rules: [
            {
                test: /\.(tsx|ts)?$/,
                loader: 'awesome-typescript-loader'
            },
            {
                test: /\.js$/,
                use: 'babel-loader',
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|j?g|svg|gif)?$/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: path.resolve( __dirname, 'public/index.html' ),
            filename: 'index.html'
        })
    ]
};

I've checked the documentation of typescript about "paths", the file is exists, I don't understand what the problem.

3 Answers 3

3

I have sorted out how to use paths for my files and make them flexible, that I can reorganize the project and manage paths easy without a lot of changes of strict relative paths.

The problem was related to configuration of the webpack. Final configuration is next:

tsconfig.json

{
  "compilerOptions": {
    // ...
    "paths": {
      "~/components/*": [
        "./src/components/*"
      ],
      "~/services/*": [
        "./src/services/*"
      ],
      "~/interfaces/*": [
        "./src/interfaces/*"
      ]
    },
  }
}

webpack.config.js

const path = require('path');
module.exports = {
  // ...
  resolve: {
    // ...
    alias: {
      '~/components': path.resolve(process.cwd(), './src/components'),
      '~/interfaces': path.resolve(process.cwd(), './src/interfaces'),
      '~/services': path.resolve(process.cwd(), './src/services'),
    }
  },
}

Examples of usage

import {IEntities} from "~/interfaces/entities.interface";
// ...
import EntityForm from "~/components/EntityForm/EntityForm";
Sign up to request clarification or add additional context in comments.

Comments

1

Just add tsconfig-paths-webpack-plugin into your webpack configuration:

const { cwd } = require('node:process');
const { resolve } = require('node:path');

const TsconfigPathsWebpackPlugin = require('tsconfig-paths-webpack-plugin');


module.exports = {
    resolve: {
        plugins: [
            new TsconfigPathsWebpackPlugin({
                configFile: resolve(cwd(), './tsconfig.json'),
            })
        ]
    }

};

And you don't need to duplicate paths configuration as webpack aliases.

Comments

-2

You're using absolute imports, not relative ones. Try import EntityTypes from "./components/EntityTypes/EntityTypes";, assuming the file you're importing it into is on the same level as the components directory.

1 Comment

If I will do so, it means that it's just a relative import of the file? What the sense of config in this case? My goal is that I can change the structure of the project, move some folders, but do not edit import in each file, but just update paths in tsconfig.json. Can I acheive it how I described in initial post?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.