Jest and SCSS variables

一曲冷凌霜 提交于 2020-12-12 01:08:01

问题


I'm using Jest in my project and got stuck on one test which contains SCSS variable.

$grey-light: #C7C7C7;

I get this Jest error:

Jest encountered an unexpected token

and it points on the previous mentioned line of code.


回答1:


I ran into this as well and it was solved by using the identity-obj-proxy package:

https://github.com/keyz/identity-obj-proxy

Just follow the instructions in the Jest docs:

https://jestjs.io/docs/en/webpack#mocking-css-modules

And should run the tests with no issues regarding the .scss files import statements. All you have to do is include the jest configuration in your package.json file:

{
  "name": "...",
  "version": "0.0.0",
  "description": "...",
  "main": "index.js",
  "scripts": {
    "start": "webpack --config webpack.config.js",
    "test": "jest"
  },
  "jest": {
    "moduleNameMapper": {
      "\\.(css|scss|less)$": "identity-obj-proxy"
    }
  },
  "keywords": [],
  "author": "Homer Jay",
  "license": "MIT",
  "devDependencies": {},
  "dependencies": {}
}

And the .scss imports will work as expected and any variable or mixin won't throw an error.




回答2:


Sass helps you write more organized and maintainable code, but it's not a vaild css code, thus, browsers don't know how to read it.

scss files needs to be compiled into css, and you need to import and use the css files. For example, the parameter you define has the #C7C7C7 value. The compiler will replace that parameter with that value so the final css will only contain hard-coded values



来源:https://stackoverflow.com/questions/52420683/jest-and-scss-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!