从Gulp切换到Webpack

15

更新于2020年4月30日

[从Webpack迁移]

我的第一个问题是,对于简单的项目,仅为了预处理 /合并/缩小,建议使用此转换吗?

理解未来的“标准”,例如Webpack与PostCss-NextCss-Autoprefixer一起使用等等,就像使我着迷....

这引出了我的下一个问题,是否有任何教程可以指导像我在第一个问题中描述的简单任务?

或者有没有简单的方法将我的gulpfile.js更改为webpack-config.js

我的gulp中的常规任务不是最佳实践,但效果很好:

//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'])
});

我开始使用postcss来改进我的工作流程。有关此事,您有何看法?如何正确地入手?

编辑 // 2017年6月28日

到这个日期为止,我们在Webpack 1上的进展非常令人满意和成功,我们的工作流程要快得多,我们对该工具的依赖是不可改变的。

这是我们每天使用的webpack.config.js

"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;

然而时代已经改变,现在是升级到Webpack 3 的时候了。我们正在进行将webpack.config.js文件升级到版本3的工作。

5个回答

8
对于简单项目,我不建议使用切换。最终,我认为这是个人口味问题,我更喜欢通过易于理解的javascript(gulp)进行后处理。
正如你在问题中所说,你目前的设置运行良好:那么为什么要修复没有问题的东西呢?我会专注于重构你的gulp代码,使其更易读,将长函数拆分成较小的gulp任务。
最终,使用webpack需要学习许多特定的webpack相关配置选项,而使用gulp,你主要只需管道传输基本js命令。

3
谢谢您的观点,但我必须说我们在Webpack中的工作流程比在Gulp中更快。 - Locke
2
好的,感谢您更新答案并提供webpack配置! - Oli
Gulp已经超过3年没有更新了,因此远离它可能更为重要。 - DrCord
1
是的,这是那种现在完全过时的答案之一。有趣的是,现在 Vite 是城里新热门的构建工具。这只是无休止的工具重组。 - Oli
是的,Gulp现已被弃用,在最新的操作系统上也不受支持。 - Sflagg

8
好的,我正在通过这篇教程获得一些很好的成就。
我的第一个尝试是这样的:

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,
];

这会成功生成一个 bundle--script.js 文件,但是我在处理 CSS 部分时遇到了一些问题。
它不会预处理任何内容 :/
如果我在此期间解决了这个问题,我会在这里更新。如果有人能够指导我,我将非常感激。

1
Gulp和Webpack的概念相当不同:你通过逐步告诉Gulp如何组合前端代码,但是你通过配置文件告诉Webpack你想要什么。因此,如果你要切换,就没有简单的一对一映射关系。
我们公司在过去一年里从Gulp转向Webpack。我发现了解这两个工具的差异对于过渡非常有帮助。这是我写的一个简短的文章(阅读时间5分钟),解释了思维方式的变化: https://medium.com/@Maokai/compile-the-front-end-from-gulp-to-webpack-c45671ad87fe 尽管我们的转换花费了一些时间,但我们找到了如何将我们在Gulp中所做的所有事情转移到Webpack中。因此,对于我们来说,我们在Gulp中所做的一切也可以通过Webpack完成,但反过来则不行。

0

这取决于问题的答案:您是否认为将CSS作为webpack捆绑包的一部分加载有任何优势。如果您要使用<link>将CSS加载到浏览器中,那么webpack可能不会带来任何优势。

除了“拥有一个工具”之外。但不是一个配置 - 不要忘记您仍然需要特定的webpack配置,仅将CSS编译为开发加速(编译JS非常缓慢),并且很难实现(当您仅编译CSS时,当前webpack 4存在一些副作用)。


0

我认为你现在不需要使用postcss loader。我的意思是,暂时不需要。你只是从一个工具转移到另一个工具,所以应该尽可能保持简洁。

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

请注意,我的代码中的include取决于您的配置。之后,我会考虑摆脱gulp中的“相对”路径。如果您想要维护开发生产环境,这可能会破坏您的东西。这只是个人经验。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接