npm - 如何安装 grunt 以及如何用它构建脚本

标签 npm gruntjs npm-install

您好,我正在尝试在 Windows 7 64 位上安装 Grunt。我已经使用命令安装了 Grunt

 npm install -g grunt
 npm install -g grunt-cli

但是现在如果我尝试执行grunt init,它会抛出一个错误 -

A valid Gruntfile could not be found. Please see the getting started guide for more information on how to configure grunt: http://gruntjs.com/getting-started Fatal error: Unable to find Gruntfile.

但是当我查看系统上的 grunt 文件夹时,Gruntfile.js 就在那里。有人可以指导我如何正确安装这个 grunt 以及如何使用 grunt 编写内置脚本。我有一个 HTML 页面和 java 脚本,如果我想使用 Grunt 构建一个脚本,我该怎么做?

最佳答案

要在此处设置 GruntJS 构建,步骤如下:

  1. 确保您已设置 package.json 或设置新的:

    npm init
    
  2. 将 Grunt CLI 安装为全局:

    npm install -g grunt-cli
    
  3. 在本地项目中安装 Grunt:

    npm install grunt --save-dev
    
  4. 安装您在构建过程中可能需要的任何 Grunt 模块。为了这个示例,我将添加 Concat 模块来将文件组合在一起:

    npm install grunt-contrib-concat --save-dev
    
  5. 现在您需要设置 Gruntfile.js,它将描述您的构建过程。对于此示例,我只需在 js 文件夹中组合两个 JS 文件 file1.jsfile2.js 并生成 app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. 现在您将准备好通过以下命令运行构建过程:

    grunt
    

我希望这能让您了解如何使用 GruntJS 构建。

注意:

如果您想要基于向导的创建而不是第 5 步的原始编码,则可以使用 grunt-init 创建 Gruntfile.js

为此,请按照以下步骤操作:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

对于 Windows 用户:如果您使用 cmd.exe,则需要将 ~/.grunt-init/gruntfile 更改为 %USERPROFILE%\.grunt-init\ 。 PowerShell 将正确识别 ~

关于npm - 如何安装 grunt 以及如何用它构建脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15703598/

相关文章:

node.js - 是否可以更改 node.js 命令提示符的默认路径?

linux - 通过 `creact-react-app` react 应用程序不工作

javascript - grunt 服务器无法连接 <gruntjs>

reactjs - 将 ReactJS 与 npm 一起使用及其给出以下错误(意外标记)

node.js - npm 错误!提取 @agm/core@1.0.0-beta.3 时验证失败 :

react-native - NPM 安装在 react-native 项目 : "unable to resolve dependency tree for react & react-dom" 上失败

node.js - Sinon 在执行 npm install 时没有安装

javascript - 编写依赖父构建工具的 Vue 组件的正确方法

构建应用程序时,Yeoman 供应商图像路径不正确

javascript - grunt-babel 挂起并且不返回错误消息