且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jest和React并导入CSS文件时出现SyntaxError

更新时间:2022-04-30 10:36:57

moduleNameMapper是告诉Jest如何解释具有不同扩展名的文件的设置.您需要告诉它如何处理更少的文件.

moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.

在您的项目中创建一个这样的文件(可以根据需要使用其他名称或路径):

Create a file like this in your project (you can use a different name or path if you’d like):

module.exports = {};

此存根是我们将告诉Jest使用的模块,而不是CSS或Less文件.然后更改moduleNameMapper设置并将此行添加到其对象以使用它:

This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:

'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'

现在,Jest会将任何CSS或Less文件视为导出空对象的模块.您也可以做其他事情-例如,如果使用CSS模块,则可以使用Proxy,这样每次导入都会返回导入的属性名称.

Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.

请参阅此指南中的更多内容.

Read more in this guide.