How to import all tasks from another gulp file.js - javascript

Is it possible to have one main gulpfile.js from which to call tasks from other gulp files.js? Simple "require" of child gulpfile.js into main one doesn't work.
I have a platform project which includes several sub projects with separate gulpfiles, so I need a solution to manage all child gulpfiles from within main one

It is possible to have one main gulpfile.js from which to call tasks from other gulp files.js using the require-dir module. From the projects README use it like this:
Split tasks across multiple files
If your gulpfile.js is starting to grow too large, you can split the tasks
into separate files by using the require-dir
module.
Imagine the following file structure:
gulpfile.js
tasks/
├── dev.js
├── release.js
└── test.js
Install the require-dir module:
npm install --save-dev require-dir
Add the following lines to your gulpfile.js file.
var requireDir = require('require-dir');
var dir = requireDir('./tasks');

I've create a special gulp-require-tasks module that will help you to split your gulpfile.js into separate smaller task files. Please see the README for example and documentation.
Please consider using it and let me know if it works for you! If you have any suggestions or ideas for improvement, I will gladly accept them.

And what if I want to make it future-proof and don't want to install
another package for it.
The following works for me with gulp 4, without any extra plugins.
In taskfile.js:
const { src, dest } = require('gulp');
const mytask = function () {
return src('assets/**/*')
.pipe(dosomething())
.pipe(dest('dest');
}
module.exports = {
mytask
}
In gulpfile.js:
const { mytask } = require('taskfile.js');
// use in other tasks
gulp.task('manythings', gulp.series(..., mytask, ...));
// or use directly as 'gulp mytask'
module.exports = {
mytask
}

I would recommend this answer for anyone who doesn't want to include a separate module or refactoring:
https://stackoverflow.com/a/5809968/40769
var fs = require('fs');
// file is included here:
eval(fs.readFileSync('tools.js')+'');

Related

The create-react-app imports restriction outside of src directory

I am using create-react-app. I am trying to call an image from my public folder from a file inside my src/components. I am receiving this error message.
./src/components/website_index.js Module not found: You attempted to
import ../../public/images/logo/WC-BlackonWhite.jpg which falls
outside of the project src/ directory. Relative imports outside of
src/ are not supported. You can either move it inside src/, or add a
symlink to it from project's node_modules/.
import logo from '../../public/images/logo_2016.png';
<img className="Header-logo" src={logo} alt="Logo" />
I have read many things saying you can do an import to the path but that is still not working for me. Any help would be greatly appreciated. I know there are many questions like this but they are all telling me to import logo or image so clearly I am missing something in the big picture.
This is special restriction added by developers of create-react-app. It is implemented in ModuleScopePlugin to ensure files reside in src/. That plugin ensures that relative imports from app's source directory don't reach outside of it.
There is no official way to disable this feature except using eject and modify webpack config.
But, most features and its updates are hidden into the internals of create-react-app system. If you make eject you will have no more new features and its update. So if you are not ready to manage and configure application included to configure webpack and so on - do not do eject operation.
Play by the existing rules - move assets to src or use based on public folder url without import.
However instead of eject there are much unofficial solutions, based on
rewire which allows you to programmatically modify the webpack config without eject. But removing the ModuleScopePlugin plugin is not good - this loses some protection and does not adds some features available in src. ModuleScopePlugin is designed to support multiple folders.
The better way is to add fully working additional directories similar to src also protected by ModuleScopePlugin. This can be done using react-app-alias
Anyway do not import from public folder - that will be duplicated in the build folder and will be available by two different url (and with different ways to load), which ultimately worsen the package download size.
Importing from the src folder is preferable and has advantages. Everything will be packed by webpack to the bundle with chunks optimal size and for best loading efficiency.
The package react-app-rewired can be used to remove the plugin. This way you do not have to eject.
Follow the steps on the npm package page (install the package and flip the calls in the package.json file) and use a config-overrides.js file similar to this one:
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
module.exports = function override(config, env) {
config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));
return config;
};
This will remove the ModuleScopePlugin from the used WebPack plugins, but leave the rest as it was and removes the necessity to eject.
Remove it using Craco:
module.exports = {
webpack: {
configure: webpackConfig => {
const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
({ constructor }) => constructor && constructor.name === 'ModuleScopePlugin'
);
webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
return webpackConfig;
}
}
};
If your images are in the public folder then you should use
"/images/logo_2016.png"
in your <img> src instead of importing
'../../public/images/logo_2016.png';
This will work
<img className="Header-logo" src="/images/logo_2016.png" alt="Logo" />
To offer a little bit more information to other's answers. You have two options regarding how to deliver the .png file to the user. The file structure should conform to the method you choose. The two options are:
Use the module system (import x from y) provided with react-create-app and bundle it with your JS. Place the image inside the src folder.
Serve it from the public folder and let Node serve the file. create-react-app also apparently comes with an environment variable e.g. <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;. This means you can reference it in your React app but still have it served through Node, with your browser asking for it separately in a normal GET request.
Source: create-react-app
There are a few answers that provide solutions with react-app-rewired, but customize-cra includes a removeModuleScopePlugin() API which is a bit more elegant. (It's the same solution, but abstracted away by the customize-cra package.)
npm i --save-dev react-app-rewired customize-cra
package.json
"scripts": {
- "start": "react-scripts start"
+ "start": "react-app-rewired start",
...
},
config-overrides.js
const { removeModuleScopePlugin } = require('customize-cra')
module.exports = removeModuleScopePlugin()
I was able to import files outside of src/ by "copying" the outside files with file: as local dependency.
"dependencies": {
"#my-project/outside-dist": "file:./../../../../dist".
}
then
import {FooComponent} from "#my-project/outside-dist/components";
No eject or react-app-rewired or other 3rd-party solution was needed.
You need to move WC-BlackonWhite.jpg into your src directory. The public directory is for static files that's going to be linked directly in the HTML (such as the favicon), not stuff that you're going to import directly into your bundle.
install these two packages
npm i --save-dev react-app-rewired customize-cra
package.json
"scripts": {
- "start": "react-scripts start"
+ "start": "react-app-rewired start"
},
config-overrides.js
const { removeModuleScopePlugin } = require('customize-cra');
module.exports = function override(config, env) {
if (!config.plugins) {
config.plugins = [];
}
removeModuleScopePlugin()(config);
return config;
};
I think Lukas Bach solution to use react-app-rewired in order to modify webpack config is a good way to go, however, I wouldn't exclude the whole ModuleScopePlugin but instead whitelist the specific file that can be imported outside of src:
config-overrides.js
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");
module.exports = function override(config) {
config.resolve.plugins.forEach(plugin => {
if (plugin instanceof ModuleScopePlugin) {
plugin.allowedFiles.add(path.resolve("./config.json"));
}
});
return config;
};
Copy-Paste Typescript solution
(e.g. this will work for a CRA/TS stack, which requires an additional step compared to CRA/JS. The solution itself is not typed.)
Adds the required paths to the ModuleScopePlugin instead of bluntly removing the plugin.
This code below is using craco, but should be easily usable for react-app-rewired or similar solutions. You just need to find the spot where you have a webpackConfig object (react-app-rewired: module.exports.webpack inside your config-overrides.js), and pass it to the provided functions.
craco.config.js
const path = require("path");
const enableImportsFromExternalPaths = require("./src/helpers/craco/enableImportsFromExternalPaths");
// Paths to the code you want to use
const sharedLibOne = path.resolve(__dirname, "../shared-lib-1/src");
const sharedLibTwo = path.resolve(__dirname, "../shared-lib-2/src");
module.exports = {
plugins: [
{
plugin: {
overrideWebpackConfig: ({ webpackConfig }) => {
enableImportsFromExternalPaths(webpackConfig, [
// Add the paths here
sharedLibOne,
sharedLibTwo,
]);
return webpackConfig;
},
},
},
],
};
helpers/craco/enableImportsFromExternalPaths.js
const findWebpackPlugin = (webpackConfig, pluginName) =>
webpackConfig.resolve.plugins.find(
({ constructor }) => constructor && constructor.name === pluginName
);
const enableTypescriptImportsFromExternalPaths = (
webpackConfig,
newIncludePaths
) => {
const oneOfRule = webpackConfig.module.rules.find((rule) => rule.oneOf);
if (oneOfRule) {
const tsxRule = oneOfRule.oneOf.find(
(rule) => rule.test && rule.test.toString().includes("tsx")
);
if (tsxRule) {
tsxRule.include = Array.isArray(tsxRule.include)
? [...tsxRule.include, ...newIncludePaths]
: [tsxRule.include, ...newIncludePaths];
}
}
};
const addPathsToModuleScopePlugin = (webpackConfig, paths) => {
const moduleScopePlugin = findWebpackPlugin(
webpackConfig,
"ModuleScopePlugin"
);
if (!moduleScopePlugin) {
throw new Error(
`Expected to find plugin "ModuleScopePlugin", but didn't.`
);
}
moduleScopePlugin.appSrcs = [...moduleScopePlugin.appSrcs, ...paths];
};
const enableImportsFromExternalPaths = (webpackConfig, paths) => {
enableTypescriptImportsFromExternalPaths(webpackConfig, paths);
addPathsToModuleScopePlugin(webpackConfig, paths);
};
module.exports = enableImportsFromExternalPaths;
Taken from here and here 🙏
Image inside public folder
use image inside html extension
<img src="%PUBLIC_URL%/resumepic.png"/>
use image inside js extension
<img src={process.env.PUBLIC_URL+"/resumepic.png"}/>
use image inside js Extension
This restriction makes sure all files or modules (exports) are inside src/ directory, the implementation is in ./node_modules/react-dev-utils/ModuleScopePlugin.js, in following lines of code.
// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
const relative = path.relative(appSrc, request.context.issuer);
// If it's not in src/ or a subdirectory, not our request!
if (relative.startsWith('../') || relative.startsWith('..\\')) {
return callback();
}
You can remove this restriction by
either changing this piece of code (not recommended)
or do eject then remove ModuleScopePlugin.js from the directory.
or comment/remove const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); from ./node_modules/react-scripts/config/webpack.config.dev.js
PS: beware of the consequences of eject.
Adding to Bartek Maciejiczek's answer, this is how it looks with Craco:
const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
const path = require("path");
module.exports = {
webpack: {
configure: webpackConfig => {
webpackConfig.resolve.plugins.forEach(plugin => {
if (plugin instanceof ModuleScopePlugin) {
plugin.allowedFiles.add(path.resolve("./config.json"));
}
});
return webpackConfig;
}
}
};
My previous workaround worked with Webpack 4, but not with 5. After skimming through the accumulated workarounds since then, I found the following one really easy (and seemingly scalable).
import { CracoAliasPlugin } from 'react-app-alias';
const cracoConfig = {
plugins: [
{
plugin: CracoAliasPlugin,
options: {
alias: { '~': './' },
},
},
],
}
Then import like so:
import whatever from '~/<path-to-file>';
I have had to overcome this same issue in Truffle. The solution was as follows:
ince Create-React-App's default behavior disallows importing files from outside of the src folder, we need to bring the contracts in our build folder inside src. We can copy and paste them every time we compile our contracts, but a better way is to simply configure Truffle to put the files there.
In the truffle-config.js file, replace the contents with the following:
const path = require("path");
module.exports = {
contracts_build_directory: path.join(__dirname, "client/src/contracts")
};
I don't know if this helps you, but I know I found your question when I had the same issue in Truffle, and this might help someone else.
This can be done directly without using the path to the public folder.
You can do it like
<img src="/images/image-name" alt=""/>
This happens because we do not use App.js in the browser. Since index.html is executed in the browser itself and the path to images is already in the public folder containing index.html file
You don't need to eject, you can modify the react-scripts config with the rescripts library
This would work then:
module.exports = config => {
const scopePluginIndex = config.resolve.plugins.findIndex(
({ constructor }) => constructor && constructor.name === "ModuleScopePlugin"
);
config.resolve.plugins.splice(scopePluginIndex, 1);
return config;
};
Came to the same issue in my project, and found this in the official create-react-app docs: https://create-react-app.dev/docs/using-the-public-folder/
There is an "escape hatch" to add an asset outside the module system:
If you put a file into the public folder, it will not be processed by
webpack. Instead it will be copied into the build folder untouched. To
reference assets in the public folder, you need to use an environment
variable called PUBLIC_URL.
Here's an example they provide:
render() {
// Note: this is an escape hatch and should be used sparingly!
// Normally we recommend using `import` for getting asset URLs
// as described in “Adding Images and Fonts” above this section.
return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
This worked for me without installing/ changing anything
Context: I got this error when I tried to generate a build using yarn run build
Things I have done between the working and failing of yarn run build
I updated my ant-design to the latest stable version (v4.23.5).
Note: I highly believe that there is nothing to do with this version. I am just mentioning it to add more details.
This answer solved my issue. But I have changed no imports that access something outside the src directory.
The changes include updated package.json, yarn.lock, new Antd implementations (change in props mainly).
It made no sense why the build command broke/ why the answer is working.
Solution here
As all the changes are related to package.json, yarn.lock. I deleted node_modules and clean installed all the packages.
Run
yarn
or
npm install
If you only need to import a single file, such as README.md or package.json, then this can be explicitly added to ModuleScopePlugin()
config/paths.js
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
module.exports = {
appPackageJson: resolveApp('package.json'),
appReadmeMD: resolveApp('README.md'),
};
config/webpack.config.dev.js + config/webpack.config.prod.js
module.exports = {
resolve: {
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [
paths.appPackageJson,
paths.appReadmeMD // README.md lives outside of ./src/ so needs to be explicitly included in ModuleScopePlugin()
]),
]
}
}
the best solution is to fork react-scripts, this is actually mentioned in the official documentation, see: Alternatives to Ejecting
If you need multiple modifications, like when using ant design, you can combine multiple functions like this:
const {
override,
removeModuleScopePlugin,
fixBabelImports,
} = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
removeModuleScopePlugin(),
);
You can try using simlinks, but in reverse.
React won't follow simlinks, but you can move something to the source directory, and create a simlink to it.
In the root of my project, I had a node server directory that had several schema files in it. I wanted to use them on the frontend, so I:
moved the files /src
in the termal, I cd'ed into where the schema files belonged in server
ln -s SRC_PATH_OF_SCHEMA_FILE
This gave react what it was looking for, and node was perfectly happy including files through simlinks.
If you want to access CSS files from the public, you might face an error OUTSIDE OF SOURCE DIRECTORY
Alternatively, you can link this file in index.html which also resides in the public directory.
<link rel="stylesheet" href="App.css">
Here's an alternative that works well in simple cases (using fs and ncp). While developing, keep a script running that watches for changes to your shared folder(s) outside of /src. When changes are made, the script can automatically copy the shared folder(s) to your project. Here's an example that watches a single directory recursively:
// This should be run from the root of your project
const fs = require('fs')
const ncp = require('ncp').ncp;
ncp.limit = 16
// Watch for file changes to your shared directory outside of /src
fs.watch('../shared', { recursive: true }, (eventType, filename) => {
console.log(`${eventType}: ${filename}`)
// Copy the shared folder straight to your project /src
// You could be smarter here and only copy the changed file
ncp('../shared', './src/shared', function(err) {
if (err) {
return console.error(err);
}
console.log('finished syncing!');
});
})
This is an issue with the relative import, which might have caused because we've used "create-react-app project" command which forms a directory named project with node_modules folder and several other files in public and src folders inside it.
The create-react-app command puts a limitation that we can't import anything from outside src.
My Problem:
I had to import react-bootstrap css files which are created in node_modules folder outside the src folder.
I used import "../node_modules/bootstrap/dist/css/bootstrap.min.css"; but I got the error on terminal.
I found out that I can create a new react app and follow solution steps from A to G, in order to fix this issue.
Solution:
A) Create a new react app, using create-react-app new
B) cd new
C) run this command: "npm install react-bootstrap bootstrap#4.6.0" (without the "" double quotes )
D) in your react file put this to import bootstrap:
D.1) import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
or
D.2)import Button from "react-bootstrap/Button";
E) create a bootstrap element like a Button or anything in your react file, for D.1) < button className="btn btn-success" > Bootstrap < /button>
or
for D.2) < Button variant="primary"> Bootstrap < /Button>
F) in terminal: cd src
G) in terminal: npm start,
this time it will be compiled successfully.
Reasoning:
I could see react-bootstrap working finally once I followed steps A to G in order, and this time I didn't get any error.
(I thought of this solution because:
I've used npm install "#material-ui/icons" and that got installed in the node_modules folder outside the src.
In my react file I've used import Add from "#material-ui/icons/Add"
and Material-ui icons were working fine for me,
but here also we are importing from outside src, from node_modules.. and everything works fine. Why there is no error of importing from outside src this time)
That's why I just created a new react app, and followed solution steps A to G.
If you want to set a background image using CSS. So you have to set the image using the URL of your's localhost and add the path of your image. Just see the example below.
.banner {
width: 100%;
height: 100vh;
background-image: url("http://localhost:3000/img/bg.jpg");
background-size: cover;
background-repeat: no-repeat;
}
Posting here what #Flaom wrote as a comment in the marked as reply answer and that actually saves lives:
"How is this the accepted answer? This bogus restriction is trivially eliminated by simply setting NODE_PATH=./src/.. in the .env file. By doing so, you can import from outside of the src folder without going through the pain associated with ejecting your app. "
Flaom
EDIT Added some more info as #cigien requested.
All the answers above describe very well why we cannot use an image from the public folder when we create our react app with the create-react-app. Having the issue myself and reading all these answers I realized that, what the answers say is to "hack" the app in order to remove the module that restricts us. Some of the answers don't even have an undo option. For a "training" application that is ok.
Personally I would not want to add a solution that alters the concept of the app to my own project, specially in a commercial one. #Flaom solution is the simplest and if anything change in the future it can be replaced with another solution. It has no risk, it can be removed anytime and is the simplest.
This was my code:
import React from 'react';
import './Navbar.scss';
import {images} from '../../constants';
const Navbar = () => {
return (
<nav>
<div>
< img src = {images.logo} alt = "logo" />
</div>
</nav>
);
}
export default Navbar;
Changed it too:
import React from 'react';
import './Navbar.scss';
import {images} from '././constants';
const Navbar = () => {
return (
<nav>
<div>
< img src = {images.logo} alt = "logo" />
</div>
</nav>
);
}
export default Navbar;
And it worked! Im getting better at fixing bugs haha.
If you file reside in public folder and if you want to import it without eject or without using react-app-rewired then in that case you can access file via domains name and the path of the file and using axios.
Example: There is a font file called favico.ico located inside public folder. You want to import it in one the file located in src. You
can access the font using following logic.
axios.get('example.com/favico.ico').then(() => {
// here you can access this file.
})
In above example example.com is domain. If you have different environment like localhost, staging, production then in that case the domain name is different.
So, to get the favico.ico you can use following logic.
axios.get(`${window.location.origin}/favico.ico`).then(() => {
// here you can access this file.
})
In above example you window.location.origin give you current domain meaning if you run your code locally then, it will give you http://localhost:{portnumber},
If your code run on production and production domain is example.com then, it will give you "example.com". So using this pattern you can access assets located in public folder.

Gulp task: get files with wiredep concatenate other js files and minify

I´m trying to build a gulp task that get all bower_components files with wiredep, then concatenates them together. Then concatenate some other JS files I have on a special folder an finally minify everything.
The problem is that I don´t know if I can specify wiredep another directory additional to the bower_components directory. If that´s not possible, is there any other solution I can use?
I´m a begginer using gulp, so any other error that you can point out in how I´m thinking my task would be highly appreciated.
var wiredep = require('wiredep')(
{
directory: 'static/bower_components', // default: '.bowerrc'.directory || bower_components
}).stream;
gulp.task('scripts',function(){
return gulp
.src('index.html') //I don´t really know what to put in the src
.pipe(wiredep())
.pipe($.inject(gulp.src("More JS files if wire dep can´t handle them")))
.pipe(minify())
.pipe(gulp.dest('static/dist/src/app.min.js'));
});
I would have a method like this (perhaps in a config file at the root of the project) to get whatever you wanted wired in with wiredep:
getWiredepDefaultOptions: function() {
var options = {
directory: bower.directory,//file path to /bower_components/
};
return options;
},
Then in your gulp task, have something like this:
gulp.task('wiredep', function() {
log('Wiring the bower dependencies into the html');
var wiredep = require('wiredep').stream;
var options = config.getWiredepDefaultOptions();
return gulp
.src('./index.html')
.pipe(wiredep(options))
.pipe(gulp.dest("wherever you want your index.html"));
});
Depending on what other things you want to wire in, you would have to add an ordering of some kind using tags within the index.html.

How to set up gulp to bundle several files into one?

This seems like a very simple question, but spent the last 3 hours researching it, discovering it can be slow on every save on a new file if not using watchify.
This is my directory tree:
gulpfile.js
package.json
www/
default.htm
<script src="toBundleJsHere/file123.js"></script>
toBundletheseJs/
componentX/
file1.js
componentY/
file2.js
componentZ/
file3.js
toPutBundledJsHere/
file123.js
Requirements.
On every creation or save of a file within the folder toBundleTheseJs/ I want this file to be rebundled into toBundleJsHere/
What do I need to include in my package.json file?
And whats the minimum I need to write into my gulp file?
This should be as fast as possible so think I should be using browserify and watchify. I want to understand the minimum steps so using package manager like jspm is overkill a this point.
thanks
First you should listen to changes in the desired dir:
watch(['toBundletheseJs/**/*.js'], function () {
gulp.run('bundle-js');
});
Then the bundle-js task should bundle your files. A recommended way is gulp-concat:
var concat = require('gulp-concat');
var gulp = require('gulp');
gulp.task('bundle-js', function() {
return gulp.src('toBundletheseJs/**/*.js')
.pipe(concat('file123.js'))
.pipe(gulp.dest('./toPutBundledJsHere/'));
});
The right answer is: there is no legit need for concatenating JS files using gulp. Therefore you should never do that.
Instead, look into proper JS bundlers that will properly concatenate your files organizing them according to some established format, like commonsjs, amd, umd, etc.
Here's a list of more appropriate tools:
Webpack
Rollup
Parcel
Note that my answer is around end of 2020, so if you're reading this in a somewhat distant future keep in mind the javascript community travels fast so that new and better tools may be around.
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('js', function (done) {
// array of all the js paths you want to bundle.
var scriptSources = ['./node_modules/idb/lib/idb.js', 'js/**/*.js'];
gulp.src(scriptSources)
// name of the new file all your js files are to be bundled to.
.pipe(concat('all.js'))
// the destination where the new bundled file is going to be saved to.
.pipe(gulp.dest('dist/js'));
done();
});
Use this code to bundle several files into one.
gulp.task('scripts', function() {
return gulp.src(['./lib/file3.js', './lib/file1.js', './lib/file2.js']) //files separated by comma
.pipe(concat('script.js')) //resultant file name
.pipe(gulp.dest('./dist/')); //Destination where file to be exported
});

How do I get Bower to install a file to a specified path and name?

I have the following bower.json:
{
"name": "myname",
"dependencies": {
"stripe": "https://js.stripe.com/v2/"
}
}
This grabs the javascript at the associated url and creates the following file:
/bower_components/stripe/index
Note that the file is not index.js, but simply index. This is problematic, as my Brocfile refuses to use the index file, insisting that it has to be index.js. If I manually change the name to index.js, then the application works fine. Obviously, this isn't a satisfactory solution.
So is there a way to get bower to install the file as index.js rather than index?
If you need to set a different folder for bower you can create a .bowerrc file with the following:
{
"directory": "public/bower"
}
I'm not exactly sure of your environment, but for example if you have node.js you can create a gulp.js setup which would do the rename before whatever other processes you need to run.
quasi example gulpfile.js
var gulp = require('gulp');
var rename = require('gulp-rename');
gulp.task('prep', function () {
gulp.src('public/bower/stripe/index', {
base: 'public/bower/stripe'
})
.pipe(rename('index.js'));
.pipe(gulp.dest('./'));
});

Compiling dynamically required modules with Browserify

I am using Browserify to compile a large Node.js application into a single file (using options --bare and --ignore-missing [to avoid troubles with lib-cov in Express]). I have some code to dynamically load modules based on what is available in a directory:
var fs = require('fs'),
path = require('path');
fs.readdirSync(__dirname).forEach(function (file) {
if (file !== 'index.js' && fs.statSync(path.join(__dirname, file)).isFile()) {
module.exports[file.substring(0, file.length-3)] = require(path.join(__dirname, file));
}
});
I'm getting strange errors in my application where aribtrary text files are being loaded from the directory my compiled file is loaded in. I think it's because paths are no longer set correctly, and because Browserify won't be able to require() the correct files that are dynamically loaded like this.
Short of making a static index.js file, is there a preferred method of dynamically requiring a directory of modules that is out-of-the-box compatible with Browserify?
This plugin allows to require Glob patterns: require-globify
Then, with a little hack you can add all the files on compilation and not executing them:
// Hack to compile Glob files. Don´t call this function!
function ಠ_ಠ() {
require('views/**/*.js', { glob: true })
}
And, for example, you could require and execute a specific file when you need it :D
var homePage = require('views/'+currentView)
Browserify does not support dynamic requires - see GH issue 377.
The only method for dynamically requiring a directory I am aware of: a build step to list the directory files and write the "static" index.js file.
There's also the bulkify transform, as documented here:
https://github.com/chrisdavies/tech-thoughts/blob/master/browserify-include-directory.md
Basically, you can do this in your app.js or whatever:
var bulk = require('bulk-require');
// Require all of the scripts in the controllers directory
bulk(__dirname, ['controllers/**/*.js']);
And my gulpfile has something like this in it:
gulp.task('js', function () {
return gulp.src('./src/js/init.js')
.pipe(browserify({
transform: ['bulkify']
}))
.pipe(rename('app.js'))
.pipe(uglify())
.pipe(gulp.dest('./dest/js'));
});

Categories