如何在webpack.mix中配置路径别名?

How to configure path alias in webpack.mix?

解法:

感谢 Karl 和 Ali,我现在可以使用 alias' 而无需创建单独的 webpack.config.js 文件。只需将 alias 添加到 webpack.mix.js,如下所示:

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();

问题:

this post,我了解到您可以在 webpack.mix.js 中配置 @ 路径以表示 vue/laravel 项目中的 assets/resources 文件夹,以便您可以在路径中使用 @ 符号。

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

不幸的是,这会导致以下错误。

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.

我尝试了不同的变体(@assets 等),但我总是得到同样的错误。那我做错了什么?

您没有添加路径包的显式要求,但您应该这样做。确保将以下内容添加到 webpack.config.js 文件的顶部。

const path = require('path');

此外,您可能需要添加 __dirname

const path = require('path');

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

在你的webpack.mix.js中:

...
.alias({'@': 'resources/js'})
...

Import Aliases - Laracasts