实现构建工具之npm包引入

衔接上文,到目前为止我们已经能够获取变更文件路径,支持loader,插件,增量打包了,那自然应该找个npm包试一试功能,此处我选择moment,在moment入口文件同样require其他依赖文件,这样可以测试整个require链路是否生效。

思路

  • 根据nodejs解析路径写一个函数
  • 输入为绝对路径、相对路径、node_modules路径

思考

  • node引入包长分为三种:绝对路径、相对路径、node_modules路径
  • node_modules路径规则为:
    1.到目录下找js文件
    2.找该目录下的package.json,读取其main获取路径
    3.寻找该目录下的index.js
    4.都找不到则向上寻找,直到根路径

实现

此处写法不严谨,仅仅判断了window 顶层路径有CDEF等盘

const getFilePath = (path) => {
  if (/^\w+$/g.test(path)) {
    const initPath = join(__dirname, "../", "node_modules", path);
    if (
      fs.existsSync(initPath) &&
      fs.existsSync(join(initPath, "package.json"))
    ) {
      const { main } = JSON.parse(
        fs.readFileSync(join(initPath, "package.json"))
      );

      if (fs.existsSync(initPath)) return join(initPath, main);
    } else {
      let curPath = initPath;
      const isRoot = /[A-Z]\:\\/.test(curPath);
      while (!isRoot && !fs.existsSync(`${curPath}.js`)) {
        curPath = join(curPath, "../");
      }

      return curPath;
    }
  }
  // 绝对路径, 相对路径
  return resolve(path);
};

index.js

const moment = require("moment");

document.write(moment());

打包结果bundle.js
由于commonjs打包把整个moment包都打进来了,所以此不做展示

1646583151(1).png

页面效果
1646583288(1).png

至此,我们的nodejs引入包基本没有问题了,变可以开开心心开发热更新插件了

你可能感兴趣的:(实现构建工具之npm包引入)