【问题标题】:Transpile npm module in Next.js在 Next.js 中编译 npm 模块
【发布时间】:2020-06-01 01:35:32
【问题描述】:

我正在尝试从 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

【问题讨论】:

  • 为什么即使您明确添加要使用 webpack 转译的模块,您的原始配置也不起作用?

标签: webpack node-modules next.js


【解决方案1】:

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

}));

【讨论】:

  • 那么我将如何在导出中合并这两个配置,因为我还有其他配置,因为它们与问题无关,所以我没有包括在这里?
  • 我在我的问题中添加了我在 UPDATE 2 中遇到的错误。
  • next-i18next 是你想要转译的那个包吗?为什么?它提供开箱即用的 cjs 版本
  • 不,我只想转译 react-device-detect。但如果我只包含react-device-detect 或者即使我包含next-i18next,它也会给出我在 UPDATE 2 中描述的错误。
  • 只需将polyfill.io/v3/polyfill.min.js 添加到您的页面,它应该提供浏览器特定的polyfill(这样现代浏览器不会下载冗余代码)
猜你喜欢
  • 2016-12-19
  • 2015-09-04
  • 2019-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2019-01-15
  • 1970-01-01
相关资源
最近更新 更多