programing

디렉토리에 있는 모든 자바스크립트 파일을 angularjs에 html 파일에 포함하시겠습니까?투덜거리며?

jooyons 2023. 10. 17. 20:14
반응형

디렉토리에 있는 모든 자바스크립트 파일을 angularjs에 html 파일에 포함하시겠습니까?투덜거리며?

인 마이 앵글JS app, 컨트롤러 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 질문 중에.

AngularJS의 폴더에 JavaScript 및 CSS 파일 로드

자바스크립트 파일을 통해 디렉토리에 모든 자바스크립트 파일을 포함하려면 어떻게 해야 합니까?

자동으로 실행할 수 없고 서버측 스크립팅이나 빌드 도구가 필요하다는 것을 알게 되었습니다.

내 질문:

지금은 제가 사용하고 있습니다.yeoman포함하여grunt제작 도구용입니다.그렇다면, 제 질문은 어떻게 디렉토리에 있는 자바스크립트 파일들이 자동으로 html 파일에 포함될 수 있을까요?

grunt-include-source 플러그인을 사용할 수 있습니다.

이를 사용하여 다음과 같은 템플릿을 정의할 수 있습니다.

html: {
    js: '<script src="{filePath}"></script>',
    css: '<link rel="stylesheet" type="text/css" href="{filePath}" />',
  }

당신의 html 파일에서, grunt 작업에서 구성될 수 있는 당신의 소스 위치에 존재하는 당신의 모든 소스 js와 css 파일을 포함하도록 확장될 것입니다.

주문 시 index.html에 소스 파일을 추가하고 grunt-include-source 사용에 대해 자동으로 설명하는 일반적인 질문에 답합니다.

이것은 다음 폴더 구조를 위한 것입니다.

MyProject
|
+-- index.js
+-- Gruntfile.js
+-- package.json
+-- //other files
|
+--+ app
   +-- //app files (.html,.js,.css,.*)
  1. 설치 대상npm i -D grunt-include-source grunt-contrib-watch.

  2. 당신의Gruntfile.js,더하다grunt.loadNpmTasks('grunt-include-source');

  3. 그런 다음 여러 가지 작업을 추가해야 합니다.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']);
    };
    
  4. 당신의index.html, 다음을 추가합니다(여기의 파일 경로는 에 설정된 기본 경로 안에 표시됩니다).

    <!-- include: "type": "css", "files": "**/*.css" -->
    <!-- /include -->
    <!-- include: "type": "js", "files": "**/*.js" -->
    <!-- /include -->
    
  5. 마지막으로 명령줄에서:

    grunt
    

이것은 순차적으로 모든 작업을 시작해야 하며, 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 -->

링크:

다음과 같은 것을 사용할 수 있습니다.

(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;
 }
})();

언급URL : https://stackoverflow.com/questions/24097146/include-all-javascript-files-in-a-directory-to-a-html-file-in-angularjs-with-gr

반응형