Javascript Grunt:将package.json和Gruntfile.js放在不同的文件夹中

Javascript Grunt:将package.json和Gruntfile.js放在不同的文件夹中,javascript,node.js,npm,gruntjs,Javascript,Node.js,Npm,Gruntjs,我在尝试在不同文件夹上实现grunt时遇到问题,在我的根目录中,我有: <root>/package.json <root>/node_modules 我得到: 未找到本地Npm模块“grunt contrib concat”。安装了吗 未找到本地Npm模块“grunt contrib cssmin”。安装了吗 未找到本地Npm模块“grunt contrib clean”。安装了吗 未找到本地Npm模块“grunt contrib watch”。安装了吗 未找到本地N

我在尝试在不同文件夹上实现grunt时遇到问题,在我的根目录中,我有:

<root>/package.json
<root>/node_modules
我得到:

未找到本地Npm模块“grunt contrib concat”。安装了吗

未找到本地Npm模块“grunt contrib cssmin”。安装了吗

未找到本地Npm模块“grunt contrib clean”。安装了吗

未找到本地Npm模块“grunt contrib watch”。安装了吗

未找到本地Npm模块“grunt contrib uglify”。安装了吗

我运行了几次npm安装

在我的Gruntile.js上,你有

grunt.loadNpmTasks('grunt-contrib-concat')

grunt.loadNpmTasks('grunt-contrib-cssmin')

grunt.loadNpmTasks('grunt-contrib-clean')

grunt.loadNpmTasks('grunt-contrib-watch')

grunt.loadNpmTasks('grunt-contrib-uglify')

我三次检查文件夹是否正常(事实上,最初Grunfile和package在同一个文件夹中,一切正常,运行几个任务,一切正常)。我真的需要在根目录上有一个通用的package.json和node_模块,在特定的项目文件夹上有grunfile.js


知道怎么回事吗?提前感谢

Grunt对
gruntfile.js
的位置做了一些假设

使用
--gruntfile
选项指定
gruntfile.js
的位置时,Grunt到包含指定文件的目录:

// Change working directory so that all paths are relative to the
// Gruntfile's location (or the --base option, if specified).
process.chdir(grunt.option('base') || path.dirname(gruntfile));
当Grunt加载NPM任务时,它会这样做:


有一种方法可以指定当前目录,但我不知道这是否会解决您的问题(不会引入其他问题)。最简单的解决方案可能是将
gruntfile.js
定位到它想要和期望的位置。

有时候,project可能需要将
gruntfile.js
放在与
package.json
不同的文件夹中

我有一个非常相似的用例,其中有多个子模块,每个子模块都有自己的构建过程,其中一个是Grunt。但与此同时,我希望有一个通用的
包.json
,以避免创建多个
节点模块
文件夹,以便使用通用依赖项(包括可传递的)安装一次。它有助于减少安装时间和磁盘使用量

我期待着Grunt本身的解决方案。但正如@cartant所提到的,Grunt做出了某些假设

下面是我所做的:

grunfile.js

定义一个函数:

function loadExternalNpmTasks(grunt, name) {
  const tasksdir = path.join(root, 'node_modules', name, 'tasks');
  if (grunt.file.exists(tasksdir)) {
    grunt.loadTasks(tasksdir);
  } else {
    grunt.log.error('Npm module "' + name + '" not found. Is it installed?');
  }
}
而不是

grunt.loadNpmTasks('grunt-contrib-concat');
做:


参考资料:

我读过关于--base的文章,但我仍然有问题,我在根文件夹中找到了:找不到有效的Gruntfile。有关如何配置grunt的更多信息,请参阅《入门指南》:致命错误:找不到GrunFile。而gruntfile就在那里。我的问题是,这是一个大项目,将所有内容放在同一个文件中可能会很复杂。我在8个网站上工作,每个网站都必须有自己特定的咕噜声才能让它变得容易。我认为,在试图找到
grunfile.js
一个它不想被找到的地方时,你正在进入一个痛苦的世界。这看起来像是一张照片。如果您的问题很复杂,Grunt还有一些其他机制可以提供不那么痛苦的解决方案(例如)。我建议你再问一个问题,问你的复杂问题是如何解决的。我认为“为什么不工作”这个问题已经得到了回答。
var root = path.resolve('node_modules');
var pkgfile = path.join(root, name, 'package.json');
function loadExternalNpmTasks(grunt, name) {
  const tasksdir = path.join(root, 'node_modules', name, 'tasks');
  if (grunt.file.exists(tasksdir)) {
    grunt.loadTasks(tasksdir);
  } else {
    grunt.log.error('Npm module "' + name + '" not found. Is it installed?');
  }
}
grunt.loadNpmTasks('grunt-contrib-concat');
loadExternalNpmTasks(grunt, 'grunt-contrib-concat');