簡體   English   中英

如何通過 postinstall npm 腳本自動將文件從包復制到本地目錄?

[英]How to automatically copy files from package to local directory via postinstall npm script?

我想在運行后自動將某些文件從npm包復制到用戶的本地目錄

npm install my-package

我可以通過在package.json聲明"files"來安裝它們。 問題是---文件沒有放在本地目錄中。 所以我需要運行postinstall腳本。

但是現在我不知道包安裝在哪里(可能在目錄樹的更高位置),那么我如何可靠地訪問文件並通過腳本將它們復制到本地目錄?

(通過本地目錄,我的意思是 --- 從我運行npm install my-package作為用戶使用包的地方。)

更新。 似乎postinstall腳本作為npm擁有的進程運行,主目錄為node_modules/my-package ,所以我仍然不知道如何訪問用戶的主目錄,而不是天真的../../

從 npm 3.4 開始,您可以使用 $INIT_CWD envar: https ://blog.npmjs.org/post/164504728630/v540-2017-08-22

運行生命周期腳本時, INIT_CWD 現在將包含執行 npm 的原始工作目錄。

要解決您的問題,請將以下內容添加到 package.json 中的 postinstall 腳本中:

  "scripts": {
    "postinstall": "cp fileYouWantToCopy $INIT_CWD",
  },

經過大量搜索后,我發現這可以跨平台工作

"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)

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

注意:如果要解析的參數具有零長度字符串,則將使用當前工作目錄而不是它們。

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

我會使用 shellscript/bash

-package.json

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

-安裝后.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

如果您使用 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM