Skip to content

Cannot import anything from node_modules/ external dependencies into web worker #63

Open
@sangeltandem

Description

The Web Worker is failing to load external dependencies.

The web worker works fine for standalone functions that are written inside the Worker.ts file but when I moved actual code that had external dependencies I saw this in the console:

0446a38b-53bf-4461-b2cd-4427cdafe0bc:23408 Uncaught ReferenceError: _ is not defined
    at 0446a38b-53bf-4461-b2cd-4427cdafe0bc:23408:4

Saw this when running the rollup -c:

(!) Missing global variable names
Use output.globals to specify browser global variable names corresponding to external modules
lodash (guessing '_')
moment (guessing 'moment$2')
moment-range (guessing 'momentRange')
uuid (guessing 'uuid')
@tandemdiabetes/taco-js-pump-events-decoder (guessing 'tacoJsPumpEventsDecoder')
lodash/flatMap (guessing 'flatMap')
lru-cache (guessing 'LRU')

This is my rollup.config.js

import typescript from 'rollup-plugin-typescript2';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import analyze from 'rollup-plugin-analyzer';
import { dependencies, peerDependencies } from './package.json';
import webWorkerLoader from 'rollup-plugin-web-worker-loader';



const devMode = process.env.NODE_ENV === 'development';

const onAnalysis = ({
  bundleSize,
  bundleOrigSize,
  bundleReduction,
  moduleCount,
  modules,
}) => {
  if (!devMode) return;
  console.log({
    bundleSize,
    bundleOrigSize,
    bundleReduction,
    moduleCount,
  });
};

const getDependenciesFromPackageJson = () => {
  return [...Object.keys(dependencies), ...Object.keys(peerDependencies)]
    .map((name) => new RegExp(`^${name}`))
    .concat([/node_modules/]);
};

export default {
  external: [...getDependenciesFromPackageJson()],
  input: 'src/index.ts',
  output: [
    {
      file: 'lib/index.esm.min.js',
      format: 'es',
    },
    {
      file: 'lib/index.min.js',
      format: 'cjs',
    },
  ],
  plugins: [
    commonjs(),
    typescript({ tsconfig: './tsconfig.json' }),
    json(),
    nodeResolve(),

    webWorkerLoader(),
    analyze({
      summaryOnly: false,
      hideDeps: true,
      skipFormatted: true,
      onAnalysis: onAnalysis,
    }),
  ],
};

Should you be able to load external dependencies into the web worker? I am able to import relative files just fine but it breaks anytime I try to use an npm package. Is there some configuration I need to change to make this work?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions