导入css时开玩笑 [英] jest unexpected token when importing css

查看:57
本文介绍了导入css时开玩笑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误SyntaxError: Unexpected token .

在我的代码中

import 'react-dates/lib/css/_datepicker.css'

import 'semantic-ui-css/semantic.min.css'

这些不在我的spec.js中,而是在我的实现代码中,为什么?我运行我的应用程序没有问题,但是尝试运行测试时会开玩笑抛出错误.

those isn't in my spec.js but my implementation code, any clue why? I have no problem running my app but jest throw error when I try to run test.

推荐答案

问题是Jest攻击了这些CSS导入,并试图将它们解析为JavaScript.

The problem is that Jest is hitting these CSS imports and trying to parse them as if they were JavaScript.

意外令牌".之所以出现此消息,可能是因为要阻塞的文件的第一行是CSS类声明,即.datepicker: { ... }.

The "Unexpected token ." message probably comes because the first line of the file it is choking on is a CSS class declaration, i.e. .datepicker: { ... }.

无论如何,如此答案所指出的那样,解决此问题的方法是创建一个包含模块的文件导出一个空对象.我叫我styleMock.js.

Anyway, as pointed out in this answer, the way to get around this is to create a file containing a module which exports an empty object. I called mine styleMock.js.

module.exports = {};

然后,您需要在项目根目录中创建一个jest.config.js文件并添加:

Then, you need to create a jest.config.js file in your project root and add:

module.exports = {
  moduleNameMapper: {
    '\\.(css|less)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
  }
};

moduleNameMapper设置告诉Jest如何解释具有不同扩展名的文件.在这种情况下,我们只需要将其指向刚创建的空文件即可.显然,相应地调整文件的路径.

The moduleNameMapper setting tells Jest how to interpret files with different extensions. In this case we simply need to point it at the empty file we just created. Obviously adjust the path to your file accordingly.

请注意,可以根据需要扩展上面的正则表达式.我的样子:

And note that you can expand the regex above for whichever file endings you need. Mine looks like:

moduleNameMapper: {
  '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
    '<rootDir>/test/jest/__mocks__/fileMock.js',
  '\\.(css|less)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
},

其中fileMock.jsstyleMock.js

或者,您可以使用 jest-transform-stub 之类的模块. ,这对您也有相同的作用.

Alternatively, you could use a module such as jest-transform-stub, which does the same thing for you.

这篇关于导入css时开玩笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆