简体   繁体   English

无效或意外的令牌“导入” - jest/babel/webpack

[英]Invalid or unexpected token 'import' - jest/babel/webpack

I have a rust library I am trying to cross-compile and pack into a npm script.我有一个 rust 库我正在尝试交叉编译并打包到 npm 脚本中。 I have been following the process of using the wasm pack.我一直在关注使用 wasm 包的过程。 The process builds the es6 js, I wrote some crude tests, then decided to try to use jest as a test runner as I am using it in another project with little issue.该过程构建了 es6 js,我编写了一些粗略的测试,然后决定尝试使用 jest 作为测试运行器,因为我在另一个项目中使用它几乎没有问题。

I face this issue when trying to run my tests我在尝试运行测试时遇到了这个问题

    /Users/nsh/WebstormProjects/wasm-ed25519ph/pkg/index_bg.wasm:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){


    SyntaxError: Invalid or unexpected token

    > 1 | import * as wasm from './index_bg.wasm';

I run jest as我开玩笑说

jest --config ./jest.config.json --detectOpenHandles --debug

the jest debug config output开玩笑的调试配置 output

{
  "configs": [
    {
      "automock": false,
      "browser": false,
      "cache": true,
      "cacheDirectory": "/var/folders/w1/hmxby_9x2h18qmm4fbgq3x1m0000gn/T/jest_dx",
      "clearMocks": false,
      "coveragePathIgnorePatterns": [
        "/node_modules/"
      ],
      "detectLeaks": false,
      "detectOpenHandles": true,
      "errorOnDeprecated": false,
      "filter": null,
      "forceCoverageMatch": [],
      "globals": {
        "NODE_ENV": "test"
      },
      "haste": {
        "providesModuleNodeModules": []
      },
      "moduleDirectories": [
        "node_modules",
        "pkg"
      ],
      "moduleFileExtensions": [
        "js"
      ],
      "moduleNameMapper": {},
      "modulePathIgnorePatterns": [],
      "modulePaths": [
        "/Users/nsh/WebstormProjects/wasm-ed25519ph/src",
        "/Users/nsh/WebstormProjects/wasm-ed25519ph/node_modules"
      ],
      "name": "fe4b74ef875c6e51570f003f6fb06c94",
      "prettierPath": null,
      "resetMocks": false,
      "resetModules": false,
      "resolver": null,
      "restoreMocks": false,
      "rootDir": "/Users/nsh/WebstormProjects/wasm-ed25519ph",
      "roots": [
        "/Users/nsh/WebstormProjects/wasm-ed25519ph"
      ],
      "runner": "jest-runner",
      "setupFiles": [
        "/Users/nsh/WebstormProjects/wasm-ed25519ph/node_modules/regenerator-runtime/runtime.js"
      ],
      "setupTestFrameworkScriptFile": null,
      "skipFilter": false,
      "snapshotSerializers": [],
      "testEnvironment": "jest-environment-jsdom",
      "testEnvironmentOptions": {},
      "testLocationInResults": false,
      "testMatch": [],
      "testPathIgnorePatterns": [
        "/node_modules/"
      ],
      "testRegex": "((\\.|/*.)(spec))\\.js?$",
      "testRunner": "/Users/nsh/WebstormProjects/wasm-ed25519ph/node_modules/jest-jasmine2/build/index.js",
      "testURL": "http://localhost",
      "timers": "real",
      "transform": [
        [
          "^.+\\.(js)$",
          "/Users/nsh/WebstormProjects/wasm-ed25519ph/node_modules/jest-config/node_modules/babel-jest/build/index.js"
        ]
      ],
      "transformIgnorePatterns": [
        "/node_modules/"
      ],
      "watchPathIgnorePatterns": []
    }
  ],
  "globalConfig": {
    "bail": false,
    "changedFilesWithAncestor": false,
    "collectCoverage": false,
    "collectCoverageFrom": null,
    "coverageDirectory": "/Users/nsh/WebstormProjects/wasm-ed25519ph/coverage",
    "coverageReporters": [
      "json",
      "text",
      "lcov",
      "clover"
    ],
    "coverageThreshold": null,
    "detectLeaks": false,
    "detectOpenHandles": true,
    "errorOnDeprecated": false,
    "expand": false,
    "filter": null,
    "globalSetup": null,
    "globalTeardown": null,
    "listTests": false,
    "maxWorkers": 3,
    "noStackTrace": false,
    "nonFlagArgs": [],
    "notify": false,
    "notifyMode": "always",
    "passWithNoTests": false,
    "projects": null,
    "rootDir": "/Users/nsh/WebstormProjects/wasm-ed25519ph",
    "runTestsByPath": false,
    "skipFilter": false,
    "testFailureExitCode": 1,
    "testPathPattern": "",
    "testResultsProcessor": null,
    "updateSnapshot": "new",
    "useStderr": false,
    "verbose": true,
    "watch": false,
    "watchman": true
  },
  "version": "23.6.0"
}

my jest.config.json我的 jest.config.json

{
  "testRegex": "((\\.|/*.)(spec))\\.js?$",
  "transform": {
    "^.+\\.(js)$": "babel-jest"
  },
  "globals": {
    "NODE_ENV": "test"
  },
  "verbose": true,
  "moduleFileExtensions": [
    "js"
  ],
  "moduleDirectories": [
    "node_modules",
    "pkg"
  ],
  "modulePaths": [
    "<rootDir>/pkg",
    "<rootDir>/node_modules"
  ]
}

my dev deps我的开发部门

  "devDependencies": {
    "@wasm-tool/wasm-pack-plugin": "1.0.0",
    "babel-eslint": "^10.0.3",
    "babel-jest": "^24.9.0",
    "babel-loader": "7.1.5",
    "babel-plugin-transform-async-to-generator": "^6.24.1",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-es2015-classes": "^6.24.1",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-jest": "23.2.0",
    "copy-webpack-plugin": "^5.0.5",
    "eslint": "^6.6.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-plugin-babel": "^5.3.0",
    "eslint-plugin-import": "^2.18.2",
    "jest": "23.6.0",
    "rimraf": "^3.0.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  }

.babelrc .babelrc

{
  "presets": ["jest", "env"],
  "plugins": [
    "transform-runtime",
    "transform-async-to-generator",
    "transform-class-properties",
    "transform-es2015-modules-commonjs"
  ]
}

my test is simple我的测试很简单

import { sign, sign_sig_and_public_key, verify, public_key_from_private } from '../pkg/index.js';
import {bytesFromHexString, bytesFromString} from './utils.js'

describe('the library can produce and validate signatures', function () {
    it('should produce a valid signature when signing a message', function () {
        const message = bytesFromString("hello");
        const context1 = bytesFromString("context");
        const private_key = bytesFromHexString("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
        const context1_length = context1.length;
        const signature = new Uint8Array(64);
        const result = sign(signature, private_key, message, context1, context1_length);
        console.log("sucessful result should be 418: ", result);
    });

my webpack.config.js我的 webpack.config.js

const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");

const dist = path.resolve(__dirname, "dist");

module.exports = {
  mode: "production",
  stats: {
    colors: true
  },
  devtool: 'source-map',
  entry: {
    index: "./js/index.js"
  },
  output: {
    path: dist,
    filename: "[name].js"
  },
  devServer: {
    contentBase: dist,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: [
          path.resolve(__dirname, "pkg")
        ],
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  },
  plugins: [
    new CopyPlugin([
      path.resolve(__dirname, "static")
    ]),
    new WasmPackPlugin({
      crateDirectory: __dirname,
      extraArgs: "--scope catalyst --target browser"
    }),
  ]
};

a snippet of the output es6 I'm trying to test我正在尝试测试的 output es6 的片段

import * as wasm from './index_bg.wasm';

let cachegetUint8Memory = null;
function getUint8Memory() {
    if (cachegetUint8Memory === null || cachegetUint8Memory.buffer !== wasm.memory.buffer) {
        cachegetUint8Memory = new Uint8Array(wasm.memory.buffer);
    }
    return cachegetUint8Memory;
}

I can only imagine that jest is not transforming the js code when running but I have specified all the paths to the code in the relevant config我只能想象 jest 在运行时没有转换 js 代码,但我已经在相关配置中指定了代码的所有路径

Review this post SyntaxError: Invalid or unexpected token @import查看这篇文章SyntaxError: Invalid or unexpected token @import

moduleNameMapper and a mock fileMock.js is likely the key. moduleNameMapper 和模拟 fileMock.js 可能是关键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM