【问题标题】:Nextjs import external components from parent directoryNextjs 从父目录导入外部组件
【发布时间】:2020-12-06 14:15:41
【问题描述】:

我有外部目录common,我想将该目录中的反应组件导入web-static。在web-static 我正在使用nextjs。

目前我有这个错误:

Module not found: Can't resolve 'react' in '/Users/jakub/Sites/WORK/wilio-web-common/common/src/@vendor/atoms'

我将这些行添加到next.config.js

const babeRule = config.module.rules[babelRuleIndex];
if (babeRule && babeRule.test) {
  babeRule.test = /\.(web\.)?(tsx|ts|js|mjs|jsx)$/;
  if (babeRule.include) {
    babeRule.include = [
      ...babeRule.include,
      resolve(__dirname, "../common/src/@vendor"),
    ];
  }
}
config.resolve.alias = {
  ...config.resolve.alias,
  "@vendor": resolve(__dirname, "../common/src/@vendor")
};

我的tsconfig.json 文件:

"paths": {
  "@vendor/*": ["../common/src/@vendor/*"]
}

Webpack 可以解析这些组件,但无法解析这些组件中安装的包。

../common/src/@vendor/atoms/Test.js
Module not found: Can't resolve 'react' in '/Users/user1/Sites/WORK/web-app/common/src/@vendor/atoms'

我是否需要将此目录也包含在 webpacks config.externals 中?当前 nextjs webpack externals

-----
options.isServer: false
[ 'next' ]
-----
-----
options.isServer: true
[ [Function] ]
-----

如何做到这一点?感谢您的帮助

【问题讨论】:

  • 你想如何使用这些反应组件?通过脚本标签?因为那么你可以添加一个入口点来编译所有这些并将其资产输出到 web-static
  • 通过import声明
  • 那么为什么所有输出文件都在网络静态中很重要?为什么不直接从他们的位置导入它们呢?拥有 web-static 文件夹有什么好处?
  • 什么输出文件?网络静态目录是 nextjs 应用程序。我想将外部目录../common 中的 react 组件导入 nextjs 目录。
  • 好的。输出文件是指 webpack 块。祝你好运,希望你能找到答案。显然我对 nextJs 平台缺乏了解

标签: javascript reactjs webpack next.js vercel


【解决方案1】:

这样试试

next.config.js

module.exports = {
  webpack: function (config, { defaultLoaders }) {
    const resolvedBaseUrl = path.resolve(config.context, "../");
    config.module.rules = [
      ...config.module.rules,
      {
        test: /\.(tsx|ts|js|mjs|jsx)$/,
        include: [resolvedBaseUrl],
        use: defaultLoaders.babel,
        exclude: (excludePath) => {
          return /node_modules/.test(excludePath);
        },
      },
    ];
    return config;
  }
};

【讨论】:

    【解决方案2】:

    从 Next.js 10.1.2 开始,您可以在 next.config.js 中使用当前的experimental externalDir 选项:

    module.exports = {
      experimental: {
        externalDir: true,
      },
    };
    

    请注意,要使 React 组件正常工作,我还必须将根 package.json 声明为 yarn workspace:

    {
      // ...
      "private": true,
      "workspaces": ["next-js-directory"],
      // ...
    }
    

    【讨论】:

    • 对我来说,这不需要向我的 package.json 添加工作区
    猜你喜欢
    • 2013-05-22
    • 2020-02-27
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    相关资源
    最近更新 更多