Switching from Gulp to Webpack

人盡茶涼 提交于 2019-11-29 11:45:46

问题


My first question is about how recommended is this switch for simple projects, just to Pre-Process/Concat/Minify?

Understanding this future "standards", like Webpack in together with PostCss-NextCss-Autoprefixer, etc. is like obsessing me....

So this leads to my next question , is there any tutorial that will guide to simple tasks like the one I told in my first question?

Or is an easy way to change my gulpfile.js to a webpack-config.js

My normal tasks in gulp are not the best practices but work well :

//load plugins
var gulp    = require('gulp'),
runSequence = require('run-sequence'),
sass        = require('gulp-ruby-sass'),
compass     = require('gulp-compass'),
rev         = require('gulp-rev'),
revDel      = require('rev-del'),
del         = require('del'),
minifycss   = require('gulp-minify-css'),
uglify      = require('gulp-uglify'),
rename      = require('gulp-rename'),
concat      = require('gulp-concat'),
notify      = require('gulp-notify'),
plumber     = require('gulp-plumber'),
watch       = require('gulp-watch'),
path        = require('path');


  //the title and icon that will be used for the Grunt notifications
  var notifyInfo = {
    title: 'Gulp',
    icon: path.join(__dirname, 'gulp.png')
  };

  //error notification settings for plumber
  var plumberErrorHandler = { errorHandler: notify.onError({
    title: notifyInfo.title,
    icon: notifyInfo.icon,
    message: "Error: <%= error.message %>"
  })
};

//patches
var paths = {
  scriptsAbs : '_coffeescript/',
  stylesAbs: '_scss/',
  scriptsCom : '_coffeescript/' + '**/*.js',
  stylesCom :'_scss/' + '**/*.scss',
  cssCom : 'resources/css',
  jsCom : 'resources/js',
  imgCom : 'resources/img'
};

gulp.task('clean',
  function (cb) {
    del([
      paths.cssCom + '/*',
      paths.jsCom + '/*'
      ], cb);
  });

//styles
gulp.task('styles',
  function() {
    return gulp.src(paths.stylesCom)
    .pipe(plumber(plumberErrorHandler))
    .pipe(compass({
      sass: '_scss',
      css: paths.cssCom,
      image: paths.imgCom,
      style: 'expanded',
      relative: true,
      require: ['normalize-scss', 'susy']
    }))
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rev())
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rev.manifest())
    .pipe(revDel({ dest: paths.cssCom }))
    .pipe(gulp.dest(paths.cssCom))
    .pipe(notify({ message: 'Styles task completed' }))
  });

//scripts
gulp.task('scripts',
  function() {
    return gulp.src(paths.scriptsCom)
    .pipe(plumber(plumberErrorHandler))
    .pipe(concat('main.js'))
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rev())
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rev.manifest())
    .pipe(revDel({ dest: paths.jsCom }))
    .pipe(gulp.dest(paths.jsCom))
    .pipe(notify({ message: 'Scripts Concatenated completed' }))
  // .pipe(reload({stream:true}));

});


gulp.task('default', ['clean','styles','scripts'], function(){
  gulp.watch(paths.stylesCom, ['styles'])
  gulp.watch(paths.scriptsCom, ['scripts'])

//watch .php files
// gulp.watch(['*.php'], ['bs-reload'])
});

And I'm starting to use postcss that is making my workflow, mm, better..easier sometimes.

What are your opinions on all this? Where is the right path to start?

EDIT // JUNE 28, 2017

At this date our progress with Webpack 1 were super satisfactory and successfully , our workflow is pretty much faster and our dependence in this tool is Unchangeable.

This is the webpack.config.js that we use every day:

"use strict";

var webpack = require('webpack');
var glob = require('glob-all');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');

let start = {

    entry: {
        scripts: glob.sync(
            [
            './_javascript/*.js',
            './_cssnext/*.pcss'
            ]
        )},

    output: {
        path: './resources/js',
        filename: 'bundle--[name].js'
    },
    watchOptions: {
        poll: true
    },

    postcss: function (webpack) {
        return [
            require("postcss-import")({addDependencyTo: webpack}),
            require("postcss-url")(),
            require("precss")(),
            require("postcss-cssnext")(),
            require('postcss-font-magician')(),
            require("postcss-reporter")(),
            require("postcss-browser-reporter")(),
            require('postcss-inline-svg')(),
            require('postcss-urlrev')(),
            require('postcss-fontpath')(),
            require('postcss-object-fit-images')()
        ]
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            },
            {
                test: /\.p?css$/,
                loader: ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader!postcss-loader'
                )
            }
        ]
    },


    plugins: [
        new webpack.optimize.CommonsChunkPlugin({name: 'scripts', filename: 'bundle--[name].js'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new ExtractTextPlugin("../css/bundle--styles.css"),
        new BrowserSyncPlugin({
            host: 'localhost',
            port: 3000,
            proxy: 'localhost:8002',
            browser: 'google chrome',
            ghostMode: false
        })
    ]

};

module.exports = start;

But times has change and is time to evolve to Webpack 3 , and now we are in the progress to change this webpack.config.jsto the version 3

UPDATE 24.07.17 || v1 (Tryout 10000.1)

[ Move from Webpack 1 to Webpack 2/3 ]


回答1:


Ok , I'm getting some great achieves thanks to this tutroial : https://www.phase2technology.com/blog/bundle-your-front-end-with-webpack/

My first approach is this:

webpack-config.js

'use strict';

const webpack    = require('webpack'),
    path         = require('path'),
    autoprefixer = require('autoprefixer'),
    glob         = require('glob');

let script = {
    entry: {
         'scripts': glob.sync('./_javascript/*.js'),
    },
    module: {
        loaders: [
            // Javascript: js, jsx
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            },
            // CSS: scss, css
            {
                test: /\.s?css$/,
                loaders: ['style', 'css', 'sass', 'postcss-loader']
            },
            // SVGs: svg, svg?something
            {
                test: /\.svg(\?.*$|$)/,
                loader: 'file-loader?name=/img/[name].[ext]'
            },
            // Images: png, gif, jpg, jpeg
            {
                test: /\.(png|gif|jpe?g)$/,
                loader: 'file?name=/img/[name].[ext]'
            },
            // HTML: htm, html
            {
                test: /\.html?$/,
                loader: "file?name=[name].[ext]"
            },
            // Font files: eot, ttf, woff, woff2
            {
                test: /\.(eot|ttf|woff2?)(\?.*$|$)/,
                loader: 'file?name=/fonts/[name].[ext]'
            }
        ]
    },
    output: {
        path: './resources/js',
        filename: 'bundle--[name].js'
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin(['scripts'], 'bundle--[name].js'),
        new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
    }
})
]
};

let style = {
    entry: {
        'styles': glob.sync('./_nextcss/*.css'),
    },
    module: {
        loaders: [
            {
                test: /\.s?css$/,
                loaders: ['style', 'css', 'sass', 'postcss-loader']
            },
        ]
    },
    postcss: function (webpack) {
        return [
            require("postcss-import")({
                addDependencyTo: webpack
            }),
            require("postcss-url")(),
            require("postcss-cssnext")(),
            require("postcss-browser-reporter")(),
            require("postcss-reporter")(),
        ]
    },
    output: {
        path: './resources/css',
        filename: 'bundle--[name].css'
    },
};

module.exports = [
    script,
    style,
];

This generates a bundle--script.js successfully , but I'm having some issues with the css part.

It won't pre-process anything :/

I will be updating here if I get to work this in the meantime, I will really appreciate much, if someone can guide me.




回答2:


For simple projects, I would not recommend the switch at all. In the end it's a personal taste I think, and I prefer postprocessing through easily understandable javascript (gulp).

As you've said in your question, your current setup works well: so why fix something that's not broken? I'd focus on refactoring your gulp code to make it a bit more readable, split the long functions into smaller gulp tasks.

In the end, using webpack requires learning a lot of specific webpack related config options, while with gulp you're mostly just piping vanilla js commands.




回答3:


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. So there is no easy one-to-one mapping if you are switching.

Our company moved from Gulp to Webpack in the past year. I found that understanding the differences of the two tools are very helpful for the transition. Here is a short article (5 min read) I wrote explaining the mindset change: https://medium.com/@Maokai/compile-the-front-end-from-gulp-to-webpack-c45671ad87fe

Although our transition 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.




回答4:


I don't think you'd need postcss loader. I mean, for the time being. You are just moving from one to tool to another, so you should just keeping as lean as possible.

{ 
  test: /(\.css|\.scss)$/, 
  include: path.join(__dirname, 'src'), 
  loaders: ['style-loader', 'css-loader', 'sass-loader'] 
}

Mind that include inside my code depends on your configuration. After that I would consider to get rid of the 'relative' path you have in gulp. It could break your things if you'd want to maintain a development and production environment. Just personal experience.




回答5:


It depends on the answer to the question: do you see any advantage to load css as part of webpack bundle or not. If you are going to load css to the browser with <link> then probably webpack doesn't bring you any advantage.

Except of "having one tool". But not one configuration - do not forget that you still need specific webpack configuration that compiles only css to speadup development (compile js is significantly slow) and it is not so easy to achieve (there are some side effects with current webpack 4 when you compile only css).



来源:https://stackoverflow.com/questions/39753642/switching-from-gulp-to-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!