简体   繁体   English

从 npm 包运行脚本

[英]run script from npm package

Say I have a function like so说我有这样的功能

index.js索引.js

sayHi = () => {
  console.log('hi');
}

sayHi();

and I want this to run immediately when the page loads so I call it with sayHi();我希望它在页面加载时立即运行,所以我用sayHi();调用它sayHi(); now obviously this works when I have the file imported in my index.html现在显然这在我将文件导入我的index.html

index.html索引.html

<! -- ... -->
<script src="./index.js"></script>

now I want to create this as a package other people can use so I have published it to npm and I can now install it using现在我想将它创建为其他人可以使用的包,所以我已将其发布到 npm,现在我可以使用

npm install say-hi

How does sayHi() run from the users side? sayHi()如何从用户端运行?

I'm not exactly sure how to put this but basically once the user has installed the package using npm, I would like the script to run automatically.我不确定如何放置它,但基本上一旦用户使用 npm 安装了包,我希望脚本自动运行。 Is this possible?这可能吗?

Now I am aware that I could export the sayHi function and the user could import it and call it, I'm just wondering if this is the only way?现在我知道我可以导出 sayHi 函数,用户可以导入它并调用它,我只是想知道这是否是唯一的方法?

You can add lifecycle handler scripts to package.json.您可以将生命周期处理程序脚本添加到 package.json。 install or postinstall look like good candidates for your scenario安装或安装后看起来很适合您的场景

{
"scripts" :
  { "install" : "scripts/install.js"
  , "postinstall" : "scripts/install.js"
  }
}

More info at https://docs.npmjs.com/misc/scripts更多信息请访问https://docs.npmjs.com/misc/scripts

now my question is how does sayHi() run from the users side?? I'm not exactly sure how to put this but basically once the user has installed the package using npm, I would like the script to run automatically.. is this possible?

If you publish your code as a package as you said, for users, a general usage or practise of your package is they import or require your package like require('say-hi') , at this moment ( require ), from your code, your sayHi() can be called immediately and you can see 'hi' in the console.如果您像您所说的那样将代码作为包发布,对于用户来说,您的包的一般用法或实践是他们从您的代码importrequire您的包,例如require('say-hi') ,此时( require ) ,您的 sayHi() 可以立即被调用,您可以在控制台中看到 'hi'。

BTW, you do not really need to export anything if you do not want.顺便说一句,如果你不想,你真的不需要导出任何东西。

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

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