Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack 5 Aliases not resolving correctly

I've just updated my project from webpack 3 to 5 and now none of my imports/aliases are working anywhere.

Webpack is in the root directory.

webpack.config.js Below:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var mode = process.env.NODE_ENV || 'development';
const config = {

  entry: {
    main: path.resolve(__dirname, 'src/index.js'),
    Dashboard: path.resolve(__dirname, 'src/shared/pages/dashboard/index.js'),
    Driver: path.resolve(__dirname, 'src/shared/pages/driver/index.js'),
    Drivers: path.resolve(__dirname, 'src/shared/pages/drivers/index.js'),
    FAQ: path.resolve(__dirname, 'src/shared/pages/faq/index.js'),
    Home: path.resolve(__dirname, 'src/shared/pages/home/index.js'),
    Job: path.resolve(__dirname, 'src/shared/pages/job/index.js'),
    Jobs: path.resolve(__dirname, 'src/shared/pages/jobs/index.js'),
    Signin: path.resolve(__dirname, 'src/shared/pages/signin/index.js')
  } ,
  // performance: {
  //   hints: "error"
  // },
  output: {
    filename: '[name].[contenthash].js'
  },
  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: Infinity,
      minSize: 0,
      cacheGroups: {
        vendor:{
          test: /[\\/]node_modules[\\/]/,
          name(module){
            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
            return `npm.${packageName.replace('@', '')}`;
          }
        }
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: 'babel-loader',
        }
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.s(a|c)ss$/,
        use: [ 'style-loader', 'css-loader','sass-loader'],
      },
      {
          test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
        use: 'url-loader?limit=100000' 
    }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'bundle.scss'}
  ),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "src", "index.html")
  })
  ],
  resolve: {
    alias: {
      shared: path.resolve(__dirname, 'src/shared/'),
      client: path.resolve(__dirname, 'src/client/'),
      server: path.resolve(__dirname, 'src/server/'),
      sass: path.resolve(__dirname, 'src/sass/')
    },
    extensions: ['.js', '.sass', '.scss']
  },
  devtool: (mode === 'development') ? 'inline-source-map' : false,
  mode: mode,
  devServer: {
    disableHostCheck: true,
    historyApiFallback: true,
    inline: true,
    contentBase: path.join(__dirname, "dist"),
    publicPath: '/provider/',
    hot: true,
    proxy: {
      '/api/**': {
        target: 'http://localhost:3333/',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
};


module.exports = config;

Example Import that isn't working:

import { meFromToken } from 'shared/actions/user'

Change that fixes it:

import {meFromToken} from '../../actions/user'

What am I doing wrong? I don't want to refactor all our imports because the aliases aren't resolving properly.

like image 275
Nick Coombe Avatar asked Dec 22 '20 21:12

Nick Coombe


People also ask

What is webpack alias?

Aliasing is webpack's handy way to shave time and keystrokes off importing frequently used modules. You will need the path module, included with node. js, as it is how you will tell webpack where to look for those specific files. Using the resolve. alias property, you can define aliases for frequently imported modules.

What is __ Dirname in webpack?

The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file. The ./ gives the current working directory. It works similar to process.

What is better than webpack?

There are some alternatives to Webpack that provide the same functionality as webpack. These alternatives are gulp, babel, parcel, browserify, grunt, npm, and requireJS.


Video Answer


1 Answers

You'd need to add the same config for tsconfig.json or jsconfig.json

Eg:

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "paths": {
      "@shared/*": ["./src/shared/*"]
    }
  }
}
like image 192
Dexter Nguyen Avatar answered Oct 27 '22 17:10

Dexter Nguyen