繁体   English   中英

下一步.js。 如何从项目外的文件夹中导入模块?

[英]Next.js. How to import a module from the folder outside of the project?

我有 Next.js 应用程序,我想知道一种可能的方法来导入位于项目外部文件夹中的一些模块。

next.js 项目文件夹

  • /web/projects/nextjs-awesome-project

以及我想导入 next.js 项目的模块所在的文件夹

  • /网络/实用程序/通用

为此,我在env.local文件中添加了路径

UTILITY_LOCAL_PATH=E:/web/utilities/common

next.config.js 中,我添加了包含规则的导入别名(将实用程序文件夹包含到包中)

const localUtilityPath = process.env.UTILITY_LOCAL_PATH;
module.exports = {
  webpack: (config) => {
    config.resolve.alias = {
      ...(config.resolve.alias || {}),
      // the alias
      'UTILITY_LOCAL': path.resolve(localUtilityPath),
    };

    if (localUtilityPath) {
      // The include rule
      config.module.rules[1].include.push(path.resolve(`${localUtilityPath}/common`))
    }

    return config
  },

但是 next.js 抛出一个错误:

Module not found: Can't resolve 'UTILITY_LOCAL/common/matrix-sublimator'
  18 |
  19 |
> 20 | import {
  21 |   matrixSublimator,
  22 | } from 'UTILITY_LOCAL/common/matrix-sublimator'

我感谢任何帮助/信息!

一点免责声明:我知道存在正确的方法:创建一个 node_modules 依赖项并安装它,但是我对这种特殊方式感兴趣,因为我已经完成了 node_modules 依赖项,但我想快速/如何在不将整个实用程序包部署到远程服务器的情况下进行一些快速修复,并在每次添加一些小的 console.log 等时重新安装 node_modules 的最简单方法。

另外,我尝试在本地更改 node_modules 包,但它根本不起作用。 看起来 Next.js 使用了一些缓存等,因为我什至删除了 node_modules/utilities/common 文件夹,但它以某种方式工作。 这很奇怪而且毫无意义,我不明白为什么它会以这种方式行事,这就是为什么我想到了我正在尝试实现的“从外部文件夹导入模块”的想法

我还没有找到任何方法来导入一些位于 next.js 之外的模块,但我找到了另一种方法来避免这种讨厌的情况。

Next.js 在第一次构建时为 babel/webpack 文件等创建缓存,然后它使用这个缓存中的模块,这就是为什么当我们在 node_modules 文件夹中进行更改时,我们在应用程序中看不到这些更改。

我找到了两种处理方法:

  1. 只需设置config.cache = false; 在 next.config.js 文件中。 它将禁用 webpack 缓存,并且在每次构建时,webpack 都会获取 node_modules 依赖项。 缺点 - 它确实会影响性能
  2. 只需删除.next/cache甚至整个.next文件夹,对于下一次构建,Next.js 将使用来自 node_modules 的新数据重新创建此文件夹。

请注意,每次在 node_modules 包中进行一些更改时都应该这样做(例如,在添加一些console.log等之后)

希望这些信息可以帮助某人

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM