I’m working on a JavaScript project and I’m having trouble configuring Webpack to correctly resolve path aliases that I’ve set up in my jsconfig.json file. Here’s the situation:
Setup:
Project Structure:
project-root/src/pages/home.jsx
jsconfig.json
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"baseUrl": "src",
"paths": {
"@page/*": ["pages/*"]
}
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"build"
]
}
webpackconfig.js
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
alias: {
'@page': path.resolve(__dirname, 'src/pages/')
},
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
}
]
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000
},
mode: 'development'
};
Problem:
Despite setting up the alias for @page in both jsconfig.json and webpack.config.js, I’m getting the following error when trying to run the project:
Module not found: Error: Can't resolve '@page/home' in 'C:UsersHIMANSHU RAJOneDriveDesktopInterior Designfrontendsrc'
What I’ve Tried:
Verified that the file home.jsx exists in the src/pages/ directory.
Checked for typos in file names and paths.
Restarted the development server and cleared cache.
Questions:
Is my Webpack configuration correct for handling path aliases?
Are there any additional settings I need to apply for Webpack to resolve these aliases?
Could there be an issue with the way path aliases are set up in jsconfig.json affecting Webpack?
Any help or advice would be greatly appreciated!
I think you are missing .babelrc
file to resolve your aliases.
Add the following to your .babelrc
file:-
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [
[
"module-resolver",
{
"root": ["./src"],
"alias": {
"@page": "./src/pages"
}
}
]
]
}
Also, do
npm install --save-dev babel-plugin-module-resolver
This should resolve your problem. You can also refer to this thread