Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migration from CRA to Snowpack 2.0, library compatibility problem #364

Closed
dougg0k opened this issue May 28, 2020 · 19 comments
Closed

Migration from CRA to Snowpack 2.0, library compatibility problem #364

dougg0k opened this issue May 28, 2020 · 19 comments

Comments

@dougg0k
Copy link

dougg0k commented May 28, 2020

Hi,

I was trying to migrate a project to Snowpack 2.0 from CRA and I got this, is there anything that can be done on my end to make it work?

⠙ snowpack installing...
...packages
✘ /own_projects/new-dir/node_modules/dayjs/dayjs.min.js?commonjs-proxy
👉 https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module

Error: '__moduleExports' is not exported by node_modules/react-dom/index.js, imported by /home/zephyrus/projects/own_projects/new-dir/node_modules/react-dom/index.js?commonjs-proxy
    at error (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:217:30)
    at Module.error (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:15145:16)
    at handleMissingExport (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:15042:28)
    at Module.traceVariable (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:15519:24)
    at ModuleScope.findVariable (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:14199:39)
    at Identifier$1.bind (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:10080:40)
    at ExportDefaultDeclaration.bind (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:9707:23)
    at Program$1.bind (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:9703:31)
    at Module.bindReferences (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:15117:18)
    at Graph.linkAndOrderModules (/home/zephyrus/projects/own_projects/new-dir/node_modules/rollup/dist/shared/rollup.js:18252:20)

Thanks!

Edit:
I've just tried importing dayjs/esm and it worked, but now I get the same issue with react-dom, all libraries are in the latest version.

@dougg0k dougg0k changed the title Issue: Snowpack 2.0, compatibility problem Snowpack 2.0, compatibility problem May 28, 2020
@dougg0k dougg0k changed the title Snowpack 2.0, compatibility problem Snowpack 2.0, library compatibility problem May 28, 2020
@dougg0k
Copy link
Author

dougg0k commented May 28, 2020

I've been trying to find out what is happening, pretty much only by having more files in my src folder already causes the react-dom error regardless if I am importing them in the index.tsx or not.

If I have this code, with a single index.tsx file and nothing else, it works, but if I have the same exact code but with all other files and folders, I get the error.

import * as React from 'react';
import * as ReactDOM from 'react-dom';

ReactDOM.render(
  <React.StrictMode>
    <div>Test</div>
  </React.StrictMode>,
  document.getElementById('root'),
);

if (import.meta.hot) {
  import.meta.hot.accept();
}

@dougg0k
Copy link
Author

dougg0k commented May 28, 2020

I've also tried the config below, still the same issue.

snowpack.config.js

const ReactDOM = require('react-dom');

module.exports = {
  extends: '@snowpack/app-scripts-react',
  scripts: { 'bundle:*': '@snowpack/plugin-webpack' },
  plugins: ['@snowpack/plugin-webpack'],
  installOptions: {
    rollup: {
      include: 'node_modules/**',
      namedExports: {
        'react-dom': Object.keys(ReactDOM),
      },
    },
  },
};

@dougg0k dougg0k changed the title Snowpack 2.0, library compatibility problem Migration from CRA to Snowpack 2.0, library compatibility problem May 28, 2020
@FredKSchott
Copy link
Owner

Thanks for filing! neither React & ReactDOM are very ESM friendly, we have a manual workaround for React but I didn't realize we might need one for ReactDOM as well. Added 76e2ee6 to fix, will go out in the next version

@dougg0k
Copy link
Author

dougg0k commented May 28, 2020

Any date for the next version?

@FredKSchott
Copy link
Owner

releasing it now!

@dougg0k
Copy link
Author

dougg0k commented May 29, 2020

Nice!

@dougg0k
Copy link
Author

dougg0k commented May 29, 2020

Snowpack ran fine, except that due to other libraries I wont be able to use snowpack in my projects, there was no error in the snowpack dev start, but had blank screen with errors in the browser console about react-table library, and that could be just one of who knows how many libraries, unfortunately.

Thanks anyways.

@FredKSchott
Copy link
Owner

FredKSchott commented May 29, 2020

Would love to see the console logs / errors, if you don't mind sharing!

@dougg0k
Copy link
Author

dougg0k commented May 29, 2020

Sure, here it is.
https://i.postimg.cc/Gcb8t7Lb/Screenshot-from-2020-05-29-08-44-15.png

If one import is removed, it complains about another, that single line with a blank screen, and the screen trying to be rendered doesn't have the table in it.

https://i.postimg.cc/Qd2fg20Y/0errors.png
With no errors here.


If I remove all imports from react-table, now I get this from styled-normalize
https://i.postimg.cc/RFjqsTJR/anothererror.png
It does pretty much only this

import { createGlobalStyle } from 'styled-components'
import { normalize } from 'styled-normalize'

export const GlobalStyle = createGlobalStyle`
  ${normalize}

  body {
    padding: 0;
  }
`

If I try to import an asset from public folder, I get this.
https://i.postimg.cc/t9SByMGV/imageimport.png
I'm not sure if it's allowed to import from there, only saw documentation about the src folder. Seems a bit weird since src is usually only for code. In the src folder the import works.


I tried to add a env var to snowpack.config.js, it didn't work.

module.exports = {
  extends: '@snowpack/app-scripts-react',
  scripts: { 'bundle:*': '@snowpack/plugin-webpack' },
  plugins: ['@snowpack/plugin-webpack'],
  installOptions: {
    env: {
      GOOGLE_RECAPTCHA_SITEKEY: 'verylargekey',
    },
  },
};

Very weird behavior, I use unform for my forms with yup for validation, for whatever reason with snowpack, it's behaving very weird. Example, in the login, if I click on the submit button it shows the validation errors that the fields are empty, but if I fill them up, the errors dissapear, but when I click submit again, the same errors appear, that the inputs are empty and the API request doesn't get called, which would be correct if the fields were empty. The unform library uses ref uncontrolled components.

@dougg0k
Copy link
Author

dougg0k commented May 29, 2020

So, I am using GraphQL with react-apollo-hooks, I removed the validation from yup, and the API call were made, but the response payload, was this. Preview in the bottom.

Persist Logs
Disable Cache
1 request
21.66 KB / 21.84 KB transferred
Finish: 2.33 s
DOMContentLoaded: 284 ms
load: 1.77 s

    <!DOCTYPE html>
    <html lang="pt-br">
      <head>
        <meta charset="utf-8" />
        <link rel="icon" href="./img/icon.png" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="manifest" href="./manifest.json" />
        <link
          href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap"
          rel="stylesheet"
        />
        <title>App Title</title>
      </head>
      <body>
    <script>
      function debounce(e,t){let u;return()=>{clearTimeout(u),u=setTimeout(e,t)}}
      const exports = {};
      /** @license React vundefined
     * react-refresh-runtime.development.js
     *
     * Copyright (c) Facebook, Inc. and its affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    'use strict';
    if ("development" !== "production") {
      (function() {
    'use strict';
    // ATTENTION
    // When adding new symbols to this file,
    // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
    // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
    // nor polyfill, then a plain number is used for performance.
    var REACT_ELEMENT_TYPE = 0xeac7;
    var REACT_PORTAL_TYPE = 0xeaca;
    var REACT_FRAGMENT_TYPE = 0xeacb;
    var REACT_STRICT_MODE_TYPE = 0xeacc;
    var REACT_PROFILER_TYPE = 0xead2;
    var REACT_PROVIDER_TYPE = 0xeacd;
    var REACT_CONTEXT_TYPE = 0xeace;
    var REACT_FORWARD_REF_TYPE = 0xead0;
    var REACT_SUSPENSE_TYPE = 0xead1;
    var REACT_SUSPENSE_LIST_TYPE = 0xead8;
    var REACT_MEMO_TYPE = 0xead3;
    var REACT_LAZY_TYPE = 0xead4;
    var REACT_BLOCK_TYPE = 0xead9;
    var REACT_SERVER_BLOCK_TYPE = 0xeada;
    var REACT_FUNDAMENTAL_TYPE = 0xead5;
    var REACT_RESPONDER_TYPE = 0xead6;
    var REACT_SCOPE_TYPE = 0xead7;
    var REACT_OPAQUE_ID_TYPE = 0xeae0;
    var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1;
    var REACT_OFFSCREEN_TYPE = 0xeae2;
    var REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
    if (typeof Symbol === 'function' && Symbol.for) {
      var symbolFor = Symbol.for;
      REACT_ELEMENT_TYPE = symbolFor('react.element');
      REACT_PORTAL_TYPE = symbolFor('react.portal');
      REACT_FRAGMENT_TYPE = symbolFor('react.fragment');
      REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode');
      REACT_PROFILER_TYPE = symbolFor('react.profiler');
      REACT_PROVIDER_TYPE = symbolFor('react.provider');
      REACT_CONTEXT_TYPE = symbolFor('react.context');
      REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref');
      REACT_SUSPENSE_TYPE = symbolFor('react.suspense');
      REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list');
      REACT_MEMO_TYPE = symbolFor('react.memo');
      REACT_LAZY_TYPE = symbolFor('react.lazy');
      REACT_BLOCK_TYPE = symbolFor('react.block');
      REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block');
      REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental');
      REACT_RESPONDER_TYPE = symbolFor('react.responder');
      REACT_SCOPE_TYPE = symbolFor('react.scope');
      REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id');
      REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode');
      REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen');
      REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
    }
    var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // We never remove these associations.
    // It's OK to reference families, but use WeakMap/Set for types.
    var allFamiliesByID = new Map();
    var allFamiliesByType = new PossiblyWeakMap();
    var allSignaturesByType = new PossiblyWeakMap(); // This WeakMap is read by React, so we only put families
    // that have actually been edited here. This keeps checks fast.
    // $FlowIssue
    var updatedFamiliesByType = new PossiblyWeakMap(); // This is cleared on every performReactRefresh() call.
    // It is an array of [Family, NextType] tuples.
    var pendingUpdates = []; // This is injected by the renderer via DevTools global hook.
    var helpersByRendererID = new Map();
    var helpersByRoot = new Map(); // We keep track of mounted roots so we can schedule updates.
    var mountedRoots = new Set(); // If a root captures an error, we remember it so we can retry on edit.
    var failedRoots = new Set(); // In environments that support WeakMap, we also remember the last element for every root.
    // It needs to be weak because we do this even for roots that failed to mount.
    // If there is no WeakMap, we won't attempt to do retrying.
    // $FlowIssue
    var rootElements = // $FlowIssue
    typeof WeakMap === 'function' ? new WeakMap() : null;
    var isPerformingRefresh = false;
    function computeFullKey(signature) {
      if (signature.fullKey !== null) {
        return signature.fullKey;
      }
      var fullKey = signature.ownKey;
      var hooks;
      try {
        hooks = signature.getCustomHooks();
      } catch (err) {
        // This can happen in an edge case, e.g. if expression like Foo.useSomething
        // depends on Foo which is lazily initialized during rendering.
        // In that case just assume we'll have to remount.
        signature.forceReset = true;
        signature.fullKey = fullKey;
        return fullKey;
      }
      for (var i = 0; i < hooks.length; i++) {
        var hook = hooks[i];
        if (typeof hook !== 'function') {
          // Something's wrong. Assume we need to remount.
          signature.forceReset = true;
          signature.fullKey = fullKey;
          return fullKey;
        }
        var nestedHookSignature = allSignaturesByType.get(hook);
        if (nestedHookSignature === undefined) {
          // No signature means Hook wasn't in the source code, e.g. in a library.
          // We'll skip it because we can assume it won't change during this session.
          continue;
        }
        var nestedHookKey = computeFullKey(nestedHookSignature);
        if (nestedHookSignature.forceReset) {
          signature.forceReset = true;
        }
        fullKey += '\n---\n' + nestedHookKey;
      }
      signature.fullKey = fullKey;
      return fullKey;
    }
    function haveEqualSignatures(prevType, nextType) {
      var prevSignature = allSignaturesByType.get(prevType);
      var nextSignature = allSignaturesByType.get(nextType);
      if (prevSignature === undefined && nextSignature === undefined) {
        return true;
      }
      if (prevSignature === undefined || nextSignature === undefined) {
        return false;
      }
      if (computeFullKey(prevSignature) !== computeFullKey(nextSignature)) {
        return false;
      }
      if (nextSignature.forceReset) {
        return false;
      }
      return true;
    }
    function isReactClass(type) {
      return type.prototype && type.prototype.isReactComponent;
    }
    function canPreserveStateBetween(prevType, nextType) {
      if (isReactClass(prevType) || isReactClass(nextType)) {
        return false;
      }
      if (haveEqualSignatures(prevType, nextType)) {
        return true;
      }
      return false;
    }
    function resolveFamily(type) {
      // Only check updated types to keep lookups fast.
      return updatedFamiliesByType.get(type);
    } // If we didn't care about IE11, we could use new Map/Set(iterable).
    function cloneMap(map) {
      var clone = new Map();
      map.forEach(function (value, key) {
        clone.set(key, value);
      });
      return clone;
    }
    function cloneSet(set) {
      var clone = new Set();
      set.forEach(function (value) {
        clone.add(value);
      });
      return clone;
    }
    function performReactRefresh() {
      if (pendingUpdates.length === 0) {
        return null;
      }
      if (isPerformingRefresh) {
        return null;
      }
      isPerformingRefresh = true;
      try {
        var staleFamilies = new Set();
        var updatedFamilies = new Set();
        var updates = pendingUpdates;
        pendingUpdates = [];
        updates.forEach(function (_ref) {
          var family = _ref[0],
              nextType = _ref[1];
          // Now that we got a real edit, we can create associations
          // that will be read by the React reconciler.
          var prevType = family.current;
          updatedFamiliesByType.set(prevType, family);
          updatedFamiliesByType.set(nextType, family);
          family.current = nextType; // Determine whether this should be a re-render or a re-mount.
          if (canPreserveStateBetween(prevType, nextType)) {
            updatedFamilies.add(family);
          } else {
            staleFamilies.add(family);
          }
        }); // TODO: rename these fields to something more meaningful.
        var update = {
          updatedFamilies: updatedFamilies,
          // Families that will re-render preserving state
          staleFamilies: staleFamilies // Families that will be remounted
        };
        helpersByRendererID.forEach(function (helpers) {
          // Even if there are no roots, set the handler on first update.
          // This ensures that if *new* roots are mounted, they'll use the resolve handler.
          helpers.setRefreshHandler(resolveFamily);
        });
        var didError = false;
        var firstError = null; // We snapshot maps and sets that are mutated during commits.
        // If we don't do this, there is a risk they will be mutated while
        // we iterate over them. For example, trying to recover a failed root
        // may cause another root to be added to the failed list -- an infinite loop.
        var failedRootsSnapshot = cloneSet(failedRoots);
        var mountedRootsSnapshot = cloneSet(mountedRoots);
        var helpersByRootSnapshot = cloneMap(helpersByRoot);
        failedRootsSnapshot.forEach(function (root) {
          var helpers = helpersByRootSnapshot.get(root);
          if (helpers === undefined) {
            throw new Error('Could not find helpers for a root. This is a bug in React Refresh.');
          }
          if (!failedRoots.has(root)) {// No longer failed.
          }
          if (rootElements === null) {
            return;
          }
          if (!rootElements.has(root)) {
            return;
          }
          var element = rootElements.get(root);
          try {
            helpers.scheduleRoot(root, element);
          } catch (err) {
            if (!didError) {
              didError = true;
              firstError = err;
            } // Keep trying other roots.
          }
        });
        mountedRootsSnapshot.forEach(function (root) {
          var helpers = helpersByRootSnapshot.get(root);
          if (helpers === undefined) {
            throw new Error('Could not find helpers for a root. This is a bug in React Refresh.');
          }
          if (!mountedRoots.has(root)) {// No longer mounted.
          }
          try {
            helpers.scheduleRefresh(root, update);
          } catch (err) {
            if (!didError) {
              didError = true;
              firstError = err;
            } // Keep trying other roots.
          }
        });
        if (didError) {
          throw firstError;
        }
        return update;
      } finally {
        isPerformingRefresh = false;
      }
    }
    function register(type, id) {
      {
        if (type === null) {
          return;
        }
        if (typeof type !== 'function' && typeof type !== 'object') {
          return;
        } // This can happen in an edge case, e.g. if we register
        // return value of a HOC but it returns a cached component.
        // Ignore anything but the first registration for each type.
        if (allFamiliesByType.has(type)) {
          return;
        } // Create family or remember to update it.
        // None of this bookkeeping affects reconciliation
        // until the first performReactRefresh() call above.
        var family = allFamiliesByID.get(id);
        if (family === undefined) {
          family = {
            current: type
          };
          allFamiliesByID.set(id, family);
        } else {
          pendingUpdates.push([family, type]);
        }
        allFamiliesByType.set(type, family); // Visit inner types because we might not have registered them.
        if (typeof type === 'object' && type !== null) {
          switch (type.$typeof) {
            case REACT_FORWARD_REF_TYPE:
              register(type.render, id + '$render');
              break;
            case REACT_MEMO_TYPE:
              register(type.type, id + '$type');
              break;
          }
        }
      }
    }
    function setSignature(type, key) {
      var forceReset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
      var getCustomHooks = arguments.length > 3 ? arguments[3] : undefined;
      {
        allSignaturesByType.set(type, {
          forceReset: forceReset,
          ownKey: key,
          fullKey: null,
          getCustomHooks: getCustomHooks || function () {
            return [];
          }
        });
      }
    } // This is lazily called during first render for a type.
    // It captures Hook list at that time so inline requires don't break comparisons.
    function collectCustomHooksForSignature(type) {
      {
        var signature = allSignaturesByType.get(type);
        if (signature !== undefined) {
          computeFullKey(signature);
        }
      }
    }
    function getFamilyByID(id) {
      {
        return allFamiliesByID.get(id);
      }
    }
    function getFamilyByType(type) {
      {
        return allFamiliesByType.get(type);
      }
    }
    function findAffectedHostInstances(families) {
      {
        var affectedInstances = new Set();
        mountedRoots.forEach(function (root) {
          var helpers = helpersByRoot.get(root);
          if (helpers === undefined) {
            throw new Error('Could not find helpers for a root. This is a bug in React Refresh.');
          }
          var instancesForRoot = helpers.findHostInstancesForRefresh(root, families);
          instancesForRoot.forEach(function (inst) {
            affectedInstances.add(inst);
          });
        });
        return affectedInstances;
      }
    }
    function injectIntoGlobalHook(globalObject) {
      {
        // For React Native, the global hook will be set up by require('react-devtools-core').
        // That code will run before us. So we need to monkeypatch functions on existing hook.
        // For React Web, the global hook will be set up by the extension.
        // This will also run before us.
        var hook = globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__;
        if (hook === undefined) {
          // However, if there is no DevTools extension, we'll need to set up the global hook ourselves.
          // Note that in this case it's important that renderer code runs *after* this method call.
          // Otherwise, the renderer will think that there is no global hook, and won't do the injection.
          var nextID = 0;
          globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
            renderers: new Map(),
            supportsFiber: true,
            inject: function (injected) {
              return nextID++;
            },
            onScheduleFiberRoot: function (id, root, children) {},
            onCommitFiberRoot: function (id, root, maybePriorityLevel, didError) {},
            onCommitFiberUnmount: function () {}
          };
        } // Here, we just want to get a reference to scheduleRefresh.
        var oldInject = hook.inject;
        hook.inject = function (injected) {
          var id = oldInject.apply(this, arguments);
          if (typeof injected.scheduleRefresh === 'function' && typeof injected.setRefreshHandler === 'function') {
            // This version supports React Refresh.
            helpersByRendererID.set(id, injected);
          }
          return id;
        }; // Do the same for any already injected roots.
        // This is useful if ReactDOM has already been initialized.
        // https://github.com/facebook/react/issues/17626
        hook.renderers.forEach(function (injected, id) {
          if (typeof injected.scheduleRefresh === 'function' && typeof injected.setRefreshHandler === 'function') {
            // This version supports React Refresh.
            helpersByRendererID.set(id, injected);
          }
        }); // We also want to track currently mounted roots.
        var oldOnCommitFiberRoot = hook.onCommitFiberRoot;
        var oldOnScheduleFiberRoot = hook.onScheduleFiberRoot || function () {};
        hook.onScheduleFiberRoot = function (id, root, children) {
          if (!isPerformingRefresh) {
            // If it was intentionally scheduled, don't attempt to restore.
            // This includes intentionally scheduled unmounts.
            failedRoots.delete(root);
            if (rootElements !== null) {
              rootElements.set(root, children);
            }
          }
          return oldOnScheduleFiberRoot.apply(this, arguments);
        };
        hook.onCommitFiberRoot = function (id, root, maybePriorityLevel, didError) {
          var helpers = helpersByRendererID.get(id);
          if (helpers === undefined) {
            return;
          }
          helpersByRoot.set(root, helpers);
          var current = root.current;
          var alternate = current.alternate; // We need to determine whether this root has just (un)mounted.
          // This logic is copy-pasted from similar logic in the DevTools backend.
          // If this breaks with some refactoring, you'll want to update DevTools too.
          if (alternate !== null) {
            var wasMounted = alternate.memoizedState != null && alternate.memoizedState.element != null;
            var isMounted = current.memoizedState != null && current.memoizedState.element != null;
            if (!wasMounted && isMounted) {
              // Mount a new root.
              mountedRoots.add(root);
              failedRoots.delete(root);
            } else if (wasMounted && isMounted) ; else if (wasMounted && !isMounted) {
              // Unmount an existing root.
              mountedRoots.delete(root);
              if (didError) {
                // We'll remount it on future edits.
                failedRoots.add(root);
              } else {
                helpersByRoot.delete(root);
              }
            } else if (!wasMounted && !isMounted) {
              if (didError) {
                // We'll remount it on future edits.
                failedRoots.add(root);
              }
            }
          } else {
            // Mount a new root.
            mountedRoots.add(root);
          }
          return oldOnCommitFiberRoot.apply(this, arguments);
        };
      }
    }
    function hasUnrecoverableErrors() {
      // TODO: delete this after removing dependency in RN.
      return false;
    } // Exposed for testing.
    function _getMountedRootCount() {
      {
        return mountedRoots.size;
      }
    } // This is a wrapper over more primitive functions for setting signature.
    // Signatures let us decide whether the Hook order has changed on refresh.
    //
    // This function is intended to be used as a transform target, e.g.:
    // var _s = createSignatureFunctionForTransform()
    //
    // function Hello() {
    //   const [foo, setFoo] = useState(0);
    //   const value = useCustomHook();
    //   _s(); /* Second call triggers collecting the custom Hook list.
    //          * This doesn't happen during the module evaluation because we
    //          * don't want to change the module order with inline requires.
    //          * Next calls are noops. */
    //   return <h1>Hi</h1>;
    // }
    //
    // /* First call specifies the signature: */
    // _s(
    //   Hello,
    //   'useState{[foo, setFoo]}(0)',
    //   () => [useCustomHook], /* Lazy to avoid triggering inline requires */
    // );
    function createSignatureFunctionForTransform() {
      {
        // We'll fill in the signature in two steps.
        // First, we'll know the signature itself. This happens outside the component.
        // Then, we'll know the references to custom Hooks. This happens inside the component.
        // After that, the returned function will be a fast path no-op.
        var status = 'needsSignature';
        var savedType;
        var hasCustomHooks;
        return function (type, key, forceReset, getCustomHooks) {
          switch (status) {
            case 'needsSignature':
              if (type !== undefined) {
                // If we received an argument, this is the initial registration call.
                savedType = type;
                hasCustomHooks = typeof getCustomHooks === 'function';
                setSignature(type, key, forceReset, getCustomHooks); // The next call we expect is from inside a function, to fill in the custom Hooks.
                status = 'needsCustomHooks';
              }
              break;
            case 'needsCustomHooks':
              if (hasCustomHooks) {
                collectCustomHooksForSignature(savedType);
              }
              status = 'resolved';
              break;
          }
          return type;
        };
      }
    }
    function isLikelyComponentType(type) {
      {
        switch (typeof type) {
          case 'function':
            {
              // First, deal with classes.
              if (type.prototype != null) {
                if (type.prototype.isReactComponent) {
                  // React class.
                  return true;
                }
                var ownNames = Object.getOwnPropertyNames(type.prototype);
                if (ownNames.length > 1 || ownNames[0] !== 'constructor') {
                  // This looks like a class.
                  return false;
                } // eslint-disable-next-line no-proto
                if (type.prototype.__proto__ !== Object.prototype) {
                  // It has a superclass.
                  return false;
                } // Pass through.
                // This looks like a regular function with empty prototype.
              } // For plain functions and arrows, use name as a heuristic.
              var name = type.name || type.displayName;
              return typeof name === 'string' && /^[A-Z]/.test(name);
            }
          case 'object':
            {
              if (type != null) {
                switch (type.$typeof) {
                  case REACT_FORWARD_REF_TYPE:
                  case REACT_MEMO_TYPE:
                    // Definitely React components.
                    return true;
                  default:
                    return false;
                }
              }
              return false;
            }
          default:
            {
              return false;
            }
        }
      }
    }
    exports._getMountedRootCount = _getMountedRootCount;
    exports.collectCustomHooksForSignature = collectCustomHooksForSignature;
    exports.createSignatureFunctionForTransform = createSignatureFunctionForTransform;
    exports.findAffectedHostInstances = findAffectedHostInstances;
    exports.getFamilyByID = getFamilyByID;
    exports.getFamilyByType = getFamilyByType;
    exports.hasUnrecoverableErrors = hasUnrecoverableErrors;
    exports.injectIntoGlobalHook = injectIntoGlobalHook;
    exports.isLikelyComponentType = isLikelyComponentType;
    exports.performReactRefresh = performReactRefresh;
    exports.register = register;
    exports.setSignature = setSignature;
      })();
    }
      exports.performReactRefresh = debounce(exports.performReactRefresh, 30);
      window.$RefreshRuntime$ = exports;
      window.$RefreshRuntime$.injectIntoGlobalHook(window);
      window.$RefreshReg$ = () => {};
      window.$RefreshSig$ = () => (type) => type;
    </script>
        <div id="root"></div>
        <noscript>
          <span style="font-family: 'Open Sans'; font-size: 28px;">
            You need to enable javascript to utilize this application.
          </span>
        </noscript>
        <script type="module" src="/_dist_/index.js"></script>
      </body>
    </html>
    <script type="module" src="/livereload/hmr.js"></script>

Preview was just this

 You need to enable javascript to utilize this application. 

I think that's it.

@FredKSchott
Copy link
Owner

@dougg0k thanks for the info, that really helps. For reference for anyone else who hits this:

  • react-table - If this is written as common.js, it may not support named exports. Instead this should be import reactTable from 'react-table'; and then reactTable.useTable. It would be great if we could detect this for you and give feedback in the dev console.
  • styled-normalize - This is a known issue! see [@rollup/plugin-commonjs] Cannot handle CJS -> ESM imports rollup/plugins#400
  • Loading image MIME type - That actually may be a bug, I'm not sure why that wouldn't have a good MIME type. If you can, can you share the import statement that you were using to import that image?

@dougg0k
Copy link
Author

dougg0k commented May 29, 2020

With:

import logo from '../../public/img/logo.png'; 

Since I didnt find any way to import from public folder in the docs, I tried that.

@FredKSchott
Copy link
Owner

Yup, that should have worked. I'll try to reproduce on my end.

Fwiw Snowpack does support images in the src/ directory, if that helps.

@FredKSchott
Copy link
Owner

Ah, I see the problem. This should have been:

import logo from '../img/logo.png'; 

Since your import is run in the browser, and the public directory has been mounted to /, the image file actually lives at /img/logo.png and not /public/img/logo.png.

We should still have a better error message for you though, besides just "bad MIME type"

@dougg0k
Copy link
Author

dougg0k commented May 29, 2020

Hm, cool. Thanks for letting me know.

@haikyuu
Copy link

haikyuu commented Jun 9, 2020

I'm having a similar issue:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
    resolveDispatcher http://localhost:8080/web_modules/common/index-d708596e.js:1651
    useMemo http://localhost:8080/web_modules/common/index-d708596e.js:1706
    Provider Redux
    React 16
    <anonymous> http://localhost:8080/_dist_/index.js:32
index-d708596e.js:1651:13
    resolveDispatcher http://localhost:8080/web_modules/common/index-d708596e.js:1651
    useMemo http://localhost:8080/web_modules/common/index-d708596e.js:1706
    Provider Redux
    React 16
    <anonymous> http://localhost:8080/_dist_/index.js:32
    InnerModuleEvaluation self-hosted:1572
    evaluation self-hosted:1543

Note that

  1. i'm migrating from cra and things were working just fine. So i'm not breaking the rules of hooks
  2. I'm using the same version of React and ReactDOM. Here is the result of npm ls
    image
  3. I don't have more than one copy (not possible since npm ls outputs one)

@FredKSchott
Copy link
Owner

That's super strange, I don't know what could be causing that. We just pushed a bunch of installer fixes in the last couple of versions, maybe there's a fix in there for this?

@haikyuu
Copy link

haikyuu commented Jun 9, 2020

I don't face this issue when installing dependencies using yarn
npm version: 6.14.4
node version: v12.18.0
yarn version: 1.22.0

Update:

I ran npm cache clean --force and it worked fine.

Thank you

@fasiha
Copy link

fasiha commented Aug 9, 2020

@FredKSchott thank you so much for taking the time to give such detailed responses to the various issues raised here! I beg leave to burden your generosity a bit more—I'm happy to move this to its own issue but I thought to start by posting it here because I think it benefits from the above discussion.

I'm running into the same Uncaught TypeError: (intermediate value).__moduleExports is undefined as above when I use the io-ts library in a certain way. Steps to reproduce:

npx create-snowpack-app new-dir --template @snowpack/app-template-react-typescript
cd new-dir
npm i io-ts fp-ts

Then, if I add the following code snippet to the bottom of src/index.tsx (cut-pasted from io-ts docs), all is well:

import * as t from 'io-ts'
// import { PathReporter } from 'io-ts/lib/PathReporter' // per https://github.com/pikapkg/snowpack/issues/364
import PR from 'io-ts/lib/PathReporter'

const User = t.type({
  userId: t.number,
  name: t.string
})
const result = User.decode({ name: 'Giulio' })
console.log(PR.PathReporter.report(result))

This is fine! However!, if I add the following two lines to the bottom:

import E from 'fp-ts/lib/Either'
console.log(E.isRight(result));

I get the following error:

Uncaught TypeError: (intermediate value).__moduleExports is undefined
    lib http://localhost:8081/web_modules/io-ts/lib/PathReporter.js:127
    createCommonjsModule http://localhost:8081/web_modules/common/_commonjsHelpers-38687f85.js:10
    <anonymous> http://localhost:8081/web_modules/io-ts/lib/PathReporter.js:4

If I'm reading this stacktrace correctly, what's happening is that both my code and PathReporter are both trying to import Either and this causes something to break.

The frustrating thing is, if I remove these offending two lines, I continue getting the same error message, even if I restart snowpack dev. My app has stopped working—likely because of Snowpack caching dependencies?

I did find a way to snap my app out of its zombie state:

  1. delete the offending two lines of code using Either,
  2. change the PathReporter import to garbage, e.g., import PR from 'io-ts/lib/PathReporter@@@'
  3. full-reload the page (Snowpack gives me an error (Uncaught TypeError: Error resolving module specifier “react”. Relative module specifiers must start with “./”, “../” or “/”.)
  4. restore the proper import to PathReporter, full-reload a couple of times, and the normal React atom page is back.

So there are a couple of issues that might be of interest here:

  • the core issue is, importing both PathReporter from io-ts and Either from fp-ts results in a runtime error, but also
  • it would be nice if the runtime error didn't persist even after I remove the offending code.

Again, apologies for burdening you with more questions about this topic, I'm happy to move it to its own issue if you'd like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants