簡體   English   中英

無效或意外的令牌“導入” - jest/babel/webpack

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

我有一個 rust 庫我正在嘗試交叉編譯並打包到 npm 腳本中。 我一直在關注使用 wasm 包的過程。 該過程構建了 es6 js,我編寫了一些粗略的測試,然后決定嘗試使用 jest 作為測試運行器,因為我在另一個項目中使用它幾乎沒有問題。

我在嘗試運行測試時遇到了這個問題

    /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';

我開玩笑說

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

開玩笑的調試配置 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"
}

我的 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"
  ]
}

我的開發部門

  "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

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

我的測試很簡單

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);
    });

我的 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"
    }),
  ]
};

我正在嘗試測試的 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;
}

我只能想象 jest 在運行時沒有轉換 js 代碼,但我已經在相關配置中指定了代碼的所有路徑

查看這篇文章SyntaxError: Invalid or unexpected token @import

moduleNameMapper 和模擬 fileMock.js 可能是關鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM