2016-05-31 93 views
1

我尝试一个简单的使用,使 - grunt-include-source但是我没有成功 -咕噜,包括源不起作用

我Gruntfile是 -

module.exports = function (grunt) { 
    grunt.initConfig({ 
     includeSource: { 
     options: { 
      basePath: 'app/file1.js' 
     }, 
     myTarget: { 
      files: { 
      'dist/index.html': 'app/index.html' 
      } 
     } 
     } 
    }); 
    grunt.loadNpmTasks('grunt-include-source'); 
    grunt.registerTask('serve', function (target) { 
     grunt.task.run('includeSource'); 
    }); 
} 

中的index.html是 -

<html> 
<head> 
</head> 
<body> 
    <!-- include: "type": "js", "files": "scripts/*.js" --> 
</body> 
</html> 

我的文件夹层次是 -

Gruntfile.js 
app > 
    file1.js 
    index.html 
dist > 
    index.html 

我跑grunt serve并在dist>index.html文件夹中得到的输出 -

<html> 
<head> 
</head> 
<body> 

</body> 
</html> 

没有预期 - <script src="scripts/file1.js"></script>

我一直遵循作为documentation并在此question

为什么我不没有达到预期的产出?

+0

你可以发布您的完整gruntfile –

+0

这是整个文件 – URL87

回答

2

您的代码有两个问题,第一个是gruntfile中指定了错误的路径,第二个问题是您的html指定了错误的源代码。

让我们通过部分去,在你gruntfile你有这样的:

... 
    includeSource: { 
    options: { 
     basePath: 'app/file1.js' 
    }, 
... 

上Docs的基本路径选项说:

类型:字符串或数组[字符串]默认值: ''

展开文件时使用的基本路径。可以是一个数组来支持 从多个路径扩展文件。

这使得我们可以做的是将一条或多条路径作为我们脚本的基本路径。因此,让我们改变我们的基本路径,以basePath: 'app',我们Gruntfile.js将这个样子:

module.exports = function (grunt) { 
    grunt.initConfig({ 
    includeSource: { 
     options: { 
     basePath: 'app' 
     }, 
     myTarget: { 
     files: { 
      'dist/index.html': 'app/index.html' 
     } 
     } 
    } 
    }); 
    grunt.loadNpmTasks('grunt-include-source'); 
    grunt.registerTask('serve', function (target) { 
    grunt.task.run('includeSource'); 
    }); 
}; 

现在,如果我们运行grunt serve它不会工作,为什么?那么因为您的index.html你有这样的:

<!-- include: "type": "js", "files": "scripts/*.js" --> 

这意味着,插入脚本标签,所有的JavaScript文件中,脚本文件夹内,但我们没有任何脚本文件夹,所以这就是为什么您的dist/index.html为空。让我们的index.html改成这样:

<!-- include: "type": "js", "files": "*.js" --> 

运行grunt serve等瞧你的索引。HTML已更改为:

<html> 
<head> 
</head> 
<body> 
    <script src="file1.js"></script> 
</body> 
</html> 

现在,你只需要从app/复制file1.jsdist/

+0

不过,有一个选项,以指示特定的js档案? – URL87

+0

@ URL87你可以将你的index.html文件改为'<! - include:“type”:“js”,“files”:“file1.js” - >' –