我试着解析.css

jest trying to parse .css

本文关键字:css      更新时间:2023-09-26

我有一个笑话的问题,无论我做什么,它一直试图解析css文件为javascript。

使用webpack可以正确构建文件。

对于jest

,我有以下配置
"jest": {
    "rootDir": "./src",
    "moduleNameMapper": {
      "^.*[.](css|CSS)$": "../jest/styleMock.js"
    }
  },

我还尝试了一个脚本预处理器来从导入中剥离css:

 "jest": {
    "rootDir": "./src",
    "scriptPreprocessor": "../node_modules/jest-css-modules"
  },

一直抛出错误。

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button {
                                                                                             ^
    SyntaxError: Unexpected token .

最好的解决方案是在Jest配置中使用moduleNameMapper行,如Jest文档中所述。

一个最小的"忽略css"jest配置,在package.json中,可能像这样

  "jest": {
    "moduleNameMapper": { "''.(css|less)$": "<rootDir>/assets/css/__mocks__/styleMock.js" }
  },

styleMock.js就是这个

module.exports = {};

我不知道这是否是最好的方法,但考虑到我已经被困在这里一段时间了,我把解决方案贴出来了。

为了修复它,我必须做两步:

1) @Jonathan Stray解决方案,因此添加一个指向js mock的moduleNameMapper(参见他的响应以了解更多细节)

2)然后我必须安装jest-css-modules-transform插件,并将其添加到package.json内部的jest配置中,如下所示:

"jest": {
    //...
    "transform": {
        ".+''.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform",
        //...
    },
    //...
}

我使用"jest-css-modules-transform"而且效果很好。

  1. 我必须安装jest-css-modules-transform插件:
npm i --save-dev jest-css-modules-transform

或带纱

yarn add -D jest-css-modules-transform
  • 然后将其添加到jest.config.s中的jest配置中,如下所示:
    module.exports = {
        testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
        setupFilesAfterEnv: ["<rootDir>/setupTests.tsx"],
        transform: {
            "^.+''.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
            '.+''.(css|styl|less|sass|scss)$': 'jest-css-modules-transform'
        }
    };
    
  • 我能够按照官方文档更新我的styleMock以使用代码语法。

    jest.config.js

      transform: {
        '.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
      },
    

    __mocks__/styleMock.js

    module.exports = {
      process() {
        return {
          code: `module.exports = {};`,
        };
      },
    };
    

    你试过babel CLI吗?

    在我的预处理器中,我使用babel-corecanCompile函数从babel-core->utils转换我的代码,并忽略除.js, .es, .jsx等以外的其他文件。

    var babel = require('babel-core');
    var canCompile = babel.util.canCompile
    module.exports = {
        process: function (src, filename) {
        if (!canCompile(filename)) {
            return ''; //ignore this file
        }
    

    也许你的代码也没有转换,这就是为什么你有SyntaxError (babel.transform)?查看jest中的自定义预处理器

    相关文章:
    • 没有找到相关文章