펄프 + 웹팩 또는 그냥 웹팩?
사람들이 webpack과 함께 gulp를 사용하는 것을 봅니다. 그러나 나는 웹팩이 꿀꺽 꿀꺽 꿀 수 있다고 읽었습니까? 나는 여기에 완전히 혼란 스럽습니다 ... 누군가가 설명 할 수 있습니까?
최신 정보
결국 나는 꿀꺽 꿀꺽 시작했다. 나는 현대 프론트 엔드를 처음 접했고 빨리 일어 서고 싶었습니다. 1 년이 지난 후 발이 완전히 젖었으므로 이제 웹팩으로 이동할 준비가되었습니다. 같은 신발을 신는 사람들에게 같은 길을 제안합니다. webpack을 시도 할 수는 없지만 gulp로 시작하는 것이 복잡한 것 같다면 말하십시오.
꿀꺽 꿀꺽 마시고 싶지 않다면, 그래도 좋지만 package.json에 명령을 지정하고 작업 러너없이 명령 행에서 명령을 호출하여 처음에 시작하고 실행할 수 있습니다. 예를 들면 다음과 같습니다.
"scripts": {
"babel": "babel src -d build",
"browserify": "browserify build/client/app.js -o dist/client/scripts/app.bundle.js",
"build": "npm run clean && npm run babel && npm run prepare && npm run browserify",
"clean": "rm -rf build && rm -rf dist",
"copy:server": "cp build/server.js dist/server.js",
"copy:index": "cp src/client/index.html dist/client/index.html",
"copy": "npm run copy:server && npm run copy:index",
"prepare": "mkdir -p dist/client/scripts/ && npm run copy",
"start": "node dist/server"
},
이 답변이 도움이 될 수 있습니다. 작업 러너 (Gulp, Grunt 등) 및 Bundler (Webpack, Browserify). 왜 함께 사용합니까?
... 그리고 gulp 작업 내에서 webpack을 사용하는 예가 있습니다. 한 단계 더 나아가 웹팩 구성이 es6로 작성된 것으로 가정합니다.
var gulp = require('gulp');
var webpack = require('webpack');
var gutil = require('gutil');
var babel = require('babel/register');
var config = require(path.join('../..', 'webpack.config.es6.js'));
gulp.task('webpack-es6-test', function(done){
webpack(config).run(onBuild(done));
});
function onBuild(done) {
return function(err, stats) {
if (err) {
gutil.log('Error', err);
if (done) {
done();
}
} else {
Object.keys(stats.compilation.assets).forEach(function(key) {
gutil.log('Webpack: output ', gutil.colors.green(key));
});
gutil.log('Webpack: ', gutil.colors.blue('finished ', stats.compilation.name));
if (done) {
done();
}
}
}
}
앱이 더 복잡 해짐에 따라 위의 예제와 같이 웹팩 작업에 꿀꺽 꿀꺽 사용하는 것이 좋습니다. 이를 통해 빌드에서 웹팩 로더와 플러그인이 실제로하지 않는 몇 가지 흥미로운 작업을 수행 할 수 있습니다. 간결하게, 출력 디렉토리 만들기, 서버 시작 등. 웹팩은 실제로 그러한 작업을 수행 할 수 있지만 장기적인 요구에 따라 제한 될 수 있습니다. gulp-> webpack에서 얻을 수있는 가장 큰 장점 중 하나는 다양한 환경에 맞게 webpack 구성을 사용자 정의하고 gulp가 적시에 올바른 작업을 수행 할 수 있다는 것입니다. 정말 당신에게 달려 있지만, gulp에서 webpack을 실행하는 데 아무런 문제가 없습니다. 실제로 그것을 수행하는 방법에 대한 흥미로운 흥미로운 예가 있습니다.
NPM 스크립트 는 꿀꺽 꿀꺽과 동일하게 수행 할 수 있지만 코드는 약 50 배 줄어 듭니다. 실제로 코드가 전혀 없으면 명령 줄 인수 만 있습니다.
예를 들어, 유스 케이스는 환경마다 다른 코드를 사용하려는 위치를 설명했습니다.
Webpack + NPM 스크립트를 사용하면 다음과 같이 쉽습니다.
"prebuild:dev": "npm run clean:wwwroot",
"build:dev": "cross-env NODE_ENV=development webpack --config config/webpack.development.js --hot --profile --progress --colors --display-cached",
"postbuild:dev": "npm run copy:index.html && npm run rename:index.html",
"prebuild:production": "npm run clean:wwwroot",
"build:production": "cross-env NODE_ENV=production webpack --config config/webpack.production.js --profile --progress --colors --display-cached --bail",
"postbuild:production": "npm run copy:index.html && npm run rename:index.html",
"clean:wwwroot": "rimraf -- wwwroot/*",
"copy:index.html": "ncp wwwroot/index.html Views/Shared",
"rename:index.html": "cd ../PowerShell && elevate.exe -c renamer --find \"index.html\" --replace \"_Layout.cshtml\" \"../MyProject/Views/Shared/*\"",
이제 두 개의 웹팩 구성 스크립트 (개발 모드 용과 webpack.development.js
프로덕션 모드 용) 를 유지 관리하면 됩니다 webpack.production.js
. 또한 webpack.common.js
모든 환경에서 공유되는 webpack 구성을 포함하고 webpackMerge를 사용하여 병합합니다.
NPM 스크립트의 차가움으로 인해 gulp가 스트림 / 파이프와 비슷한 방식으로 체인을 쉽게 연결할 수 있습니다.
위의 예에서 개발을 위해 빌드하려면 명령 행으로 이동하여 실행하십시오 npm run build:dev
.
- NPM 먼저 실행됩니다
prebuild:dev
, - 그런 다음
build:dev
, - 그리고 마지막으로
postbuild:dev
.
pre
및 post
접두사에서 실행되는 순서 NPM을 말한다.
Webpack + NPM 스크립트를 사용하면과 같은 기본 프로그램 rimraf
에 대한 꿀꺽 래퍼 대신와 같은 기본 프로그램을 실행할 수 있습니다 gulp-rimraf
. 여기에서 한 것처럼 기본 Windows .exe 파일을 실행 elevate.exe
하거나 Linux 또는 Mac에서 기본 * nix 파일을 실행할 수도 있습니다.
꿀꺽 꿀꺽 같은 일을 해보십시오. 누군가가 와서 사용하려는 기본 프로그램에 대한 꿀꺽 꿀꺽 래퍼를 작성해야합니다. 또한 다음과 같은 복잡한 코드를 작성해야 할 수도 있습니다. ( 각도 2 종 리포 에서 직접 가져옴 )
펄프 개발 코드
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import * as util from 'gulp-util';
import { join/*, sep, relative*/ } from 'path';
import { APP_DEST, APP_SRC, /*PROJECT_ROOT, */TOOLS_DIR, TYPED_COMPILE_INTERVAL } from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPlugins();
let typedBuildCounter = TYPED_COMPILE_INTERVAL; // Always start with the typed build.
/**
* Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
* environment.
*/
export = () => {
let tsProject: any;
let typings = gulp.src([
'typings/index.d.ts',
TOOLS_DIR + '/manual_typings/**/*.d.ts'
]);
let src = [
join(APP_SRC, '**/*.ts'),
'!' + join(APP_SRC, '**/*.spec.ts'),
'!' + join(APP_SRC, '**/*.e2e-spec.ts')
];
let projectFiles = gulp.src(src);
let result: any;
let isFullCompile = true;
// Only do a typed build every X builds, otherwise do a typeless build to speed things up
if (typedBuildCounter < TYPED_COMPILE_INTERVAL) {
isFullCompile = false;
tsProject = makeTsProject({isolatedModules: true});
projectFiles = projectFiles.pipe(plugins.cached());
util.log('Performing typeless TypeScript compile.');
} else {
tsProject = makeTsProject();
projectFiles = merge(typings, projectFiles);
}
result = projectFiles
.pipe(plugins.plumber())
.pipe(plugins.sourcemaps.init())
.pipe(plugins.typescript(tsProject))
.on('error', () => {
typedBuildCounter = TYPED_COMPILE_INTERVAL;
});
if (isFullCompile) {
typedBuildCounter = 0;
} else {
typedBuildCounter++;
}
return result.js
.pipe(plugins.sourcemaps.write())
// Use for debugging with Webstorm/IntelliJ
// https://github.com/mgechev/angular2-seed/issues/1220
// .pipe(plugins.sourcemaps.write('.', {
// includeContent: false,
// sourceRoot: (file: any) =>
// relative(file.path, PROJECT_ROOT + '/' + APP_SRC).replace(sep, '/') + '/' + APP_SRC
// }))
.pipe(plugins.template(templateLocals()))
.pipe(gulp.dest(APP_DEST));
};
꿀꺽 꿀꺽 생산 코드
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import { join } from 'path';
import { TMP_DIR, TOOLS_DIR } from '../../config';
import { makeTsProject, templateLocals } from '../../utils';
const plugins = <any>gulpLoadPlugins();
const INLINE_OPTIONS = {
base: TMP_DIR,
useRelativePaths: true,
removeLineBreaks: true
};
/**
* Executes the build process, transpiling the TypeScript files for the production environment.
*/
export = () => {
let tsProject = makeTsProject();
let src = [
'typings/index.d.ts',
TOOLS_DIR + '/manual_typings/**/*.d.ts',
join(TMP_DIR, '**/*.ts')
];
let result = gulp.src(src)
.pipe(plugins.plumber())
.pipe(plugins.inlineNg2Template(INLINE_OPTIONS))
.pipe(plugins.typescript(tsProject))
.once('error', function () {
this.once('finish', () => process.exit(1));
});
return result.js
.pipe(plugins.template(templateLocals()))
.pipe(gulp.dest(TMP_DIR));
};
The actual gulp code is much more complicated that this, as this is only 2 of the several dozen gulp files in the repo.
So, which one is easier to you?
In my opinion, NPM scripts far surpasses gulp and grunt, in both effectiveness and ease of use, and all front-end developers should consider using it in their workflow because it is a major time saver.
UPDATE
There is one scenario I've encountered where I wanted to use Gulp in combination with NPM scripts and Webpack.
When I need to do remote debugging on an iPad or Android device for example, I need to start up extra servers. In the past I ran all the servers as separate processes, from within IntelliJ IDEA (Or Webstorm) that is easy with the "Compound" Run Configuration. But if I need to stop and restart them, it was tedious to have to close 5 different server tabs, plus the output was spread across the different windows.
One of the benefits of gulp is that is can chain all the output from separate independent processes into one console window, which becomes the parent of all the child servers.
So I created a very simple gulp task that just runs my NPM scripts or the commands directly, so all the output appears in one window, and I can easily end all 5 servers at once by closing the gulp task window.
Gulp.js
/**
* Gulp / Node utilities
*/
var gulp = require('gulp-help')(require('gulp'));
var utils = require('gulp-util');
var log = utils.log;
var con = utils.colors;
/**
* Basic workflow plugins
*/
var shell = require('gulp-shell'); // run command line from shell
var browserSync = require('browser-sync');
/**
* Performance testing plugins
*/
var ngrok = require('ngrok');
// Variables
var serverToProxy1 = "localhost:5000";
var finalPort1 = 8000;
// When the user enters "gulp" on the command line, the default task will automatically be called. This default task below, will run all other tasks automatically.
// Default task
gulp.task('default', function (cb) {
console.log('Starting dev servers!...');
gulp.start(
'devserver:jit',
'nodemon',
'browsersync',
'ios_webkit_debug_proxy'
'ngrok-url',
// 'vorlon',
// 'remotedebug_ios_webkit_adapter'
);
});
gulp.task('nodemon', shell.task('cd ../backend-nodejs && npm run nodemon'));
gulp.task('devserver:jit', shell.task('npm run devserver:jit'));
gulp.task('ios_webkit_debug_proxy', shell.task('npm run ios-webkit-debug-proxy'));
gulp.task('browsersync', shell.task(`browser-sync start --proxy ${serverToProxy1} --port ${finalPort1} --no-open`));
gulp.task('ngrok-url', function (cb) {
return ngrok.connect(finalPort1, function (err, url) {
site = url;
log(con.cyan('ngrok'), '- serving your site from', con.yellow(site));
cb();
});
});
// gulp.task('vorlon', shell.task('vorlon'));
// gulp.task('remotedebug_ios_webkit_adapter', shell.task('remotedebug_ios_webkit_adapter'));
Still quite a bit of code just to run 5 tasks, in my opinion, but it works for the purpose. One caveate is that gulp-shell
doesn't seem to run some commands correctly, such as ios-webkit-debug-proxy
. So I had to create an NPM Script that just executes the same command, and then it works.
So I primarily use NPM Scripts for all my tasks, but occasionally when I need to run a bunch of servers at once, I'll fire up my Gulp task to help out. Pick the right tool for the right job.
UPDATE 2
I now use a script called concurrently which does the same thing as the gulp task above. It runs multiple CLI scripts in parallel and pipes them all to the same console window, and its very simple to use. Once again, no code required (well, the code is inside the node_module for concurrently, but you don't have to concern yourself with that)
// NOTE: If you need to run a command with spaces in it, you need to use
// double quotes, and they must be escaped (at least on windows).
// It doesn't seem to work with single quotes.
"run:all": "concurrently \"npm run devserver\" nodemon browsersync ios_webkit_debug_proxy ngrok-url"
This runs all 5 scripts in parallel piped out to one terminal. Awesome! So that this point, I rarely use gulp, since there are so many cli scripts to do the same tasks with no code.
I suggest you read these articles which compare them in depth.
- How to Use NPM as a Build Tool
- Why we should stop using Grunt & Gulp
- Why I Left Gulp and Grunt for NPM Scripts
I used both options in my different projects.
Here is one boilerplate that I put together using gulp
with webpack
- https://github.com/iroy2000/react-reflux-boilerplate-with-webpack.
I have some other project used only webpack
with npm tasks
.
And they both works totally fine. And I think it burns down to is how complicated your task is, and how much control you want to have in your configuration.
For example, if you tasks is simple, let's say dev
, build
, test
... etc ( which is very standard ), you are totally fine with just simple webpack
with npm tasks
.
But if you have very complicated workflow and you want to have more control of your configuration ( because it is coding ), you could go for gulp route.
But from my experience, webpack ecosystem provides more than enough plugins and loaders that I will need, and so I love using the bare minimum approach unless there is something you can only do in gulp. And also, it will make your configuration easier if you have one less thing in your system.
And a lot of times, nowadays, I see people actually replacing gulp and browsify
all together with webpack
alone.
Honestly I think the best is to use both.
- Webpack for all javascript related.
- Gulp for all css related.
I still have to find a decent solution for packaging css with webpack, and so far I am happy using gulp for css and webpack for javascript.
I also use npm
scripts as @Tetradev as described. Expecially since I am using Visual Studio
, and while NPM Task runner
is pretty reliable Webpack Task Runner
is pretty buggy.
The concepts of Gulp and Webpack are quite different. You tell Gulp how to put front-end code together step-by-step, but you tell Webpack what you want through a config file.
Here is a short article (5 min read) I wrote explaining my understanding of the differences: https://medium.com/@Maokai/compile-the-front-end-from-gulp-to-webpack-c45671ad87fe
Our company moved from Gulp to Webpack in the past year. Although it took some time, we figured out how to move all we did in Gulp to Webpack. So to us, everything we did in Gulp we can also do through Webpack, but not the other way around.
As of today, I'd suggest just use Webpack and avoid the mixture of Gulp and Webpack so you and your team do not need to learn and maintain both, especially because they are requiring very different mindsets.
참고URL : https://stackoverflow.com/questions/33558396/gulp-webpack-or-just-webpack
'IT' 카테고리의 다른 글
Jelly Bean DatePickerDialog — 취소 할 수있는 방법이 있습니까? (0) | 2020.06.14 |
---|---|
Windows에서 가장 빠른 화면 캡처 방법 (0) | 2020.06.14 |
C 런타임 라이브러리 란 무엇입니까? (0) | 2020.06.14 |
Double.MIN_VALUE가 음수가 아닌 이유 (0) | 2020.06.14 |
당김 용 후크가 있습니까? (0) | 2020.06.14 |