Next.js中的Transpile npm模块

时间:2020-02-17 06:34:54

标签: webpack node-modules next.js

我正在尝试从node_modules转换模块“ react-device-detect”,但无法实现。以下是我尝试过的:

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;
  }
});

我也分别尝试过这些规则,但是没有用。

更新1: 完成next.config.js配置@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;
  }
});

更新2:

next-transpile-modules似乎不能与next-i18next配合使用。我进入IE浏览器的控制台:

'exports' is undefined

运行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'.

运行npm start时得到了关注:

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

1 个答案:

答案 0 :(得分:6)

next-transpile-modules有一个NPM模块,可让您指定要移植的模块。

// 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

}));