eidellev / inertiajs-adonisjs

280 stars 17 forks source link

Using SSR causes : Cannot use 'import.meta' outside a module #106

Open Xstoudi opened 1 year ago

Xstoudi commented 1 year ago

webpack.config.js: https://pastebin.com/TqBTuZNf webpack.ssr.config.js: https://pastebin.com/7eSR3tD5

As you can see, I use a Inertia-React-Tailwind stack.

When navigating to a route of my app, Adonis throws this error:

[18:50:01.079] ERROR (hydra/18528): Cannot use 'import.meta' outside a module
    err: {
      "type": "SyntaxError",
      "message": "Cannot use 'import.meta' outside a module",
      "stack":
          D:\Programmation\Perso\hydra\build\inertia\ssr\ssr.js:1514
          /******/      if (typeof import.meta.url === "string") scriptUrl = import.meta.url
                                          ^^^^

          SyntaxError: Cannot use 'import.meta' outside a module
              at internalCompileFunction (node:internal/vm:74:18)
              at wrapSafe (node:internal/modules/cjs/loader:1141:20)
              at Module._compile (node:internal/modules/cjs/loader:1182:27)
              at Object.Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
              at Module.load (node:internal/modules/cjs/loader:1081:32)
              at Function.Module._load (node:internal/modules/cjs/loader:922:12)
              at Module.require (node:internal/modules/cjs/loader:1105:19)
              at require (node:internal/modules/cjs/helpers:103:18)
              at Inertia.renderSsrPage (REDACTED\node_modules\@eidellev\inertia-adonisjs\build\src\Inertia.js:97:24)
              at Inertia.render (REDACTED\node_modules\@eidellev\inertia-adonisjs\build\src\Inertia.js:77:47)
      "status": 500
    }

It seems to generate ESM code import.meta that obviously fail.

Did I do something wrong?

eidellev commented 1 year ago

Hey @Xstoudi

Unfortunately, and if I recall correctly, we still use CJS on the server. This was a limitation imposed by adonis, but things may have changed since then. I will check this out when I am able.

Can you please confirm that client-side rendering works?

Xstoudi commented 1 year ago

Hey !

Yes I can confirme CSR works, the website renders perfectly if I set ssr.enabled to false in the config/inertia.ts file.

I know that Adonis still uses CJS, but I can't figure ou why Webpack seems to output ESM.

Xstoudi commented 1 year ago

Ok I found a workaround. Webpack is trying to deduct a publicPath and do it using the import.meta (which we want to avoid). So, forcing a publicPath in the webpack.ssr.config.js did the trick.

End of webpack.ssr.config.js is modified like this:

config.externals = [require('webpack-node-externals')()]
config.externalsPresets = { node: true }
config.output = {
  libraryTarget: 'commonjs2',
  filename: 'ssr.js',
  path: join(__dirname, './build/inertia/ssr'),
  publicPath: '/', // <--- HERE
}
config.experiments = { outputModule: true }