Avoid client import

How can I stop the client to import a file that is only intended for the server?

import { readdirSync } from 'fs' // <== Module "fs" has been externalized for browser compatibility. Cannot access "fs.default" in client code.

I cannot use Meteor.isServer, because the browser complains the import statement has to be at the beginning of the file:

if (Meteor.isServer) {
  import { readdirSync } from 'fs' // <== Uncaught SyntaxError: import declarations may only appear at top level of a module


1 Like

You can use a special directory like server/nameofyourfile. There is more info here in the docs

@grubba Thank you for your answer. But my file already resides there: /server/i19next/i18n.js

It’s being imported from a method, which needs to be visible to the client, or so I think it’s need to be.

You should be able to use require. Check out the example here: Security | Meteor Guide

Thank you @jam .

In this case, I had to completely get rid of the optimistic UI part.

This post might help you

Somewhat related article I wrote last year:

This is primarily about npm packages but the technique is the same to achieve exact Code splitting


You can also use dynamic import. In your case, something like this:

if (Meteor.isServer) {
        // Dynamically importing the fs module
        import('fs').then(fsModule => {
            const readdirSync = fsModule.default; // Accessing the default export
            // Now you can use fs
        }).catch(error => {
            // Handle any errors that occurred during import
            console.error("Failed to import 'moment':", error);

Maybe the syntax above is not 100% exact but check for dynamic import on ES6. There is also a synchronous dynamic import if needed if I remember correctly…

1 Like