Next.js - import server-side package in a file contains both server-side and client-side functionality? - next.js

Let's say I have a file named utils.js, containing two functions s and c.
s is a server-side function (Being called on an /api endpoint handler), and uses mongodb package.
c is a client-side function (will be bundled and sent to the browser).
When compiling the app using next build, will it cause any issues?
Does webpack know to bundle only part of a file/module? (considering server-side functions and imports as a "dead code" since they only being called from a server-side code)
Thanks

If you need to know which functions get bundled to the client & which ones to the server, there's an easy way to know this → https://next-code-elimination.now.sh/
Just copy & paste the contents of your file into it & you'll see which code gets bundled to the client & which code is bundled to the server. If you have imports then make sure to put all the imports in one file so you can see how it works.
The thumb rule is:
Anything like getServerSideProps, getStaticProps & getStaticPaths will be removed from the bundled code. If you import anything from a file that uses server-side code like fs but doesn't use it in any of the above 3 functions, then it won't be removed (check at Next Code Elimination Tool) & will give you an error.
The tool is the answer. I copy-pasted my file in it & found the answer in an instant.

I think there will be errors but not in the build time. It is likely issues will happen in the run time. You won't be able to access file systems on the client side just like how you can't access the window object on the server-side.
In my current project, we have utility functions for both the server-side, client-side, or universal. All server-side functions are called in getServerSideProps to make sure they work as expected. All your server-side code in getServerSideProps will not be imported as part of the client-side bundle if that's what you mean by "dead code". According to the Next.js
Note: You can import modules in top-level scope for use in
getServerSideProps. Imports used in getServerSideProps will not be
bundled for the client-side.
This means you can write server-side code directly in
getServerSideProps. This includes reading from the filesystem or a
database.
I'm not aware of a way you can ask webpack to bundle part of the file or execute a subset of import statements.
I hope that provides some help.
Reference:
Docs - getServerSideProps
Custom Webpack Config

Related

"Disable" SSR in nextjs

I want to create a Browser-Application without SSR, with React and MUI. So I found a NextJS-Template here:
https://github.com/mui/material-ui/tree/master/examples/nextjs-with-typescript
I want to disable SSR completely, let's say in the best case starting with _document.tsx, but at least the file _app.tsx and all following as for example _index.tsx should be rendered without SSR.
So, how to disable SSR "completely"?
While some might tell you to use plain React, others still use Next.js because of things like file-based routing, sane ESLint and TypeScript defaults, and fast compilation times (because of SWC). If you prefer the developer experience of Next.js over standalone React, but don't want/need SSR, then you have the option to use a static HTML export:
next export allows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server. It is recommended to only use next export if you don't need any of the unsupported features requiring a server.
The example template you linked to shouldn't need any additional code changes (running next export on it worked fine for me, it only threw a warning about a missing ESLint configuration which is easy to set up).
Just remove the getStaticProps, getStaticPaths and getServerSideProps from the pages you don't want to SSR and it will act like a normal react page.

How to do SSR (server-side rendering) in Svelte/TypeScript?

Svelte’s JavaScript server-side rendering API is described here: https://svelte.dev/docs#run-time-server-side-component-api
However, when I do this in TypeScript, there is no method App.render().
Do I need to change rollup.config.js (e.g. compilerOptions.generate)?
Do I need two versions of this file – one for the server and one for the client?
Can anyone help? Thanks!
Svelte Server-side component API is not directly accessible via import. Instead, you need to build the production with vite options --ssr. Otherwise, you're importing the component class extended SvelteComponent and that class has no render function.
You can check out this guide for Production SSR build: Vite Server-Side Rendering.
You don't need to set up the SSR Dev server or inject /#vite/client because svelte-hmr already does the magic under the hood.
The SSR Bundle options ssr.noExternal doesn't seem to work for me. So that I need to convert all Svelte components import into static import for a production build.
The official template relies on rollup-plugin-svelte, where similar question was asked. Essentially compiling in SSR mode does not automatically generate any HTML, in fact some post processing is required. The Svelte Server-side component API can be used for that.
There are several solutions out there for SSR:
SvelteKit
Routify
ElderJS

Module resolution not consistent with esm and non esm files

I have a project setup where I have a web app that rely on few Firebase SDKs that is Webpacked and served via webpack dev server.
From what I could gather without getting into too much details is that there is a final dependency that have both general index, and es2017 index files
there are intermediate dependencies that also have both, like the app and some that have only es2017 for example the messaging, and some only general index files.
The problem I have is that, and I have debugged for a very long time, from my application level when I import an intermediate dependency in different files, in some cases it takes the general index file, and in some the es2017 of the same library.
So in the error stacktrace here I am trying to initialize the messaging service of Firebase: (ignore for a moment the missing promise reject)
at Provider.getImmediate (index.cjs.js:153) // in component lib
at Module.getMessagingInWindow (index.esm2017.js:1155) // in messaging lib
at new MessagingWrapper (MessagingWrapper.js:76) // in my application
at FirebaseSession.push.56916.FirebaseSession.getMessaging (FirebaseSession.js:96)
at PushPubSubModule_Class.<anonymous> (PushPubSubModule.js:118)
at step (PushPubSubModule.js:63)
at Object.next (PushPubSubModule.js:44)
at fulfilled (PushPubSubModule.js:35)
When the messaging module is initially loaded it also accessed the component lib and uses the correct es2017 index file, but at a later point when I am trying to actually get the instance of the Messaging service it goes to the other general index file.
in all cases I use the import the same as in import {somthing} from "#firebase/messaging"
I never really had to worry about these things and might miss something fundamental, but this feels like a webpack bug in predetermine which module to load from the nested lib...
do you know of a way I could FORCE webpack to resolve es2017 index file?
or should I open a bug?
More details:
This is the transpiled code of my MessagingWrapper file:
line 71: goes to the correct es2017 index file in the messaging lib and the correct es2017 in the component lib
where as line 76: goes to the correct es2017 index file in the messaging
line:
and here line 1155: actually goes to the firebase/app lib es2017 file to resolve the provider, comes back to line 1155 and then call to getImmediate which ends up in the general index file in the component lib, as you can see below:
How do I fix this?
#firebase/* packages are internal and you shouldn't be importing them within your code as warned on each of their npm directory listing. As you encountered, this can lead to issues with module resolution as you essentially skip the internal setup steps by accessing the internals directly.
Instead, use the public API interfaces via firebase/* (for the modular SDK on v9+ or legacy SDK v8 and lower) and via firebase/compat/* (for the legacy SDK on v9+).

Deno - Importing TypeScript into a JS file

In Deno, to import a TypeScript module, does your own code file have to be TypeScript? Or does Deno auto convert TypeScript to javascript before the module gets imported?
I want all my code files to be EcmaScript modules (js or mjs, but not ts).
Unlike everyone else these days, I want to avoid using TypeScript in my own code. I dislike the rigidity of static types and Typescript is not part of the EcmaScript standard. EcmaScript alone has all I need to manage big projects. To me, TypeScript is an antiquated technology that has not been necessary since the advent of ES6 modules. The types of problems TypeScript addresses are problems I do not have.
You can write your own code with JavaScript.
Suppose you have or are using a TypeScript file/module numbers.ts:
export function isEven(n: number): boolean {
if (n % 2 != 0) {
return false
}
return true;
}
You can import and run it with an app.js JavaScript script:
import { isEven } from "./module.ts";
const one = isEven(1)
const two = isEven(2)
console.log(one)
console.log(two)
Deno does the TypeScript convertion to JavaScript internally. The process is the same when using standard or 3rd party libraries. The folks at the Deno project went even further by adding it as a goal:
https://deno.land/manual/introduction
Browser compatible: The subset of Deno programs which are written
completely in JavaScript and do not use the global Deno namespace (or
feature test for it), ought to also be able to be run in a modern web
browser without change.
Name resolution must be fully qualified. There's a whole lot more about referencing type definitions in this dedicated page for using TypeScript:
https://deno.land/manual/getting_started/typescript
Deno supports both JavaScript and TypeScript as first class languages
at runtime. This means it requires fully qualified module names,
including the extension (or a server providing the correct media type)
Example:
import { config } from "https://deno.land/x/dotenv/mod.ts";
Following my example above you can use the bundle command to generate a single JavaScript file with all the dependencies. Bundling it will take my app.js and module.ts files and create a new file app.bundle.js which is JavaScript.
https://deno.land/manual/tools/bundler
$ deno bundle app.js app.bundle.js
Bundling file:///home/pomatti/projects/deno-sandbox/app.js
Emitting bundle to "app.bundle.js"
3111 bytes emmited.
$ deno run app.bundle.js
false
true
It can even be loaded in the browser:
Bundles can also be loaded in the web browser. The bundle is a
self-contained ES module, and so the attribute of type must be set to
"module". For example:
<script type="module" src="website.bundle.js"></script>
As for ECMAScript modules I would like to point out that TypeScript implements it as well.
https://github.com/microsoft/TypeScript/issues/2242
https://www.staging-typescript.org/docs/handbook/modules.html
Starting with ECMAScript 2015, JavaScript has a concept of modules.
TypeScript shares this concept.
Now, the "static type" discussion falls out of scope of this forum so I won't touch it here, but I believe I covered everything else.

In Meteor how can I include a js file in another js file server side?

In Meteor is there a way to include a js file in another js file.
Specifically, server side and most importantly at start up.
The use case I am running into is for complicated Meteor.startups where I need to load quite a bit of data to the mongodb into a variety of collections.
In order to have different test scripts I have to have more than one file each with duplicate data.
So, is there anyway to have say a boostrap.js file that calls Meteor.startup and then is able to load different files in order to load up the test data?
Or can this be done in a different way through some kind of object?
By design Meteor will automatically include all the javascript files in the the entire project (except in the public folder) but only segregate them between the server and client.
You could create objects in separate files and just use the functions or objects whenever you please, they should all be available at startup.
Try using my module loader made for use with Meteor. It's very similar to AMD: https://github.com/matb33/meteor-smd

Resources