Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpile npm module in Next.js

I am trying to transpile a module "react-device-detect" from node_modules but unable to achieve yet. Following is what I have tried:

module.exports = withLess({
  webpack: (config, { isServer, defaultLoaders }) => {
    // other configs
    config.module.rules.push({
      test: /\\.+(ts|tsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'ts-loader' }],
    });

    config.module.rules.push({
      test: /\\.+(js|jsx)$/,
      include: [path.join(__dirname, 'node_modules/react-device-detect')],
      // exclude: /node_modules/,
      use: [{ loader: 'babel-loader' }],
    });
    return config;
  },
});

I have tried the rules individually as well but didn't work.

UPDATE 1: Complete next.config.js configurations @felixmosh

const webpack = require("webpack");
const withLess = require("@zeit/next-less");
const { parsed: localEnv } = require("dotenv").config();
require("dotenv").config({
  path: process.env.NODE_ENV === "production" ? ".env.production" : ".env"
});
const Dotenv = require("dotenv-webpack");

module.exports = withLess({
  webpack: (config, { isServer }) => {
    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: "empty"
    };
    // add env variables on client end
    config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
    config.plugins.push(new Dotenv());

    if (!isServer) {
      config.resolve.alias["@sentry/node"] = "@sentry/browser";
    }
    return config;
  }
});

UPDATE 2:

It seems that next-transpile-modules does not work comfortably with next-i18next. I got in IE browser's console:

'exports' is undefined

I got errors like following when I run npm run build:

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'isMobileSafari' is not exported from 'react-device-detect'.

./utils.js
Attempted import error: 'osName' is not exported from 'react-device-detect'.

I got following when I run npm start:

react-i18next:: i18n.languages were undefined or empty undefined

like image 873
Fawad Khalil Avatar asked Feb 17 '20 06:02

Fawad Khalil


1 Answers

There is an NPM module for this next-transpile-modules that allows you to specify which modules to transpile.

// next.config.js
const withTM = require('next-transpile-modules')(['somemodule', 'and-another']); // pass the modules you would like to see transpiled

module.exports = withTM(withLess({
  ... // your custom next config

}));
like image 57
felixmosh Avatar answered Sep 22 '22 22:09

felixmosh