The*_*ect 23 javascript angularjs gruntjs
在我的AngularJS应用程序中,我有很多控制器js文件.
这些控制器(one.ctrl.js
,two.ctrl.js
,...
)需要被包含在我的index.html
文件.
目录结构:
app/
js/
controllers/
one.ctrl.js
two.ctrl.js
Run Code Online (Sandbox Code Playgroud)
目前,上述js
文件包含在index.html
文件中,如下所示.
index.html的:
<!-- other html components -->
<script src="js/controllers/one.ctrl.js"/>
<script src="js/controllers/two.ctrl.js"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
*.ctrl.js
将需要包含更多文件index.html
.
我需要一种方法来自动包含目录中的所有*.ctrl.js
文件.controllers
index.html
发现:
从一些SO问题,
在AngularJS中的文件夹中加载JavaScript和CSS文件
如何通过JavaScript文件将所有JavaScript文件包含在目录中?
我发现它不能自动完成,需要一些服务器端脚本或构建工具.
我的问题:
目前,我正在使用yeoman
哪些包含grunt
用于构建工具.所以,我的问题是,目录中的那些javascript文件如何自动包含在html文件中?
aks*_*kap 13
您可以使用grunt-include-source插件
使用它,您可以定义以下模板:
html: {
js: '<script src="{filePath}"></script>',
css: '<link rel="stylesheet" type="text/css" href="{filePath}" />',
}
Run Code Online (Sandbox Code Playgroud)
在你的html文件中,它将被扩展为包含源位置中存在的所有源js和css文件,可以在grunt任务中配置
回答了根据需要向index.html添加源文件的一般问题,并自动详细说明了grunt-include-source的使用.
这适用于以下文件夹结构:
MyProject
|
+-- index.js
+-- Gruntfile.js
+-- package.json
+-- //other files
|
+--+ app
+-- //app files (.html,.js,.css,.*)
Run Code Online (Sandbox Code Playgroud)
安装时npm i -D grunt-include-source grunt-contrib-watch
.
在你的Gruntfile.js
,添加grunt.loadNpmTasks('grunt-include-source');
然后你必须向你添加一堆任务Gruntfile.js
,之后它应该是这样的:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
//...
watch: {
//...
includeSource: {
// Watch for added and deleted scripts to update index.html
files: ['app/**/*.js','app/**/*.css'],
tasks: ['includeSource'],
options: {
event: ['added', 'deleted']
}
}
},
includeSource: {
options: {
//This is the directory inside which grunt-include-source will be looking for files
basePath: 'app'
},
app: {
files: {
//Overwriting index.html
'app/index.html': 'app/index.html'
}
}
}
});
//...
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-include-source');
//...
//Include sources, run the server, open the browser, and watch.
grunt.registerTask('default', ['includeSource', 'watch']);
};
Run Code Online (Sandbox Code Playgroud)在你的index.html
,添加这个(此处的文件路径在设置的基本路径内查看Gruntfile.js
):
<!-- include: "type": "css", "files": "**/*.css" -->
<!-- /include -->
<!-- include: "type": "js", "files": "**/*.js" -->
<!-- /include -->
Run Code Online (Sandbox Code Playgroud)最后,在命令行上:
grunt
Run Code Online (Sandbox Code Playgroud)这应该按顺序启动所有任务,并且在添加或删除JS或CSS时应相应地更新index.html.
这是您index.html
使用少量文件时的样子:
<!-- include: "type": "css", "files": "**/*.css" -->
<link href="styles.css" rel="stylesheet" type="text/css">
<!-- /include -->
<!-- include: "type": "js", "files": "**/*.js" -->
<script src="_routes/routes.js"></script>
<script src="scripts/app.js"></script>
<!-- /include -->
Run Code Online (Sandbox Code Playgroud)
链接:
归档时间: |
|
查看次数: |
22214 次 |
最近记录: |