Javascript 将所有代码放在一个js文件中,而不是将代码拆分为多个js文件
到目前为止,我的项目中只有一个javascript文件,其中包含了大量的函数,只有很少几个函数被多个网页使用。随着涉及的代码量的增加,我可以看到该文件变得凌乱且过长。我正在考虑为每个网页提供一个单独的javascript文件,以便:Javascript 将所有代码放在一个js文件中,而不是将代码拆分为多个js文件,javascript,code-separation,Javascript,Code Separation,到目前为止,我的项目中只有一个javascript文件,其中包含了大量的函数,只有很少几个函数被多个网页使用。随着涉及的代码量的增加,我可以看到该文件变得凌乱且过长。我正在考虑为每个网页提供一个单独的javascript文件,以便: 我不必加载一个巨大的javascript文件,即使对于那些很少使用它的页面也是如此 文件没有变得更乱 但我不知道这是否会有我不知道的负面影响 文件越少,代码越不干净,这反过来意味着编码速度越慢,调试难度越大。 更多的文件意味着更多的HTTP请求和较慢的网站。因此,开
但我不知道这是否会有我不知道的负面影响 文件越少,代码越不干净,这反过来意味着编码速度越慢,调试难度越大。
更多的文件意味着更多的HTTP请求和较慢的网站。因此,开发尽可能多的文件以组织代码并保持开发的可管理性。拥有多个文件确实有助于组织工作,但同时需要浏览器向服务器发出多个请求,这可能会影响站点加载时间 这就是为什么现在很多人使用诸如 简而言之,它将允许您定义任意数量的小模块(每个模块位于单独的文件中),然后异步加载它们 如果你将它与一些构建工具(如Grunt)结合,你可以拥有一个只加载两个文件的网页(RequireJS库和你的JS文件,即
main.JS
),但是main.JS
将是连接许多较小模块的结果
通过这种方式,您可以将请求的数量保留在minium中,同时,您的代码被组织并拆分为小模块—成本是多少?您将引入一个额外的构建步骤。不过,可以使用grunt contrib watch
等工具进一步自动化此构建步骤
以下是一个站点的几个代码片段,该站点使用一个
main.js
文件,还依赖于将从Google CDN加载的jQuery:
首先,main.js:它是一个RequireJS模块(是AMD模块),看起来像:
// Tell RequireJS that jQuery dependency should be loaded from the given URL.
// Without this, RequireJS would try to find jQuery.js file locally.
requirejs.config({
paths: {
'jQuery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
},
shim: {
'jQuery': {'exports': 'jQuery'},
}
});
// You define that the module below depends on jQuery and two custom modules.
define(['jQuery', 'module1', 'module2'], function ($, Module1, Module2) {
// Here you can access $, Module1 and Module2
});
然后使用Grunt的Grunt contrib requirejs
插件,其配置类似于(grunfile.js):
最后,加载RequireJS脚本并告诉它使用main.js
文件作为站点的入口点(index.html):
这里有许多选项,仅侧重于组织文件,如果您正在处理的文件相当大,则值得考虑使用库。然而,这是针对应用程序的,即使您可以轻松地将其用于其他事情,其想法是将代码重新构造为独立模块,这在您的情况下可能是明智的,也可能是不明智的 然而,如果我们正在讨论的javascript与页面内容紧密耦合,因此在它的设置中不可用于其他页面,那么使用内联
标记而不是外部javascript文件是非常正确的
最后一点要注意的是,require.js或任何带有多个javascript的设置都会给http请求带来一些开销,但我不太担心这一点。Require.js或类似的库甚至会为您加载这个异步文件,因此总的来说,它可能比一个巨大的文件更高效,而对于任何给定的访问者来说,这个文件可能不用于大部分内容(尽管这取决于访问者最终是否会访问所有页面)。,我在带有一组逻辑文件夹(服务、控制器、库等)的独立文件中开发所有javascript 但是,我在Node.js上使用了Gulp和Bower。注意,我的服务器端代码不使用Node.JS,只使用前端资产。将其视为客户端资产的分发工具。我使用Gulp Watch监视SRC文件夹,并在处理源代码时自动转换最终的javascript文件 因此,我获得了将所有内容逻辑分离的好处,但仍然获得了用于生产的单个压缩JS文件的性能 下面是一个示例bower.json文件:
{
"name": "MyApp",
"private": true,
"dependencies": {
"jquery": "2.2.4",
"bootstrap": "v4.0.0-alpha.3",
"angular": "^1.5.8",
"font-awesome": "fontawesome#^4.6.3",
"angular-ui-router": "^0.3.1",
"angular-cookies": "^1.5.8",
"angular-ui-select": "^0.19.4",
"angular-ui-tree": "^2.17.0",
"angular-toastr": "^2.0.0",
"angular-animate": "^1.5.8",
"angular-sanitize": "^1.5.8",
"angular-chart": "^0.5.0",
"angular-loading-bar": "^0.9.0",
"angular-messages": "^1.5.8"
},
"devDependencies": {}
}
这是吞咽文件
/// <binding Clean='clean' />
"use strict";
var gulp = require("gulp");
var sass = require("gulp-sass"); //Syntactically Awesome Style Sheets
var sourcemaps = require('gulp-sourcemaps'); //Generate source maps for css and js
var autoprefixer = require('gulp-autoprefixer'); //auto prefix browser specific css
var cleanCss = require('gulp-clean-css'); //minimize css
var rename = require('gulp-rename'); //rename file in gulp stream
var concat = require('gulp-concat'); //concat mutliple files in gulp stream into one
var runSequence = require('run-sequence'); //run mutliple gulp taxes in parrellel or sequence
var uglify = require('gulp-uglify'); //minimize js
var webroot = "./wwwroot/"; //the root folder where the css and js is going
var paths = {
css: webroot + "css/", //path to my css
scss: webroot + "scss/", //path to my scss src files
destJs: webroot + "js/", //path to my js source files (also the destination)
lib: webroot + "/lib/" //path to my lib folder for storing libraries
};
//build both the dev and production styles
gulp.task('build-styles', function (done) {
return runSequence(["build-styles-dev", "build-styles-prod"]);
});
//sass transforms all my scss files individually (producing separate css files for each library I am using)
gulp.task('build-styles-dev', function () {
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded',
sourceMap: true
};
return gulp.src([ //include all my libraries css files that isn't sass based in the front of the stream
paths.lib + '/angular-loading-bar/build/loading-bar.css',
paths.lib + '/angular-toastr/dist/angular-toastr.css',
paths.lib + '/angular-ui-select/dist/select.css',
paths.lib + '/angular-ui-tree/dist/angular-ui-tree.css',
paths.lib + '/tether/dist/css/tether.css',
paths.lib + '/tether/dist/css/tether-theme-basic.css',
paths.scss + '/site.scss' //my sass file (does imports etc in it)
])
.pipe(sass({ errLogToConsole: true, outputStyle: 'expanded', sourceMap: true }).on('error', sass.logError))
.pipe(autoprefixer()) //autoprefix browser specific css
.pipe(gulp.dest(paths.css)) //output all the sass and auto prefixed css files based on the source
.resume();
});
//same as above task except this one doesn't output the individual files. It concats them all together into one file, compresses it, and generates the source maps for it.
gulp.task('build-styles-prod', function () {
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded',
sourceMap: true
};
return gulp.src([
paths.lib + '/angular-loading-bar/build/loading-bar.css',
paths.lib + '/angular-toastr/dist/angular-toastr.css',
paths.lib + '/angular-ui-select/dist/select.css',
paths.lib + '/angular-ui-tree/dist/angular-ui-tree.css',
paths.lib + '/tether/dist/css/tether.css',
paths.lib + '/tether/dist/css/tether-theme-basic.css',
paths.scss + '/site.scss'
])
.pipe(sass({ errLogToConsole: true, outputStyle: 'expanded', sourceMap: true }).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(concat("compiled.css"))
.pipe(gulp.dest(paths.css))
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(cleanCss())
.pipe(rename({ suffix: '.min' }))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.css))
.resume();
});
//grabs all the library scripts and compresses them into one js file
gulp.task('build-scripts', function () {
return gulp.src([
paths.lib + 'jquery/dist/jquery.js',
paths.lib + 'tether/dist/js/tether.js',
paths.lib + 'angular/angular.js',
paths.lib + 'angular-messages/angular-messages.js',
paths.lib + 'angular-animate/angular-animate.js',
paths.lib + 'angular-cookies/angular-cookies.js',
paths.lib + 'angular-chart/angular-chart.js',
paths.lib + 'angular-loading-bar/build/loading-bar.js',
paths.lib + 'angular-toastr/dist/angular-toastr.js',
paths.lib + 'angular-sanitize/angular-sanitize.js',
paths.lib + 'angular-ui-router/release/angular-ui-router.js',
paths.lib + 'angular-ui-select/dist/select.js',
paths.lib + 'angular-ui-tree/dist/angular-ui-tree.js',
paths.lib + 'bootstrap/dist/js/bootstrap.js',
paths.js + 'app.js', //Load app.js first
paths.js + 'services/**/*.js', //Load all angular services next
paths.js + 'directives/**/*.js', //load directives after services
paths.js + 'controllers/**/*.js', //load angular controllers last after services and directives
paths.js + 'appLast.js', //A tail script I have load last for end of page logic, preventing the need for me to use document ready since this loads in the page footer.
])
.pipe(sourcemaps.init())
.pipe(gulp.dest(paths.destJs)) //output all the files individually (so file names need to be unique accross the whole system, generally not a problem)
.pipe(concat('scripts.js')) //concat all the scripts together into one file called scripts.js
.pipe(uglify()) //minimize all the scripts
.pipe(rename({ suffix: '.min' })) //rename to scripts.min.js
.pipe(sourcemaps.write('.')) //write the source maps
.pipe(gulp.dest(paths.destJs)); //output scripts.min.js
});
//
“严格使用”;
var gulp=需要(“gulp”);
var sass=需要(“吞咽sass”)//语法上很棒的样式表
var sourcemaps=require('gulp-sourcemaps')//为css和js生成源映射
var autoprefixer=require('gulp-autoprefixer')//自动前缀特定于浏览器的css
var cleanCss=require('gulp-clean-css')//最小化css
var rename=require('gulp-rename')//重命名gulp流中的文件
var concat=需要(“咕噜咕噜咕噜”)//将多个文件压缩成一个文件
var runSequence=require('run-sequence')//以Parrelell或sequence运行多个吞咽税
var-uglify=需要('gulp-uglify')//最小化js
var webroot=“./wwwroot/”//css和js所在的根文件夹
变量路径={
css:webroot+“css/”,//指向我的css的路径
scss:webroot+“scss/”,//指向我的scss src文件的路径
destJs:webroot+“js/”,//指向我的js源文件的路径(也是目标)
lib:webroot+“/lib/”//用于存储库的我的lib文件夹的路径
};
//构建开发和生产样式
吞咽任务(“构建样式”,功能(完成){
返回runSequence([“构建样式开发”、“构建样式生产”]);
});
//sass分别转换我的所有scss文件(为我使用的每个库生成单独的css文件)
gulp.task('build-styles-dev',function(){
var sassOptions={
errLogToConsole:true,
outputStyle:“已扩展”,
sourceMap:true
};
return gulp.src([//在流前面包含所有不基于sass的我的库css文件
paths.lib+'/angular loading bar/build/loading bar.css',
paths.lib+'/angular-toastr/dist/angular-toastr.css',
paths.lib+/angular ui select/dist/select.css',
paths.lib+'/angular ui tree/dist/angular ui tree.css',
{
"name": "MyApp",
"private": true,
"dependencies": {
"jquery": "2.2.4",
"bootstrap": "v4.0.0-alpha.3",
"angular": "^1.5.8",
"font-awesome": "fontawesome#^4.6.3",
"angular-ui-router": "^0.3.1",
"angular-cookies": "^1.5.8",
"angular-ui-select": "^0.19.4",
"angular-ui-tree": "^2.17.0",
"angular-toastr": "^2.0.0",
"angular-animate": "^1.5.8",
"angular-sanitize": "^1.5.8",
"angular-chart": "^0.5.0",
"angular-loading-bar": "^0.9.0",
"angular-messages": "^1.5.8"
},
"devDependencies": {}
}
/// <binding Clean='clean' />
"use strict";
var gulp = require("gulp");
var sass = require("gulp-sass"); //Syntactically Awesome Style Sheets
var sourcemaps = require('gulp-sourcemaps'); //Generate source maps for css and js
var autoprefixer = require('gulp-autoprefixer'); //auto prefix browser specific css
var cleanCss = require('gulp-clean-css'); //minimize css
var rename = require('gulp-rename'); //rename file in gulp stream
var concat = require('gulp-concat'); //concat mutliple files in gulp stream into one
var runSequence = require('run-sequence'); //run mutliple gulp taxes in parrellel or sequence
var uglify = require('gulp-uglify'); //minimize js
var webroot = "./wwwroot/"; //the root folder where the css and js is going
var paths = {
css: webroot + "css/", //path to my css
scss: webroot + "scss/", //path to my scss src files
destJs: webroot + "js/", //path to my js source files (also the destination)
lib: webroot + "/lib/" //path to my lib folder for storing libraries
};
//build both the dev and production styles
gulp.task('build-styles', function (done) {
return runSequence(["build-styles-dev", "build-styles-prod"]);
});
//sass transforms all my scss files individually (producing separate css files for each library I am using)
gulp.task('build-styles-dev', function () {
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded',
sourceMap: true
};
return gulp.src([ //include all my libraries css files that isn't sass based in the front of the stream
paths.lib + '/angular-loading-bar/build/loading-bar.css',
paths.lib + '/angular-toastr/dist/angular-toastr.css',
paths.lib + '/angular-ui-select/dist/select.css',
paths.lib + '/angular-ui-tree/dist/angular-ui-tree.css',
paths.lib + '/tether/dist/css/tether.css',
paths.lib + '/tether/dist/css/tether-theme-basic.css',
paths.scss + '/site.scss' //my sass file (does imports etc in it)
])
.pipe(sass({ errLogToConsole: true, outputStyle: 'expanded', sourceMap: true }).on('error', sass.logError))
.pipe(autoprefixer()) //autoprefix browser specific css
.pipe(gulp.dest(paths.css)) //output all the sass and auto prefixed css files based on the source
.resume();
});
//same as above task except this one doesn't output the individual files. It concats them all together into one file, compresses it, and generates the source maps for it.
gulp.task('build-styles-prod', function () {
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded',
sourceMap: true
};
return gulp.src([
paths.lib + '/angular-loading-bar/build/loading-bar.css',
paths.lib + '/angular-toastr/dist/angular-toastr.css',
paths.lib + '/angular-ui-select/dist/select.css',
paths.lib + '/angular-ui-tree/dist/angular-ui-tree.css',
paths.lib + '/tether/dist/css/tether.css',
paths.lib + '/tether/dist/css/tether-theme-basic.css',
paths.scss + '/site.scss'
])
.pipe(sass({ errLogToConsole: true, outputStyle: 'expanded', sourceMap: true }).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(concat("compiled.css"))
.pipe(gulp.dest(paths.css))
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(cleanCss())
.pipe(rename({ suffix: '.min' }))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.css))
.resume();
});
//grabs all the library scripts and compresses them into one js file
gulp.task('build-scripts', function () {
return gulp.src([
paths.lib + 'jquery/dist/jquery.js',
paths.lib + 'tether/dist/js/tether.js',
paths.lib + 'angular/angular.js',
paths.lib + 'angular-messages/angular-messages.js',
paths.lib + 'angular-animate/angular-animate.js',
paths.lib + 'angular-cookies/angular-cookies.js',
paths.lib + 'angular-chart/angular-chart.js',
paths.lib + 'angular-loading-bar/build/loading-bar.js',
paths.lib + 'angular-toastr/dist/angular-toastr.js',
paths.lib + 'angular-sanitize/angular-sanitize.js',
paths.lib + 'angular-ui-router/release/angular-ui-router.js',
paths.lib + 'angular-ui-select/dist/select.js',
paths.lib + 'angular-ui-tree/dist/angular-ui-tree.js',
paths.lib + 'bootstrap/dist/js/bootstrap.js',
paths.js + 'app.js', //Load app.js first
paths.js + 'services/**/*.js', //Load all angular services next
paths.js + 'directives/**/*.js', //load directives after services
paths.js + 'controllers/**/*.js', //load angular controllers last after services and directives
paths.js + 'appLast.js', //A tail script I have load last for end of page logic, preventing the need for me to use document ready since this loads in the page footer.
])
.pipe(sourcemaps.init())
.pipe(gulp.dest(paths.destJs)) //output all the files individually (so file names need to be unique accross the whole system, generally not a problem)
.pipe(concat('scripts.js')) //concat all the scripts together into one file called scripts.js
.pipe(uglify()) //minimize all the scripts
.pipe(rename({ suffix: '.min' })) //rename to scripts.min.js
.pipe(sourcemaps.write('.')) //write the source maps
.pipe(gulp.dest(paths.destJs)); //output scripts.min.js
});