【问题标题】:How to fix "SyntaxError: Invalid or unexpected token @import"?如何修复“SyntaxError: Invalid or unexpected token @import”?
【发布时间】:2017-11-28 21:42:56
【问题描述】:

我正在尝试将 Jest 和 Enzyme 添加到 React webpack 项目中。

一切正常,直到我向组件添加测试,使用导入谷歌字体的样式表。

我得到的错误是:

● Test suite failed to run
    /Users/dev/Code/Git/react-redux-webpack/src/App.sass:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){@import url('https://fonts.googleapis.com/css?family=Barlow+Condensed')
                                                                                             ^
    SyntaxError: Invalid or unexpected token

sass 文件如下所示:

@import url('https://fonts.googleapis.com/css?family=Barlow+Condensed')

body
    background: #f9f9f9
    color: #444444
    font-family: 'Barlow Condensed', sans-serif
    text-align: center

.container
    width: 100%
    max-width: 960px
    margin: 0 auto

.container__logo--image
    position: absolute
    top: 50%
    left: 50%
    margin-left: -75px
    margin-top: -75px

我的.babelrc:

{
  "presets": [
    "react",
    "stage-0",
    [
      "env",
      {
        "targets": {
          "node": "6.10",
          "browsers": ["last 2 versions", "safari >= 7"]
        }
      }
    ]
  ],
  "plugins": ["transform-class-properties"]
}

我在 webpack 中有所有必需的加载器,我可以整天构建和服务 sass,没有任何问题。这是我正在努力解决的 Jest 的介绍。

我已经推送了一个带有当前代码状态的分支https://github.com/nombienombie/react-redux-webpack/tree/feature/jest-unit-tests

【问题讨论】:

    标签: reactjs webpack jestjs enzyme


    【解决方案1】:

    我在 package.json 中添加了以下内容:

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

    并在 mocks 文件夹中添加以下内容:

    fileMock.js

    module.exports = 'test-file-stub';
    

    styleMock.js

    module.exports = {}
    

    【讨论】:

    • 如何找到根目录?
    【解决方案2】:

    由于它们不是由 Webpack 编译的,因此应该以某种方式处理通过测试导入的静态资产。

    典型的方法包括模拟它们,因为它们与测试目的无关。开玩笑公开moduleNameMapper 选项以轻松模拟/代理它们。

    【讨论】:

      【解决方案3】:

      在@Harry 给出的答案上还要补充一点,

      如果您使用的是jest.config.js 文件,则添加它而不是package.json

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 2016-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-21
        • 1970-01-01
        相关资源
        最近更新 更多