Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何在本地调试npm包 #13

Open
allenGKC opened this issue Apr 3, 2020 · 2 comments
Open

如何在本地调试npm包 #13

allenGKC opened this issue Apr 3, 2020 · 2 comments
Labels

Comments

@allenGKC
Copy link
Owner

allenGKC commented Apr 3, 2020

image

背景

最近项目结束,准备优化一下webpack,公司内部将打包工具单独抽出来作为npm包引入,既然要优化打包,必然涉及到要本地化调试npm包,下面介绍一下正确的✅调试姿势。

解决方案

假设有一个已经编写好的本地node包test-npm-util包(github上的包同理)和一个测试该包的项目my-project在同一个文件夹下project下,有以下两种方式可以在my-project项目中测试本地的allen-npm-util包

|-- project
    |-- my-project
        | -- package.json
    |-- test-npm-util

使用相对路径安装test-npm-util测试

进入项目目录,按照相对路径找到test-npm-util包,npm install直接安装。

cd my-project
npm install ../test-npm-util

然后进入my-project中的node_modules文件夹检查是否安装成功,一般情况下只要路径正确,node包编写正确,都会安装成功,这样就可以在my-project中使用test-npm-util。

const xcxutil = require('xcxutil');

使用 npm link 连接到全局测试

上面的方法的前提是node包和测试项目在同一个文件夹下,所以很方便的就找到路径,但很多情况是我们本地项目众多,分布在不同的文件夹下,所以找路径就很麻烦了,因此推荐使用npm link这种将node包连接到全局的方式,关于npm link的原理可以参考npm link官网

cd test-npm-util
npm link

执行完会得到下面的输出:

/Users/allen/.nvm/versions/node/v10.0.0/lib/node_modules/test-npm-util -> /Users/allen/project/test-npm-util 

意思是将project下的test-npm-util连接到全局的node_modules下,我们进入全局node_modules包下也可以查看到test-npm-util包

然后在my-project中也link一下该包即可测试使用

cd my-project
npm link test-npm-util

这样test-npm-util就被安装到my-project下啦,在test-npm-util下的修改也会同步到my-project下,就可以实现本地测试了。

如果想取消在全局的连接也非常的简单:

cd test-npm-util
npm unlink

总结

以上就是npm包本地调试的方法,希望对你有帮助,感谢阅读。

@allenGKC allenGKC added the node label Apr 3, 2020
@allenGKC allenGKC changed the title npm包本地调试 如何在本地调试npm Apr 3, 2020
@allenGKC allenGKC changed the title 如何在本地调试npm 如何在本地调试npm包 Apr 3, 2020
@mebtte
Copy link

mebtte commented Dec 24, 2020

作为npn包引入 --> 作为npm包引入

@allenGKC
Copy link
Owner Author

作为npn包引入 --> 作为npm包引入

已修改,thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants