简体   繁体   English

如何覆盖 npm 包的 package.json

[英]How to override npm package's package.json

A npm package that I use has wrong path in its package.json.我使用的 npm 包在 package.json 中有错误的路径。 It is这是

  "main": "./htmldiff.js",

But it has to be this to work properly.但它必须是这样才能正常工作。

  "main": "./src/htmldiff.js",

I guess maybe I can commit and download un-merged version.. but is there any easier way that only touches local files?我想也许我可以提交和下载未合并的版本..但是有没有更简单的方法只涉及本地文件?

You can override the file content.您可以覆盖文件内容。 Just read package.json.只需阅读 package.json。 Parse the content as an object.将内容解析为对象。 Change the object.改变对象。 Stringify it and then write it.把它字符串化然后写出来。 I made this sync for simplicity.为了简单起见,我做了这个同步。 You may want to use the async version.您可能想要使用异步版本。 Also, writeFile overrides the file content by default.此外, writeFile 默认覆盖文件内容。

   'use strict';

   const 
          fs      = require('fs'),
          content = fs.readFileSync('package.json', 'utf8'),
          parsed  = JSON.parse(content);
    
    parsed.main = "./src/htmldiff.js";
    
    fs.writeFileSync('package.json', JSON.stringify(parsed));

You can always skip the main target and import directly from node_modules folder like this您始终可以跳过主要目标并直接从 node_modules 文件夹中导入,如下所示

import xx from './node_modules/htmldiff/src/htmldiff'

If you are trying to avoid a relative path like ../../../ , a resolve alias from webpack or babel could help.如果你试图避免像../../../这样的相对路径,webpack 或 babel 的解析别名可能会有所帮助。

  const path = require('path');
  resolve: {
    alias: {
      '@': path.resolve('node_modules'),
    }
  }

And then you can do it like然后你可以这样做

import xx from '@/htmldiff/src/htmldiff'

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

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