Включить все файлы javascript в каталог в html файл в angularjs? с ворчанием?
В моем приложении AngularJS у меня много файлов js-контроллеров.
Эти контроллеры (one.ctrl.js
, two.ctrl.js
, ...
) должны быть включены в мой файл index.html
.
Структура каталогов:
app/
js/
controllers/
one.ctrl.js
two.ctrl.js
В настоящее время выше js
файлы включены в файл index.html
следующим образом.
index.html
<!-- other html components -->
<script src="js/controllers/one.ctrl.js"/>
<script src="js/controllers/two.ctrl.js"/>
</body>
</html>
Будет больше файлов *.ctrl.js
, которые должны быть включены в index.html
.
Мне нужен способ автоматического включения всех файлов *.ctrl.js
в каталог controllers
в index.html
.
Выводы:
Из некоторых вопросов SO,
Загрузите файлы JavaScript и CSS в папки в AngularJS
Как включить все файлы JavaScript в каталог через файл JavaScript?
Я обнаружил, что это невозможно сделать автоматически, и для этого требуются некоторые скриптовые скрипты или инструменты сборки на стороне сервера.
Мой вопрос:
В настоящее время я использую yeoman
, которые включают grunt
для инструмента построения.
Итак, мой вопрос: как эти файлы javascript в каталоге автоматически включаются в html файл?
Ответы
Ответ 1
Вы можете использовать плагин grunt-include-source
Используя его, вы можете определить такие шаблоны, как эти:
html: {
js: '<script src="{filePath}"></script>',
css: '<link rel="stylesheet" type="text/css" href="{filePath}" />',
}
в вашем html файле, который будет расширен, чтобы включить все ваши исходные js и css файлы, имеющиеся в вашем исходном местоположении, которые могут быть настроены в задаче grunt
Ответ 2
Отвечая на общий вопрос о добавлении исходных файлов в index.html по запросу и автоматически и при разработке grunt-include-source.
Это для следующей структуры папок:
MyProject
|
+-- index.js
+-- Gruntfile.js
+-- package.json
+-- //other files
|
+--+ app
+-- //app files (.html,.js,.css,.*)
-
Установите с помощью 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']);
};
-
В вашем index.html
добавьте это (путь к файлу находится внутри базового пути, установленного в Gruntfile.js
):
<!-- include: "type": "css", "files": "**/*.css" -->
<!-- /include -->
<!-- include: "type": "js", "files": "**/*.js" -->
<!-- /include -->
-
Наконец, в командной строке:
grunt
Это должно начинаться со всех задач в последовательности, и ваш index.html должен быть соответствующим образом обновлен при добавлении или удалении JS или CSS.
Вот как ваш 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 -->
Ссылки:
Ответ 3
Вы можете использовать что-то вроде этого:
(function loadScript() {
var head = document.getElementsByTagName("head")[0];
var done = false;
var directory = 'libraries/';
var extension = '.js';
var files = ['functions', 'speak', 'commands', 'wsBrowser', 'main'];
for (var file of files){
var path = directory + file + extension;
var script = document.createElement("script");
script.src = path;
script.onload = script.onreadystatechange = function() {
// attach to both events for cross browser finish detection:
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
// cleans up a little memory:
script.onload = script.onreadystatechange = null;
// to avoid douple loading
head.removeChild(script);
}
};
head.appendChild(script);
done = false;
}
})();