Rafael Milewski Rafael Milewski - 15 days ago 5
Node.js Question

How to keep my shebang in place using webpack?

is there any way to make Webpack keep the

#!/usr/bin/env node
at the top of my file?

I'm trying to bundle a CLI along with a module... it was a bit tricky to export my
index.js / cli.js
separately using just one configuration file... and making the cli require index... i got it working...

However.. i didn't find any way to keep the
#!/usr/bin/env node
at the top of my cli file, any ideas?

in shorts webpack outputs an file like this:

/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};

/******/ // The require function
/******/ function __webpack_require__(moduleId) {

/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
..............................................................


but what i need is

#!/usr/bin/env node //<------ HEREEEE

/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};

/******/ // The require function
/******/ function __webpack_require__(moduleId) {

/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;

..............................................................

Answer

You should be able to use BannerPlugin with raw mode for this. With this plugin you can add any string you want at the top of your bundle. By using the raw mode, it will not wrap the string in a comment.

In your webpack.config.js file:

plugins: [
    new webpack.BannerPlugin('#!/usr/bin/env node', { raw: true });
]