WebPack在构建开始之前执行功能 [英] WebPack execute function before build starts

查看:106
本文介绍了WebPack在构建开始之前执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Webpack开始其构建过程之前,我需要执行一个JavaScript函数.该函数只需要 .scss 文件并将它们连接成一个文件.

I need to execute one JavaScript function before the Webpack starts its building process. The function just takes .scss files and concatenate them into one.

之后,Webpack应该获取结果文件.有没有这样做的选择?

After that Webpack should take the result file. Is there an option to do that?

此刻,我在 webpack.config.js 中的 module.exports 之前运行了该函数,但似乎它不是同步操作.Module.exports在 concat()函数结束并且Webpack找不到.scss文件之前执行.

At the moment I run the function before the module.exports in webpack.config.js, but it seems that its not synchronous operation. Module.exports execute before the concat() function ends and Webpack can't find .scss file.

function concat(opts) {
  (...)
}

concat({ src : styles,  dest : './css/style.scss' });

module.exports = [
   (...)
] 

推荐答案

在运行Webpack之前concat scss文件似乎有些奇怪,因为这类操作通常是由Webpack本身处理的.

It seems a little bit odd to concat scss files before running Webpack as those kind of operations are usually handled by Webpack itself.

话虽如此,有几种解决方法.

That being said, there's a few way of solving this.

最明显的方法是将 concat 部分提取到一个单独的文件(例如 prepare.js )中,然后通过在此过程中运行某些东西来启动构建过程行: node prepare.js&&webpack .这将首先运行prepare,并且如果退出时没有错误,则将运行webpack.通常会将其添加到package.json的 scripts 部分,例如

The most obvious way would be to extract the concat parts to a separate file (e.g. prepare.js) and then run start the build process by running something along this line: node prepare.js && webpack. That'll first run prepare and if that exits without error webpack will be run. Usually that'll be added to the scripts part of your package.json, e.g.

"scripts": {
  "build": "node prepare.js && webpack"
}

要实现相同的目的,但要以更完整的Webpack集成方式,您可以做同样的事情,将 concat 部分提取到一个单独的文件中,然后让Webpack在构建开始之前执行该文件,方法如下: Webpack Shell插件的帮助,例如

To achieve the same but in a more Webpack integrated way you could do the same thing where you extract the concat part to a separate file and then let Webpack execute that file, before build starts, with the help of Webpack Shell Plugin, e.g.

const WebpackShellPlugin = require('webpack-shell-plugin');
module.exports = {
  ...
  plugins: [
    new WebpackShellPlugin({
      onBuildStart:['node prepare.js']
    })
  ],
  ...
}

这篇关于WebPack在构建开始之前执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆