如何配置 NextJS 以正确处理 scss 中的别名路径?

ugl*_*nky 15 sass nomachine-nx next.js postcss-loader next-images

我在 NX monorepo 中创建了一个 nextjs 应用程序,并开始将现有的 NX 应用程序(在同一个 monorepo 中)移植到其中。

我的 NX monorepo 设置了许多别名,所有别名都在根tsconfig.base.json文件中配置。例如,我将所有图像保存在图像库中,并从 JSX 中像这样加载它们:

import myImage from '@images/myImage.png';
Run Code Online (Sandbox Code Playgroud)

这是我在 SCSS 文件中使用别名的方式:

background-image: url('@images/myImage.png');
Run Code Online (Sandbox Code Playgroud)

这两个应用程序都可以在我现有的非 Nextjs 应用程序中工作,但是,当我将应用程序移植到新的 Nextjs 应用程序时,url()无法识别其中使用的别名。我得到的错误看起来像这样:

Module not found: Can't resolve '../themes/@images/myImage.png'
Run Code Online (Sandbox Code Playgroud)

请注意,我的 css 文件位于其中,./themes因此它将别名@images/...url 视为相对路径并将它们附加到当前文件位置。

在 scss 中使用时正确处理别名路径的推荐方法是什么?

zor*_*404 0

TypeScript 和 SCSS 的别名必须单独配置。


对于 SCSS,您必须在 webpack 配置中配置别名。

在 Next.js 中,您可以在 next.config.js 中修改 webpack 配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
    webpack: (config) =>
    {
        // in my version (v13) I had to write ./@images
        // in your version it may be possible to instead write @images
        config.resolve.alias['./@images'] = '/path/to/images';
        // config.resolve.alias['@images'] = '/path/to/images';

        // in some cases you may need to use path.resolve, but normally it should work without it
        // config.resolve.alias['./@images'] = path.resolve(__dirname, './path/to/images');

        return config;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于 next.js 以外的项目,您通常会有一个 webpack.config.js,然后您可以执行以下操作:

module.exports = {
    resolve: {
        alias: {
            '@images': '/path/to/images'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在官方文档中阅读有关 webpack 中别名的更多信息。


对于 TypeScript,您已经看到可以在 tsconfig.json 中配置别名:

{
  "compilerOptions": {
    "paths": {
      "@images/*": ["/path/to/images/*"],
    }
  }
}
Run Code Online (Sandbox Code Playgroud)