首页 > 解决方案 > 在节点中导入 ES6 相关模块时找不到模块

问题描述

尝试构建一个模块以通过我的 React 路由器进行映射并返回路由。目前正在尝试在 Node 中对其进行测试并收到此错误:

Error: [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/corey/projects/react-build-sitemap/src/mapJson.js' imported from /home/corey/projects/react-build-sitemap/index.js Did you mean to import ../src/mapJson.js?

不太确定我应该如何导入它以使其在测试时工作。这最终会被导入到 React 项目中。

import fs from "fs";
import PropTypes from "prop-types";
import { warn } from "console";
import mapJson from "./src/mapJson";
import BasicRouter from "./BasicRouter";

const buildSitemap = (fileName, buildPath, url) => {
  const sitemapElements = [
    '<?xml version="1.0" encoding="UTF-8?">',
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
  ];
  //if component does not exist, throw warning and skip.
  if (fileName === undefined || fileName === null) {
    throw new warn("Component does not exist to generate sitemap. Skipping.");
  }
  //read through jsx
  const jsxTree = babelParser.parse(fileName, {
    sourceType: "module",
    plugins: ["jsx"],
  });
  //find the 'router', 'browserrouter', or 'switch' element.
  const router = mapJson(jsxTree);
  //if the above elements exist, map through all routes.
  if (router !== undefined) {
    router.forEach((item) => {
      console.log(item);
    });
  }
  //if does not exist, throw a warning saying it doesn't exist and skip running.
  //generate xml file string.
  //write sitemap.xml file to build path.
};

buildSitemap.propTypes = {
  fileName: PropTypes.string,
  buildPath: PropTypes.string,
  url: PropTypes.url,
};

buildSitemap(BasicRouter, "./src/", "https://coreylanier.com");

export default buildSitemap;

package.json包含"type": "module"并且相对导入的文件也有 ES6 导出。

编辑:这里是./src/mapJson.js

const mapJson = (json) => {
  //run code
};

export default mapJson;

标签: javascriptnode.jsnode-modules

解决方案


推荐阅读