将文件从目录拉入NPM的根文件夹

Ben*_*Ben 7 npm

我正在向NPM出版一个图书馆.

当我构建库时,生成的工件将放置在dist项目根目录中的文件夹中index.js.

当用户从NPM安装时,我希望index.js出现在其文件夹中创建的文件夹的node_modules目录中.目前,它仍保留在一个名为的目录中dist.

我怎样才能做到这一点?

我的packages.json:

{
  "name": "my-package",
  "version": "0.0.9",
  "files": ["dist/*"],
  "main": "index.min.js",
  "private": false,
  "dependencies": {},
  "devDependencies": {},
  "repository": "git@github.com:username/my-package.git"
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 2

我有完全相同的问题。

我不是通过复制文件来解决这个问题,而是通过将我需要的文件复制到文件夹中,然后从那里./dist/执行;npm publish然后,NPM 将该文件夹视为一个完整的包,一切都运行良好。我需要从根文件夹复制的唯一文件是:

  • package.json
  • README.md

因为我们要在发布之前将这些文件复制到./dist/文件夹中,所以我们不希望package.json文件引用./dist/. 因此,完全删除package.jsonfiles条目,因为我们不需要告诉它我们将获取哪些文件 - 我们将获取文件夹中的所有内容./dist/。我正在使用 TypeScript,所以我也有一个typings条目,但同样没有引用./dist/.

{
  "name": "my-package",
  "version": "0.0.9",
  "main": "index.min.js",
  "typings": "index.d.ts",
  "private": false,
  "dependencies": {},
  "devDependencies": {},
  "repository": "git@github.com:username/my-package.git"
}
Run Code Online (Sandbox Code Playgroud)

现在进行发布步骤。我构建了一个 gulp 任务,它将为我执行发布,使其变得良好且自动化(除了增加包版本 # 之外)。

从 gulp 中,我将使用 Node 的 spawn() 来启动 npm 进程。然而,因为我实际上是在 Windows 上工作,所以我使用了“ cross-spawn ”,而不是普通的内置 Node.js spawn(当我的路径中有空格时,我才知道这种方法不起作用!)。

这是我的 gulp 文件,删除了 TypeScript 位:

var gulp = require('gulp');
var del = require('del');
var spawn =  require('cross-spawn'); // WAS: require('child_process').spawn;

var config = {
    src: { tsFiles: './src/**/*.ts' },
    out: { path: './dist/' }
}

gulp.task('clean', () => {
    return del('dist/*');
});


gulp.task('build', ['clean'], () => {
    ....
});


gulp.task('publish', ['build'], (done) => {
    // Copy the files we'll need to publish
    // We just use built-in gulp commands to do the copy
    gulp.src(['package.json', 'README.md']).pipe(gulp.dest(config.out.path));

    // We'll start the npm process in the dist directory
    var outPath = config.out.path.replace(/(\.)|(\/)/gm,'');
    var distDir = __dirname + '\\' + outPath + '\\';
    console.log("dist directory = " + distDir);

    // Start the npm process
    spawn('npm', ['publish'], { stdio:'inherit', cwd:distDir } )
        .on('close', done)
        .on('error', function(error) {
            console.error('  Underlying spawn error: ' + error);
            throw error;
        });
});
Run Code Online (Sandbox Code Playgroud)

请注意,当我们调用 spawn() 时,我们传递了第三个参数,即选项。这里的主要条目是cwd:distDir,它告诉 spawn 从 ./dist/ 目录运行 npm 进程。因为使用spawn可能会导致问题,所以我已经加入spawn错误处理。当我对我的使用进行故障排除时,spawn()我发现以下StackOverflow文章非常有帮助。

这就像一种魅力。我发布的包根目录下有所有文件,./dist/文件夹没有发布。