【问题标题】:Import modules into next js将模块导入下一个 js
【发布时间】:2021-05-11 11:59:04
【问题描述】:

实际上我有一个项目,我需要将它作为一个模块包含在 Next JS 中。所以基本上我正在尝试通过npm link 使用它,我成功地能够将该模块作为组件添加到我的下一个 JS 存储库中。但由于 webpack 加载器,它正在崩溃。我是否需要在下一个 JS 中添加所有必需的加载器?有什么更好的方法来实现这一点?

【问题讨论】:

  • @felixmosh 请看看这个。

标签: reactjs next.js npm-link


【解决方案1】:

默认情况下 Next.js 不编译位于 node_modules 的依赖项。

您应该使用next-transpile-modules 来指示它编译特定的库。

// next.config.js
const withTM = require('next-transpile-modules')(['somemodule', 'and-another']);

module.exports = withTM({
  ...regular next config
});

【讨论】:

  • 添加后出现以下错误。 Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.tsx. Or convert the import to Component-Level CSS (CSS Modules).
  • 你不能从_app之外导入没有.module.css后缀的css文件,如果你的lib这样做了,而你使用css modules只需添加后缀
  • 嘿 @felixmosh Unhandled Runtime Error Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. 虽然组件中没有任何混合导入。
  • 看起来你的一个导入返回一个未定义的,你将它作为一个组件传递给反应
  • 有更好的调试方法吗?因为你知道我导入到下一个 JS 的其他模块中有很多文件。
【解决方案2】:

随着Next的新更新,js支持ES Modules和URL Imports。

从 Next.js 11.1 开始,我们添加了对优先于 CommonJS 模块的 ES 模块的实验性支持。在 Next.js 12 中,这是现在的默认设置。仍然支持导入仅提供 CommonJS 的 NPM 模块。

https://nextjs.org/blog/next-12#es-modules-support-and-url-imports

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2021-05-25
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多