Home Web Front-end JS Tutorial Detailed explanation of examples of multi-entry js file packaging

Detailed explanation of examples of multi-entry js file packaging

Jun 25, 2017 am 09:28 AM
javascript Entrance Pack document page

The following points need to be made clear:

1. The local front-end debugging code must call the original path and code, but the online operation must be through another packaged path. Here is the generated dist folder.

2. With the introduction of requirejs, how to control the online and offline paths? This is how we control it. The code is as follows:

1

<script src="${resource}/js/base/require.js?1.1.11" data-main="${resource}/js/accountMain"></script>

Copy after login

This${resource} is controlled by the server and passed to the page. Debugging this locally The value of ${resource} is /resource/v1/; Then the value online is /dist/v1/. So the cooperation between online and offline js is completed. Local debugging calls resources under /resource/v1/, and online resources under /dist/v1/. Of course, v1 is actually redundant. At that time, it was mainly a version number added for version release.

#Now we will explain step by step how to package all the entry files under resource/v1/js/.

First take a look at where all my entry files are, as shown in the picture:

#These js are under resource/v1/js/.

The entrance now has 11 js files, and all imported modules need to be packaged into their respective entrance js.

The first step is to copy the fonts, images, css in the original resources and the js under the base in js. The js files under the base are mainly basic libraries, including requirejs library, etc. Copy to the dist folder.

The purpose of copying is that I also need the fonts, images, and css under dist online.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

copy: {/*  main: {

            expand: true,

            cwd: 'src',

            src: '**',

            dest: 'dist/',

          },          */  main:{

              files:[

                {expand: true,cwd: 'resources/v1/css/',src: '**',dest:'dist/v1/css/'},

                {expand: true,cwd: 'resources/v1/fonts/',src: '**',dest:'dist/v1/fonts/'},

                {expand: true,cwd: 'resources/v1/images/',src: '**',dest:'dist/v1/images/'},

                {expand: true,cwd: 'resources/v1/js/base/',src: '**',dest:'dist/v1/js/base/'}

              ]

          }

        }

Copy after login

The second step is to package the entry file through grunt-contrib-requirejs. The configuration file is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// r.js 打包准备var files = grunt.file.expand('resources/v1/js/*.js');var requirejsOptions = {}; //用来存储 打包配置的对象//遍历文件files.forEach(function(file,index,array) {var name = file.substring(file.lastIndexOf('/') + 1);var reqname = name.replace(/\.js$/,'');

        console.log(name);var filename = 'requirejs' + index;

        requirejsOptions[filename] = {

            options: {

                baseUrl: "resources/v1/js",

                paths:{"jquery":'base/jquery-1.11.3.min','vue':'base/vue.min',"vuedraggable":'base/vuedraggable','bootstrap':'base/bootstrap.min',"sortablejs":'base/Sortable',"basicLib":'widgets/basicLib','msg':'widgets/msg','baseUrl':'widgets/baseUrl','common':'widgets/common',"ajaxfileupload":'widgets/ajaxfileupload','document':'widgets/document',"comp":'widgets/comp','header':'module/header','accountCenter':'view/accountCenter','docking':'view/docking','templateUploadCtr':'view/templateUploadCtr'    

                },

                shim:{'vue':{

                        exports:'vue'   },'basicLib':['jquery'],'bootstrap':['jquery'],'ajaxfileupload':['jquery'],'sortablejs':['vue']

                },

                optimizeAllPluginResources: true,

                name: reqname,

                out: 'dist/v1/js/' + name

            }

        };    

    });

Copy after login

Then initialize the configuration and load the registration task

1

2

3

4

5

6

grunt.initConfig({

    requirejs: requirejsOptions

})

 

grunt.loadNpmTasks('grunt-contrib-requirejs');

grunt.registerTask('default', ['requirejs']);

Copy after login

Since my code has es6 syntax, so after merging The es6 syntax is converted to es5; then comments and other comments are removed during compression.

The total configuration code is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

    module.exports = function(grunt) {  // r.js 打包准备var files = grunt.file.expand('resources/v1/js/*.js');var requirejsOptions = {}; //用来存储 打包配置的对象//遍历文件files.forEach(function(file,index,array) {var name = file.substring(file.lastIndexOf('/') + 1);var reqname = name.replace(/\.js$/,'');

        console.log(name);var filename = 'requirejs' + index;

        requirejsOptions[filename] = {

            options: {

                baseUrl: "resources/v1/js",

                paths:{"jquery":'base/jquery-1.11.3.min','vue':'base/vue.min',"vuedraggable":'base/vuedraggable','bootstrap':'base/bootstrap.min',"sortablejs":'base/Sortable',"basicLib":'widgets/basicLib','msg':'widgets/msg','baseUrl':'widgets/baseUrl','common':'widgets/common',"ajaxfileupload":'widgets/ajaxfileupload','document':'widgets/document',"comp":'widgets/comp','header':'module/header','accountCenter':'view/accountCenter','docking':'view/docking','templateUploadCtr':'view/templateUploadCtr'    

                },

                shim:{'vue':{

                        exports:'vue'   },'basicLib':['jquery'],'bootstrap':['jquery'],'ajaxfileupload':['jquery'],'sortablejs':['vue']

                },

                optimizeAllPluginResources: true,

                name: reqname,

                out: 'dist/v1/js/' + name

            }

        };    

    });    //配置参数      grunt.initConfig({  

        pkg: grunt.file.readJSON('package.json'), 

        requirejs:requirejsOptions,

        watch: {

           js: {

            files:['resources/**/*.js'],

            tasks:['default'],

            options: {livereload:false}

          },

          babel:{

              files:'resources/**/*.js',

              tasks:['babel']

          }

        },

 

        jshint:{

            build:['resources/**/*.js'],

            options:{

                jshintrc:'.jshintrc' //检测JS代码错误            }

        },

        copy: {/*  main: {

            expand: true,

            cwd: 'src',

            src: '**',

            dest: 'dist/',

          },          */  main:{

              files:[

                {expand: true,cwd: 'resources/v1/css/',src: '**',dest:'dist/v1/css/'},

                {expand: true,cwd: 'resources/v1/fonts/',src: '**',dest:'dist/v1/fonts/'},

                {expand: true,cwd: 'resources/v1/images/',src: '**',dest:'dist/v1/images/'},

                {expand: true,cwd: 'resources/v1/js/base/',src: '**',dest:'dist/v1/js/base/'}

              ]

          }

        },

        babel: {

            options: {

                sourceMap: false,

                presets: ['babel-preset-es2015']    

            },

            dist: {

                files: [{

                   expand:true,

                   cwd:'dist/v1/js/'//js目录下   src:['*.js'], //所有js文件   dest:'dist/v1/js/'  //输出到此目录下                 }] 

            }

        },

 

         

        uglify: {  

            options: {

                mangle: true, //混淆变量名comments: 'false' //false(删除全部注释),some(保留@preserve @license @cc_on等注释)            },  

            my_target: {

                 files: [{

                   expand:true,

                   cwd:'dist/v1/js/'//js目录下   src:['*.js'], //所有js文件   dest:'dist/v1/js/'  //输出到此目录下                 }] 

            

        }

         

    });  

       

      //载入uglify插件,压缩js   grunt.loadNpmTasks('grunt-contrib-copy');

      grunt.loadNpmTasks('grunt-babel');      //grunt.loadNpmTasks('grunt-contrib-jshint');  grunt.loadNpmTasks('grunt-contrib-uglify');

      grunt.loadNpmTasks('grunt-contrib-requirejs');

      grunt.loadNpmTasks('grunt-contrib-watch');      

      //注册任务  grunt.registerTask('default', ['copy','requirejs','babel','uglify']);

      grunt.registerTask('watcher',['watch']);

    }

Copy after login

Reference address:

Use grunt to complete the merge and compression of requirejs and the version control of js files

requirejs Multiple pages, multiple js packaging codes, requirejs many-to-many packaging [Collection]

The above is the detailed content of Detailed explanation of examples of multi-entry js file packaging. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

Detailed explanation of the role of .ibd files in MySQL and related precautions Detailed explanation of the role of .ibd files in MySQL and related precautions Mar 15, 2024 am 08:00 AM

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage

What is the entrance URL of Manwa Comics? What is the entrance URL of Manwa Comics? Feb 27, 2024 pm 06:58 PM

Manwa Comics is a comic reading platform. It has a lot of wonderful comic resources recommended to everyone. Everyone can watch them according to their own preferences. However, many users have never been able to find the entrance URL of Manwa Comics. So this book Below, the site editor will share with you the entrance to Frog Comics, so that you can better find the comics you like! I hope it can help everyone in need. Frog Comics entrance: https://fuw11.cc/mw666 Frog Comics is currently closed. What I share with you is the official entrance of Manwa Comics. Manwa Comics is also a comics reading platform. Here you can see many types of comics, including Japanese comics, Korean comics, European and American comics and other resources that you are interested in. All of them are free resources.

How to implement page jump in 3 seconds: PHP Programming Guide How to implement page jump in 3 seconds: PHP Programming Guide Mar 25, 2024 am 10:42 AM

Title: Implementation method of page jump in 3 seconds: PHP Programming Guide In web development, page jump is a common operation. Generally, we use meta tags in HTML or JavaScript methods to jump to pages. However, in some specific cases, we need to perform page jumps on the server side. This article will introduce how to use PHP programming to implement a function that automatically jumps to a specified page within 3 seconds, and will also give specific code examples. The basic principle of page jump using PHP. PHP is a kind of

See all articles