首页 > 解决方案 > NextJS & CSS SyntaxError: Unexpected token

问题描述

我正在尝试进行单元测试,但我可以阻止错误抛出的唯一方法是注释掉该import './styles.css行。

一旦我把它放回去,我得到:

Jest encountered an unexpected token

...

 SyntaxError: Unexpected token.

      1 | import React from 'react';
      2 | import PropTypes from 'prop-types';
    > 3 | import './styles.css';
        | ^
      4 |
      5 |

我已经配置了 webpack、babel、jest、enzyme,但谷歌搜索告诉我运行应用程序(通过 webpack)和使用 .css 文件运行可以读取.css文件的测试之间存在差异,这需要单独配置。

为了爱和金钱,我找不到import './styles.css成功导入并通过测试的示例。

任何人都可以帮忙吗?

标签: reactjswebpackjestjsnext.js

解决方案


设法通过点击https://github.com/eddyerburgh/jest-transform-stub来完成这项工作

我的 jest.config.js 现在看起来像这样:


module.exports = {
    setupFiles: ['<rootDir>/jest.setup.js'], // links to normal "configure({ adapter: new Adapter() })" stuff.

    testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'], // ignores test files in .next(js) & node modules

    transform: {
      "^.+\\.js$": "babel-jest", // anything .js is babel'd for jest to consume
      "^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub" // anything style related is ignored and mapped to jest-transform-stub module
    },
    moduleNameMapper: {
      '\\.css$': '<rootDir>/EmptyModule.js' // <-- had to pop this in the following day to get any separetly imported .css files mapped to an empty module / object. So if i try to do import 'react-style-module/styles/my-styles.css' it would fail, though 'import './styles.css' worked. Now with this mapped correctly also, everything is imported/mapped/passing successfully.
    } 
  }

如果其他人有其他更整洁的解决方案,请告诉我。X


推荐阅读