How to configure path alias in webpack.mix?

Viewed 1347

Solution:

Thanks to both Karl & Ali I can now use alias' without having to create a seperate webpack.config.js file. Just add the alias to webpack.mix.js like so:

const mix = require('laravel-mix');
const path = require('path');

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css')
    .alias({'@': 'resources/'})
    .webpackConfig({resolve: {alias: {'@': path.resolve('resources/')}}})
    .vue();

Question:

From this post, I learned that you could configure your @ path in webpack.mix.js to represent the assets/resources folder in a vue/laravel project so that you can use the @ symbol in your paths.

mix.webpackConfig({
  resolve: {
    alias: {
      '@resources': path.resolve('resources'),
    },
  },
})

Unfortunately, this leads to the following error.

yarn run v1.22.17 $ mix watch [webpack-cli] ReferenceError: path is not defined at Object. (/Users/artur/PhpstormProjects/safa-ameedee.com/webpack.mix.js:16:21) at Module._compile (node:internal/modules/cjs/loader:1097:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:999:19) at require (node:internal/modules/cjs/helpers:102:18) at module.exports (/Users/artur/PhpstormProjects/safa-ameedee.com/node_modules/laravel-mix/setup/webpack.config.js:11:5) at loadConfigByPath (/Users/artur/PhpstormProjects/safa-ameedee.com/node_modules/webpack-cli/lib/webpack-cli.js:1747:27) at async Promise.all (index 0) error Command failed with exit code 2.

I've tried different variations (@assets etc.), but I always get the same error. So what am I doing wrong?

2 Answers

You're not adding the explicit require of the path package, but you should do so. Make sure you add the following to the top of your webpack.config.js file.

const path = require('path');

Also, you may need to add __dirname.

const path = require('path');

mix.webpackConfig({
    resolve: {
        alias: {
            '@resources': path.resolve(__dirname, 'resources/')
        }
    }
});
Related