I've been using gulp for a while now and know how to import another node module, e.g.
var sass = require('gulp-sass');
That's fine, but my gulpfile is filling up with code that I'd like to move into a separate file and "require". Specifically I am writing a postcss plugin, which I already have working when declared as a function inside of the gulpfile. My question is how to put my function in an external file and require it like I do a node module. Do I need to "export" the function in the file being required? Do I need to use ES6 modules or something like that?
As an aside, I realise that if i was doing this probably I would either (A) turn this into a proper node module and put it on a private NPM repository, but that seems unnecessary, or (B) turn it into a proper gulp plugin, but that would require learning how to author a gulp plugin and learning about streams and stuff. Both of these are probably better but would take more time so I've decided to just keep the function simple and local for now.
First, you have to add
export default <nameOfYourFile>
at the end of your fileThen to use it, write
import gulp from 'gulp'
If you have an error message, install
babel-core
andbabel-preset-es2015
with NPM, and add a preset"presets": ["es2015"]
in your.babelrc
config file.I fix my problem by install:
npm i babel-plugin-add-module-exports
Then i add "plugins": [["add-module-exports"]] to the .babelrc
First create a new js file (here
./lib/myModule.js
):You could also pass some arguments to your module:
Then require it in your gulpfile: