Web Worker - 玩笑 - 无法在模块外部使用“import.meta”

Byr*_*pez 6 reactjs webpack jestjs babel-jest next.js

我正在开发一个nextjs 10.1.3内置的网络应用程序。我们实施了一个网络工作人员来提高其中一个页面的性能,并且计划继续添加更多工作人员;此外,所有代码都经过了正确的单元测试,并且使用worker-loader以前的 webpack 版本(第 4 版及以下版本)我们能够对其进行测试。

随着新的 webpack 5 版本,worker-loader不再需要该插件;相反,使用新版本加载 Web Worker 的方法是new Worker(new URL("@/workers/task.worker.js", import.meta.url));

这样做,我的代码可以按预期工作npm build && npm start;但是,当我尝试添加相应的单元测试时,出现以下错误:Cannot use 'import.meta' outside a module并且所有发生的事情都是因为import.meta.url用于在浏览器中添加工作人员的位置。

我在网上读了很多有关的帖子,babel但我想摆脱这个选项。还有其他选择来嘲笑import.meta.url笑话吗?

任何帮助将非常受欢迎。这是当前的配置。

包.json

{
  ...
    "@babel/core": "^7.8.6",
    "next": "^10.1.3",
    "react": "^16.13.0",
    "webpack": "^5.37.1"
    "devDependencies": {
        ...
        "enzyme": "^3.11.0",
        "enzyme-adapter-react-16": "^1.15.2",
        "jest": "^24.9.0",
        "jest-cli": "^25.1.0",
        ...
    }
  ...
}
Run Code Online (Sandbox Code Playgroud)

next.config.js

const {
...
} = process.env;

const basePath = "";
const COMMIT_SHA = [];

const { parsed: localEnv } = require("dotenv").config();
const webpack = require("webpack");
const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
});

const nextConfig = {
  env: {
    NEXT_PUBLIC_COMMIT_SHA: COMMIT_SHA,
  },
  images: {
    domains: [
      "...",
    ],
  },
  future: {
    webpack5: true,
  },
  productionBrowserSourceMaps: true,
  trailingSlash: true,
  reactStrictMode: true,
  webpack: (config, options) => {
    if (localEnv) {
      config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
    } else {
      config.plugins.push(new webpack.EnvironmentPlugin(process.env));
    }
    config.module.rules.push({
      test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
      use: {
        loader: "url-loader",
        options: {
          limit: 100000,
          name: "[name].[ext]",
        },
      },
    });

    config.output = {
      ...config.output,
      chunkFilename: options.isServer
        ? `${options.dev ? "[name]" : "[name].[fullhash]"}.js`
        : `static/chunks/${options.dev ? "[name]" : "[name].[fullhash]"}.js`,
      publicPath: `/_next/`,
      globalObject: `(typeof self !== 'undefined' ? self : this)`,
    };

    config.plugins.push(new webpack.IgnorePlugin(/pages.*\/__tests__.*/));

    config.plugins.push(
      new options.webpack.DefinePlugin({
        "process.env.NEXT_IS_SERVER": JSON.stringify(
          options.isServer.toString()
        ),
      })
    );

    return config;
  },
};

module.exports = withBundleAnalyzer(nextConfig);
Run Code Online (Sandbox Code Playgroud)

工人useEffect

useEffect(() => {
    if (pageData.data?.length) {
      workerRef.current = new Worker(new URL("@/workers/task.worker.js", import.meta.url));
      workerRef.current.addEventListener("message", result => {
        if (result.error) {
          setWorkerError();
        } else {
          updateData(result.data);
        }
      });
      
      const ids = pageData.data.map(store => store.id);

      workerRef.current.postMessage(ids);
    } else {
      setNoDataFound();
    }

    return () => {
      workerRef.current && workerRef.current.terminate();
    };
  }, []);
Run Code Online (Sandbox Code Playgroud)

笑话配置.js

module.exports = {
  moduleDirectories: ["node_modules", "src", "static", "store"],
  modulePathIgnorePatterns: [
    "<rootDir>/node_modules/prismjs/plugins/line-numbers",
  ],
  testPathIgnorePatterns: [
    "<rootDir>/src/components/component-library",
    "<rootDir>/.next",
    "jest.config.js",
    "next.config.js",
  ],
  collectCoverageFrom: [
    "**/src/**",
    "**/store/**",
    "**/pages/**",
    "!**/__tests__/**",
    "!**/node_modules/**",
    "!**/component-library/**",
  ],
  testEnvironment: "node",
  collectCoverage: true,
  verbose: false,
  automock: false,
  setupFiles: ["./setupTests.js"],
  moduleNameMapper: {
    "@/components/(.*)$": "<rootDir>/src/components/$1",
    "@/functions/(.*)$": "<rootDir>/src/components/functions/$1",
    "@/services/(.*)$": "<rootDir>/src/components/services/$1",
    "@/workers/(.*)$": "<rootDir>/src/components/workers/$1",
    "@/scripts(.*)$": "<rootDir>/src/scripts/$1",
    "@/src(.*)$": "<rootDir>/src/$1",
    "@/__mocks__(.*)$": "<rootDir>/__mocks__/$1",
    "@/pages(.*)$": "<rootDir>/pages/$1",
    "@/store(.*)$": "<rootDir>/store/$1",
    "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
  },
  coveragePathIgnorePatterns: ["/node_modules/"],
  coverageThreshold: {
    global: {
      branches: 67,
      functions: 66,
      lines: 73,
      statements: 72,
    },
  },
  runner: "groups",
  extraGlobals: [],
  testTimeout: 10000,
};
Run Code Online (Sandbox Code Playgroud)

Anx*_*fer 2

在我的设置(typescript + ts-jest)中,我在前面添加了以下节点选项以使其正常工作:

NODE_OPTIONS=--experimental-vm-modules
Run Code Online (Sandbox Code Playgroud)

可以在这里找到参考: https: //jestjs.io/docs/ecmascript-modules