如何配置NextJs以正确处理SCS中的别名路径?
我已经在NX MonorePo中创建了一个NextJS应用程序,并且已经开始将现有的NX应用程序(在同一MonorePo中)移植到它。
我的NX MonorePo设置了许多别名,所有这些都在root tsconfig.base.json.json
文件中配置。例如,我将所有图像都保存在图像库中,然后从JSX中加载它们:
import myImage from '@images/myImage.png';
这就是我在SCSS文件中使用别名的方式:
background-image: url('@images/myImage.png');
这些都在我现有的非Nextjs应用中使用,但是,当我将应用程序移植到新的NextJS应用程序中,未识别url()
中使用的别名。我看起来像这样的错误:
Module not found: Can't resolve '../themes/@images/myImage.png'
请注意,我的CSS文件属于./主题
,因此它将别名@images /...@images /...
urls视为相对路径和附加路径他们到当前的文件位置。
在SCSS中使用时,正确处理别名路径的建议方法是什么?
I've created a nextjs app within my NX monorepo and I've started porting an existing NX app (within the same monorepo) to it.
My NX monorepo is set up with many alias's, all of them configured within the root tsconfig.base.json
file. For instance, I keep all my images in an images library and I load them like this from within JSX:
import myImage from '@images/myImage.png';
This is how I use the aliases from within a SCSS file:
background-image: url('@images/myImage.png');
Both of these work within my existing Non-Nextjs app, however, when I port my app over to the new Nextjs app, the aliases used within url()
are not recognized. The errors I get look like this:
Module not found: Can't resolve '../themes/@images/myImage.png'
Note, my css file lives in ./themes
and so it's treating the aliased @images/...
urls as relative paths and appending them to the current file location.
What is the recommended approach for having the aliased paths handled correctly when used within scss?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于打字稿和SCS的别名必须单独配置。
对于SCS,您必须在WebPack配置中配置别名。
在Next.js中,您可以在Next.Config.js中修改WebPack配置:
对于Next.js以外的其他项目,您通常会有一个WebPack.config.js,您可以这样做:
您可以在<<<<<<< a href =“ https://webpack.js.org/configuration/resolve/#resolvealias” rel =“ nofollow noreferrer”>官方文档。
For TypeScript you already seen that you can configure aliases in tsconfig.json:
Aliases for TypeScript and for SCSS have to be configured separately.
For SCSS you have to configure aliases in the webpack config.
In Next.js you can modify webpack config in next.config.js:
For projects other than next.js you would usually have a webpack.config.js and there you would do:
You can read more about aliases in webpack on the official docs.
For TypeScript you already seen that you can configure aliases in tsconfig.json: