Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run arbitrary bash scripts on files via Webpack without maintaining loaders for each file type?

It seems like Webpack runs tools that transform code via "loaders", rather than using the APIs of those tools directly. This adds a layer of abstraction over those tools which sometimes means the APIs of the tools is not fully exposed or updates to the tools take time to be updated in the loader. Here's a more detailed description of the problem.

I ran into this problem with Grunt/gulp, and ended up abandoning those in favor of transforming my source directly with bash scripts that I run via npm. Is it possible to do the same thing with Webpack? If so, how?

like image 773
Jo Sprague Avatar asked Sep 02 '17 22:09

Jo Sprague


People also ask

Why do we need to use a loader when using a webpack?

Webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node. js.

What does webpack file-loader do?

Webpack file-loader is a loader used mainly for supporting images such as SVG and PNG, and fonts in your webpack project. If your images are not loading in your webpack app then you probably miss the configuration of file-loader.

What loaders need to be used in webpack config JS for the code below to work?

In the webpack. config. js, add a rule to use 'css-loader' and 'style-loader' for .

How do you make a webpack loader?

To build any loader in webpack, you need to: Transform the source file's contents into a javascript value, probably a string. Transform parts of the content that are references into requests for other needed files, like images. Export the built value as JavaScript so that other parts of your application can use it.


1 Answers

I created a custom Webpack loader called shell-loader that takes an arbitrary shell script and runs it on the content of each file that it loads using child_process.exec. I can use it like this in webpack.config.js;

{
  test: /.*\.css$/,
  use: [ 'css-loader', { loader: 'shell-loader', options: {
    script: 'postcss --use autoprefixer'
  }} ]
}

It seems to work, as a proof of concept, but I'm not sure if this is a good idea when working with Webpack, or if I'm hacking things together that they weren't meant to be.

like image 130
Jo Sprague Avatar answered Oct 05 '22 22:10

Jo Sprague