Search code examples
meteorwebpacksharp

How to prevent loading Sharp module on Meteor client?


I used npm pkg Sharp on server's picture collection to transform imgs. The server code is like this:

import * as sharp from 'sharp';

export const Pictures = new Mongo.Collection('pictures');

export const PicturesStore = new UploadFS.store.GridFS({
    collection: Pictures,
    name: 'pictures',
    filter: new UploadFS.Filter({
        contentTypes: [ 'image/*' ],
    }),
    transformWrite(from, to, fileId, file) {
        const transform = sharp().resize(300, 300).min().crop().toFormat('jpeg', { quality });
        from.pipe(transform).pipe(to);
    },
})

However on the client, it reports error:

cannot load native .node modules on the client.

The client doesn't run sharp functions actually. It only refers to PicturesStore and also create a minimongo collection for Pictures.

In another project, it uses webpack on the client. It can be configured to resolve sharp with an empty dummy object.

But how to create an empty dummy Sharp object to prevent loading Sharp module on Meteor client without webpack?


Solution

  • It turns out you have to write a Meteor package to define different files loaded on client and server. In you package.js, it's like this:

    Package.onUse(function (api) {
        api.mainModule('sharp-client.js', 'client');
        api.mainModule('sharp-server.js', 'server');
    });
    

    In sharp-client.js, it's like this:

    export var Sharp = {};
    

    In sharp-server.js, it's like this:

    import {
        checkNpmVersions
    } from 'meteor/tmeasday:check-npm-versions';
    
    checkNpmVersions({
        'sharp': '^0.20.5'
    }, 'my:awesome-package');
    
    export var Sharp = require('sharp');
    

    done.