kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

Router is not a constructor #127

Closed bezenson closed 2 years ago

bezenson commented 6 years ago

Hi! I am using universal router with your react-starter-kit. I've upgraded there universal router to latest version (4.2.0).

import Router from 'universal-router';
import routes from './routes';

console.log(Router);

export default new Router(routes, {
  resolveRoute(context, params) {
    if (typeof context.route.load === 'function') {
      return context.route
        .load()
        .then(action => action.default(context, params));
    }
    if (typeof context.route.action === 'function') {
      return context.route.action(context, params);
    }
    return null;
  },
});

I am getting error that Router is not a constructor. console.log result is /assets/node_modules/universal-router/browser.mjs?05fd4504. It's just a string. Where is the magic? What I am doing wrong?

frenzzy commented 6 years ago

From changelog:

  • If you are using webpack, change rule (loader) for .js files to include .mjs extension, i.e.
    • test: /\.js$/ => test: /\.m?js$/

Also see https://github.com/kriasoft/react-starter-kit/pull/1403 and https://github.com/kriasoft/react-starter-kit/issues/1233

javiermatos commented 6 years ago

Hi, I am having this issue too when adding universal-router 4 and 5 to my project. I am using create-react-app. It works with version 3. According to create-react-app code, they added mjs extension in rule loader.

To reproduce this issue just create an empty project with create-react-app and change src/index.js to include the following code, that is similar to the one shown by universal-router here:

import UniversalRouter from 'universal-router';

const routes = [
    {
        path: '/',
        action: () => (<h1>Home</h1>),
    },
    {
        path: '/test',
        action: () => (<h1>Test</h1>),
    },
];

const router = new UniversalRouter(routes);

router.resolve('/test').then(html => {
    document.body.innerHTML = html;
});

How can I do to have it working? For version 5 in my project I was able to import from universal-router/browser.js and it worked, but generateUrls function from universal-router/generateUrls/browser.js failed. I tried with node 6 and 8.

frenzzy commented 6 years ago

@javiermatos it because https://github.com/facebookincubator/create-react-app/pull/3537 is not yet released, you can use version from master or wait a little bit.

javiermatos commented 6 years ago

Thank you @frenzzy, it worked.