Gulp를 사용한 Concat 스크립트
예를 들어 Backbone 또는 기타 프로젝트에서 프로젝트를 빌드 중이고 스크립트를 특정 순서 underscore.js
로로드해야합니다 ( 예 : 이전에로드해야 함) backbone.js
.
순서대로 스크립트를 연결하려면 어떻게해야합니까?
// JS concat, strip debugging and minify
gulp.task('scripts', function() {
gulp.src(['./source/js/*.js', './source/js/**/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./build/js/'));
});
내에서 올바른 스크립트 순서가 source/index.html
있지만 파일이 알파벳 순서로 구성되어 있으므로 gulp는 underscore.js
이후 backbone.js
에 연결 되며 내 스크립트의 순서는 source/index.html
중요하지 않으므로 디렉토리의 파일을 찾습니다.
누구든지 이것에 대한 아이디어가 있습니까?
내가 가진 최고의 아이디어와 공급 업체 스크립트의 이름을 변경하는 것입니다 1
, 2
, 3
그들에게 적절한 순서를 제공하지만,이 같은 내가 있는지 확실하지 않다.
더 많은 것을 알았을 때 Browserify가 훌륭한 솔루션이라는 것을 알았습니다. 처음에는 고통이 될 수 있지만 훌륭합니다.
AngularJS 앱을 만들 때 최근 Grunt와 비슷한 문제가 발생했습니다. 여기 질문 내가 게시는.
내가 한 일은 grunt 설정에서 파일을 명시 적으로 나열하는 것입니다. 그래서 다음과 같이 보였습니다 :
[
'/path/to/app.js',
'/path/to/mymodule/mymodule.js',
'/path/to/mymodule/mymodule/*.js'
]
그리고 일들이 효과가있었습니다. 그런트는 같은 파일을 두 번 포함하지 않을만큼 똑똑합니다.
이것은 Gulp와 동일하게 작동합니다.
여러 파일 뒤에 오는 파일이 필요한 경우 도움이되는 또 다른 방법은 다음 과 같이 글로브에서 특정 파일을 제외시키는 것입니다.
[
'/src/**/!(foobar)*.js', // all files that end in .js EXCEPT foobar*.js
'/src/js/foobar.js',
]
이것을 Chad Johnson의 답변에 설명 된대로 가장 먼저 필요한 파일을 지정하는 것과 결합 할 수 있습니다.
gulp-order 플러그인을 사용했지만 스택 오버플로 post gulp-order 노드 모듈에서 병합 된 스트림으로 볼 수 있듯이 항상 성공하지는 않습니다 . Gulp 문서를 탐색 할 때 스트림 연결 모듈을 발견했습니다.이 모듈은 순서대로 연결 순서를 지정하는 데 매우 효과적이었습니다. https://github.com/gulpjs/gulp/blob/master/docs/recipes/using-multiple-sources-in-one-task.md
내가 사용한 방법의 예는 다음과 같습니다.
var gulp = require('gulp');
var concat = require('gulp-concat');
var handleErrors = require('../util/handleErrors');
var streamqueue = require('streamqueue');
gulp.task('scripts', function() {
return streamqueue({ objectMode: true },
gulp.src('./public/angular/config/*.js'),
gulp.src('./public/angular/services/**/*.js'),
gulp.src('./public/angular/modules/**/*.js'),
gulp.src('./public/angular/primitives/**/*.js'),
gulp.src('./public/js/**/*.js')
)
.pipe(concat('app.js'))
.pipe(gulp.dest('./public/build/js'))
.on('error', handleErrors);
});
gulp-useref를 사용하면 색인 파일에 선언 된 모든 스크립트를 선언 된 순서대로 연결할 수 있습니다.
https://www.npmjs.com/package/gulp-useref
var $ = require('gulp-load-plugins')();
gulp.task('jsbuild', function () {
var assets = $.useref.assets({searchPath: '{.tmp,app}'});
return gulp.src('app/**/*.html')
.pipe(assets)
.pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
.pipe(gulp.dest('dist'))
.pipe($.size({title: 'html'}));
});
그리고 HTML에서 다음과 같이 생성하려는 빌드 파일의 이름을 선언해야합니다.
<!-- build:js js/main.min.js -->
<script src="js/vendor/vendor.js"></script>
<script src="js/modules/test.js"></script>
<script src="js/main.js"></script>
빌드 디렉토리에는 vendor.js, test.js 및 main.js를 포함하는 main.min.js에 대한 참조가 있습니다.
정렬 스트림은 또한 가진 파일의 특정 순서를 보장하기 위해 사용될 수있다 gulp.src
. backbone.js
항상 처리 할 마지막 파일로 두는 샘플 코드 :
var gulp = require('gulp');
var sort = require('sort-stream');
gulp.task('scripts', function() {
gulp.src(['./source/js/*.js', './source/js/**/*.js'])
.pipe(sort(function(a, b){
aScore = a.path.match(/backbone.js$/) ? 1 : 0;
bScore = b.path.match(/backbone.js$/) ? 1 : 0;
return aScore - bScore;
}))
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./build/js/'));
});
bower에서 가져온 각 패키지마다 스크립트를 다른 폴더에 구성하고 내 앱을위한 스크립트도 있습니다. 이 스크립트의 순서를 어딘가에 나열 할 것이므로 왜 gulp 파일에 나열하지 않습니까? 프로젝트의 새로운 개발자의 경우 모든 스크립트 엔드 포인트가 여기에 나열되어있는 것이 좋습니다. gulp-add-src로 이것을 할 수 있습니다 :
gulpfile.js
var gulp = require('gulp'),
less = require('gulp-less'),
minifyCSS = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
addsrc = require('gulp-add-src'),
sourcemaps = require('gulp-sourcemaps');
// CSS & Less
gulp.task('css', function(){
gulp.src('less/all.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(minifyCSS())
.pipe(sourcemaps.write('source-maps'))
.pipe(gulp.dest('public/css'));
});
// JS
gulp.task('js', function() {
gulp.src('resources/assets/bower/jquery/dist/jquery.js')
.pipe(addsrc.append('resources/assets/bower/bootstrap/dist/js/bootstrap.js'))
.pipe(addsrc.append('resources/assets/bower/blahblah/dist/js/blah.js'))
.pipe(addsrc.append('resources/assets/js/my-script.js'))
.pipe(sourcemaps.init())
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(sourcemaps.write('source-maps'))
.pipe(gulp.dest('public/js'));
});
gulp.task('default',['css','js']);
참고 : jQuery 및 Bootstrap은 데모 목적으로 추가되었습니다. CDN은 널리 사용되며 브라우저는 이미 다른 사이트에서 캐시 할 수 있기 때문에 CDN을 사용하는 것이 좋습니다.
I just add numbers to the beginning of file name:
0_normalize.scss
1_tikitaka.scss
main.scss
It works in gulp without any problems.
Try stream-series. It works like merge-stream/event-stream.merge() except that instead of interleaving, it appends to the end. It doesn't require you to specify the object mode like streamqueue, so your code comes out cleaner.
var series = require('stream-series');
gulp.task('minifyInOrder', function() {
return series(gulp.src('vendor/*'),gulp.src('extra'),gulp.src('house/*'))
.pipe(concat('a.js'))
.pipe(uglify())
.pipe(gulp.dest('dest'))
});
An alternative method is to use a Gulp plugin created specifically for this problem. https://www.npmjs.com/package/gulp-ng-module-sort
It allows you to sort your scripts by adding in a .pipe(ngModuleSort())
as such:
var ngModuleSort = require('gulp-ng-module-sort');
var concat = require('gulp-concat');
gulp.task('angular-scripts', function() {
return gulp.src('./src/app/**/*.js')
.pipe(ngModuleSort())
.pipe(concat('angularAppScripts.js))
.pipe(gulp.dest('./dist/));
});
Assuming a directory convention of:
|——— src/
| |——— app/
| |——— module1/
| |——— sub-module1/
| |——— sub-module1.js
| |——— module1.js
| |——— module2/
| |——— sub-module2/
| |——— sub-module2.js
| |——— sub-module3/
| |——— sub-module3.js
| |——— module2.js
| |——— app.js
Hope this helps!
For me I had natualSort() and angularFileSort() in pipe which was reordering the files. I removed it and now it works fine for me
$.inject( // app/**/*.js files
gulp.src(paths.jsFiles)
.pipe($.plumber()), // use plumber so watch can start despite js errors
//.pipe($.naturalSort())
//.pipe($.angularFilesort()),
{relative: true}))
merge2 looks like the only working and maintained ordered stream merging tool at the moment.
I just use gulp-angular-filesort
function concatOrder() {
return gulp.src('./build/src/app/**/*.js')
.pipe(sort())
.pipe(plug.concat('concat.js'))
.pipe(gulp.dest('./output/'));
}
I'm in a module environnement where all are core-dependents using gulp. So, the core
module needs to be appended before the others.
What I did:
- Move all the scripts to an
src
folder - Just
gulp-rename
yourcore
directory to_core
gulp is keeping the order of your
gulp.src
, my concatsrc
looks like this:concat: ['./client/src/js/*.js', './client/src/js/**/*.js', './client/src/js/**/**/*.js']
It'll obviously take the _
as the first directory from the list (natural sort?).
Note (angularjs): I then use gulp-angular-extender to dynamically add the modules to the core
module. Compiled it looks like this:
angular.module('Core', ["ui.router","mm.foundation",(...),"Admin","Products"])
Where Admin and Products are two modules.
if you would like to order third party libraries dependencies, try wiredep. This package basically checks each package dependency in bower.json then wire them up for you.
I tried several solutions from this page, but none worked. I had a series of numbered files which I simply wanted be ordered by alphabetical foldername so when piped to concat()
they'd be in the same order. That is, preserve the order of the globbing input. Easy, right?
Here's my specific proof-of-concept code (print
is just to see the order printed to the cli):
var order = require('gulp-order');
var gulp = require('gulp');
var print = require('gulp-print').default;
var options = {};
options.rootPath = {
inputDir: process.env.INIT_CWD + '/Draft',
inputGlob: '/**/*.md',
};
gulp.task('default', function(){
gulp.src(options.rootPath.inputDir + options.rootPath.inputGlob, {base: '.'})
.pipe(order([options.rootPath.inputDir + options.rootPath.inputGlob]))
.pipe(print());
});
The reason for the madness of gulp.src
? I determined that gulp.src
was running async when I was able to use a sleep()
function (using a .map
with sleeptime incremented by index) to order the stream output properly.
The upshot of the async of src
mean dirs with more files in it came after dirs with fewer files, because they took longer to process.
In my gulp setup, I'm specifying the vendor files first and then specifying the (more general) everything, second. And it successfully puts the vendor js before the other custom stuff.
gulp.src([
// vendor folder first
path.join(folder, '/vendor/**/*.js'),
// custom js after vendor
path.join(folder, '/**/*.js')
])
참고URL : https://stackoverflow.com/questions/21961142/concat-scripts-in-order-with-gulp
'Programing' 카테고리의 다른 글
UIImage : 크기 조정 후 자르기 (0) | 2020.05.15 |
---|---|
IntelliJ IDEA 기본 JDK를 어떻게 변경합니까? (0) | 2020.05.15 |
SQL Server 2008에서 테이블 별칭으로 UPDATE SQL을 작성하는 방법은 무엇입니까? (0) | 2020.05.15 |
MySQL에서 열 이름 바꾸기 (0) | 2020.05.15 |
Java List.add () UnsupportedOperationException (0) | 2020.05.15 |