26

我想在运行后自动将某些文件从npm包中复制到用户的本地目录

npm install my-package

我可以通过声明"files"inside来安装它们package.json。问题是---文件没有放在本地目录中。所以我需要运行postinstall脚本。

但是现在我不知道包的安装位置(可能是目录树的更高位置),那么我怎样才能可靠地访问文件并通过脚本将它们复制到本地目录呢?

(通过本地目录,我的意思是 --- 从我以使用包npm install my-package 的用户身份运行的地方。)

更新。似乎postinstall脚本作为npm拥有的进程运行,主目录为node_modules/my-package,所以我仍然不知道如何访问用户的主目录,而不是使用 naive ../../

4

5 回答 5

16

从 npm 3.4 开始,您可以使用 $INIT_CWD 环境变量: https ://blog.npmjs.org/post/164504728630/v540-2017-08-22

运行生命周期脚本时,INIT_CWD 现在将包含执行 npm 的原始工作目录。

要解决您的问题,请在 package.json 中添加以下安装后脚本:

  "scripts": {
    "postinstall": "cp fileYouWantToCopy $INIT_CWD",
  },
于 2018-07-11T09:59:46.060 回答
6

经过大量搜索,我发现这适用于跨平台

"scripts":
  "postinstall": "node ./post-install.js",

// post-install.js

/**
 * Script to run after npm install
 *
 * Copy selected files to user's directory
 */

'use strict'

var gentlyCopy = require('gently-copy')

var filesToCopy = ['.my-env-file', 'demo']

// User's local directory
var userPath = process.env.INIT_CWD

// Moving files to user's local directory
gentlyCopy(filesToCopy, userPath)
于 2019-03-06T18:07:10.417 回答
3

我会使用 shellscript/bash

-package.json

"scripts":
  "postinstall": "./postinstall.sh",

-postinstall.sh

#!/bin/bash

# go to YOUR_NEEDED_DIRECTORY .e.g "dist" or $INIT_CWD/dist
cd YOUR_NEEDED_DIRECTORY

# copy each file/dir to user dir(~/)
for node in `ls`
do
  cp -R $node ~/$node
done

别忘了!

chmod +x postinstall.sh
于 2017-04-06T23:04:20.267 回答
3

var cwd = require('path').resolve();

注意:如果要解析的参数具有零长度字符串,则将使用当前工作目录而不是它们。

来自https://nodejs.org/api/path.html

于 2016-01-14T06:43:06.417 回答
0

如果你是用 yarn 或 npm 构建的。你只能做“cp”。


    "scripts": {
        "start": "yarn run tailwind && react-scripts start",
        "build": "yarn run tailwind && yarn run purge-tailwind && cross-env GENERATE_SOURCEMAP=false react-scripts build &&  cp .htaccess build/ ",
    },

如果在构建之后需要这个 .htaccess,只需在构建 npm 指令之后添加它。 && cp .htaccess build/

于 2020-06-28T18:59:17.073 回答