Copy all files but change the name of some automatically in yeoman - yeoman

I am trying to create a yeoman generator where I have to copy from templatePath to destinationPath some files and folders, but I would want to have some of this files with a variable that yeoman could change by one of the user's inputs.
like: "<%=name%>-plugin.php" -> "hello-plugin.php"
I saw some references that this can be done but I can't find how.
I am doing right now:
//Copy the configuration files
app: function () {
this.fs.copyTpl(
this.templatePath('**'),
this.destinationPath(),
{
name: this.props.pluginName,
name_function: this.props.pluginName.replace('-', '_'),
name_class: this.props.className,
description: this.props.pluginDescription
}
);
}
I thought that with that code my <%=name%> would magically changed on copyTpl but it doesn't work

I've just found the solution:
Use this.registerTransformStream(); to pipe all files through some node.js script.
var rename = require("gulp-rename");
//other dependecies...
module.exports = yeoman.Base.extend({
//some other things generator do...
writing: function() {
var THAT = this;
this.registerTransformStream(rename(function(path) {
path.basename = path.basename.replace(/(666replacethat666)/g, THAT.props.appName);
path.dirname = path.dirname.replace(/(666replacethat666)/g, THAT.props.appName);
}));
this.fs.copyTpl(
this.templatePath(),
this.destinationPath(), {
appName: this.props.appName
});
}
});
I'm using here gulp-rename to change file names to something else.
Assuming that this.props.appName == "myFirstApp", this:
666replacethat666-controller.html
will change its name to
myFirstApp-controller.html

Following #piotrek answer, I made a function to replace all props with some pattern (like ejs does) -> $$[your prop name]$$. warning: ES6 inside
var rename = require("gulp-rename");
//other dependecies...
module.exports = yeoman.Base.extend({
//some other things generator do...
writing: function() {
this.registerTransformStream(rename((path) => {
for (let prop in this.props) {
let regexp = new RegExp('\\$\\$' + prop + '\\$\\$', 'g')
path.basename = path.basename.replace(regexp, this.props[prop]);
path.dirname = path.dirname.replace(regexp, this.props[prop]);
}
}));
this.fs.copyTpl(
this.templatePath(),
this.destinationPath(), {
appName: this.props.appName
});
}
});
Example:
Let's assume you have this.props.appname = MyApp and this.props.AnotherProps = Test and you want to rename file or folder.
Name your file or folder MyFile$$appname$$.js -> MyFileMyApp.js
Name your file or folder $$appname$$.js -> MyApp.js
Name your file or folder $$AnotherProps$$.js -> Test.js

This is not possible anymore. The feature was bloated and was removed at some point in 2015.
For now, just rename the file:
this.fs.copy('name.js', 'new-name.js')

Related

Trouble reading user accessible files

I am using nativescript-mediafilepicker as means of choosing a file, and this can read external storage successfully (I have downloaded a PDF to the 'downloads' folder on iOS and I am able to pick it.) I then try to load the file using the file system module from nativescript library, and this fails because it is listed as NativeScript encountered a fatal error: Uncaught Error: You can’t save the file “com.xxxxxx” because the volume is read only. This doesn't make sense as I am trying to read anyway - I don't understand where the saving part is from. The error comes from fileSystemModule.File.fromPath() line.
Something to note that file['file'] is file:///Users/adair/Library/Developer/CoreSimulator/Devices/82F397CE-B0B3-4ADD-AD52-805265C7AC49/data/Containers/Data/Application/7B47A8BD-6DBA-42CF-8792-38A8C5E61174/tmp/com.xxxxxx/test.pdf
Is the file automatically being pulled to an application specific directory after this media picker?
getFiles() {
let extensions = [];
if (app.ios) {
extensions = [kUTTypePDF]; // you can get more types from here: https://developer.apple.com/documentation/mobilecoreservices/uttype
} else {
extensions = ["pdf"];
}
const mediaFilePicker = new Mediafilepicker();
const filePickerOptions = {
android: {
extensions,
maxNumberFiles: 1,
},
ios: {
extensions,
maxNumberFiles: 1,
},
};
masterPermissions
.requestPermissions([masterPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,masterPermissions.PERMISSIONS.WRITE_EXTERNAL_STORAGE])
.then((fulfilled) => {
console.log(fulfilled);
mediaFilePicker.openFilePicker(filePickerOptions);
mediaFilePicker.on("getFiles", function (res) {
let results = res.object.get("results");
let file = results[0];
console.dir(file);
let fileObject = fileSystemModule.File.fromPath(file["file"]);
console.log(fileObject);
});
mediaFilePicker.on("error", function (res) {
let msg = res.object.get("msg");
console.log(msg);
});
mediaFilePicker.on("cancel", function (res) {
let msg = res.object.get("msg");
console.log(msg);
});
})
.catch((e) => {
console.log(e);
});
},
The issue I have experienced is resultant of the expectation of File.fromPath and what is returned by the file picker. File picker is returning a "file://path" URI, and File.fromPath is expecting a string of just "path".
Simply using the following instead is enough.
let fileObject = fileSystemModule.File.fromPath(file["file"].replace("file://","");

Call yeoman generator from code with options

I created a yeoman generator with user interaction, that can be called in the terminal like (after running npm link):
yo mygenerator --name test --path /test/path --project testproject
Now I want to include this generator in my vscode extension.
How can I call the yo generator from my typescript code when the generator when the generator is added as a package.json dependency?
So something like (pseudo code)
import { yo } from 'yeoman';
import mygenerator; // added as a dependency via package.json
const options = {
name: 'test',
path: '/test/path',
project: 'testproject',
};
yo.exec(mygenerator, options, () => {
console.log('yeoman finished')
});
Is something like this possible?
Here is a solution for that:
const env = yeoman.createEnv();
const generatorPath = '../node_modules/generator-name/generators/app/index.js';
env.getByPath(generatorDir);
env.on('error', (err: any) => {
// handle error
});
const options = {
env,
'option1': option1,
'option2': option2,
};
try {
await env.run('name', options);
} catch (err) {
// handle error
}

How to get a fileEntry to then use readAsText in cordova / ionic(2)?

In my Ionic2 app I managed to successfully use certain methods of the File plugin such as:
checkDir
createDir
createFile
Now I want to use readAsText (as specified in the docs) but I can't figure out how to get a fileEntry without creating a new file, (which apparently would require overriding it)?
You can get a fileEntry by using cordova-plugin-filepath
If you have an URI starting with "content://", we need the local file URI starting with "file://".
FilePath.resolveNativePath returns the local file url.
let uri = "content://com.android.externalstorage.documents/document/primary/data...";
window.FilePath.resolveNativePath(uri, (localFileUri) => {
// result is file:///storage/emulated/0/Android/data/...
// now get a fileEntry from this uri
window.resolveLocalFileSystemURL(localFileUri, (fileEntry) => {
});
});
File Entry, has a method "file" which can be used to get a file object and read the content of the file with FileReader, e.g:
fileEntry.file((file) => {
var reader = new FileReader();
reader.onloadend = (e) => {
let result = e.target.result; // text content of the file
// do whatever you like
};
reader.readAsText(file);
Here is an example of using the readAsText() function if you know the path of the file:
const fs:string = cordova.file.externalRootDirectory;
File.readAsText(fs, filePath).then((contents) => {
if(typeof contents == 'string'){
processFile(contents);
}
});
One slight gotcha is that the file path must not start with a /.
An example where this might catch you is when processing files in a directory;
const fs:string = cordova.file.externalRootDirectory;
File.listDir(fs, "").then(files => {
for (let file of files){
if(file.name.toLowerCase().endsWith(".csv")){
File.readAsText(fs, file.fullPath.substr(1)).then((contents) => {
if(typeof contents == 'string'){
processFile(contents);
}
});
}
}
});

How to create multiple output paths in Webpack config

Does anyone know how to create multiple output paths in a webpack.config.js file? I'm using bootstrap-sass which comes with a few different font files, etc. For webpack to process these i've included file-loader which is working correctly, however the files it outputs are being saved to the output path i specified for the rest of my files:
output: {
path: __dirname + "/js",
filename: "scripts.min.js"
}
I'd like to achieve something where I can maybe look at the extension types for whatever webpack is outputting and for things ending in .woff .eot, etc, have them diverted to a different output path. Is this possible?
I did a little googling and came across this *issue on github where a couple of solutions are offered, edit:
but it looks as if you need to know the entry point in able to specify an output using the hash method
eg:
var entryPointsPathPrefix = './src/javascripts/pages';
var WebpackConfig = {
entry : {
a: entryPointsPathPrefix + '/a.jsx',
b: entryPointsPathPrefix + '/b.jsx',
c: entryPointsPathPrefix + '/c.jsx',
d: entryPointsPathPrefix + '/d.jsx'
},
// send to distribution
output: {
path: './dist/js',
filename: '[name].js'
}
}
*https://github.com/webpack/webpack/issues/1189
however in my case, as far as the font files are concerned, the input process is kind of abstracted away and all i know is the output. in the case of my other files undergoing transformations, there's a known point where i'm requiring them in to be then handled by my loaders. if there was a way of finding out where this step was happening, i could then use the hash method to customize output paths, but i don't know where these files are being required in.
Webpack does support multiple output paths.
Set the output paths as the entry key. And use the name as output template.
webpack config:
entry: {
'module/a/index': 'module/a/index.js',
'module/b/index': 'module/b/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
}
generated:
└── module
├── a
│   └── index.js
└── b
└── index.js
I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.
But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js).
var config = {
// TODO: Add common Configuration
module: {},
};
var fooConfig = Object.assign({}, config, {
name: "a",
entry: "./a/app",
output: {
path: "./a",
filename: "bundle.js"
},
});
var barConfig = Object.assign({}, config,{
name: "b",
entry: "./b/app",
output: {
path: "./b",
filename: "bundle.js"
},
});
// Return Array of Configurations
module.exports = [
fooConfig, barConfig,
];
If you have common configuration among them, you could use the extend library or Object.assign in ES6 or {...} spread operator in ES7.
You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –
module.exports = {
entry: {
home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
}
};
If you can live with multiple output paths having the same level of depth and folder structure there is a way to do this in webpack 2 (have yet to test with webpack 1.x)
Basically you don't follow the doc rules and you provide a path for the filename.
module.exports = {
entry: {
foo: 'foo.js',
bar: 'bar.js'
},
output: {
path: path.join(__dirname, 'components'),
filename: '[name]/dist/[name].bundle.js', // Hacky way to force webpack to have multiple output folders vs multiple files per one path
}
};
That will take this folder structure
/-
foo.js
bar.js
And turn it into
/-
foo.js
bar.js
components/foo/dist/foo.js
components/bar/dist/bar.js
Please don't use any workaround because it will impact build performance.
Webpack File Manager Plugin
Easy to install copy this tag on top of the webpack.config.js
const FileManagerPlugin = require('filemanager-webpack-plugin');
Install
npm install filemanager-webpack-plugin --save-dev
Add the plugin
module.exports = {
plugins: [
new FileManagerPlugin({
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}),
],
};
Screenshot
If it's not obvious after all the answers you can also output to a completely different directories (for example a directory outside your standard dist folder). You can do that by using your root as a path (because you only have one path) and by moving the full "directory part" of your path to the entry option (because you can have multiple entries):
entry: {
'dist/main': './src/index.js',
'docs/main': './src/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, './'),
}
This config results in the ./dist/main.js and ./docs/main.js being created.
In my case I had this scenario
const config = {
entry: {
moduleA: './modules/moduleA/index.js',
moduleB: './modules/moduleB/index.js',
moduleC: './modules/moduleB/v1/index.js',
moduleC: './modules/moduleB/v2/index.js',
},
}
And I solve it like this (webpack4)
const config = {
entry: {
moduleA: './modules/moduleA/index.js',
moduleB: './modules/moduleB/index.js',
'moduleC/v1/moduleC': './modules/moduleB/v1/index.js',
'moduleC/v2/MoculeC': './modules/moduleB/v2/index.js',
},
}
You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.
In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:
const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
// ...
new FileManagerPlugin({
onEnd: {
copy: [{
source: './dist/*.*',
destination: './public/',
}],
},
}),
],
You can only have one output path.
from the docs https://github.com/webpack/docs/wiki/configuration#output
Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified.
If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPlugin or recordsPath.
I wrote a plugin that can hopefully do what you want, you can specify known or unknown entry points (using glob) and specify exact outputs or dynamically generate them using the entry file path and name. https://www.npmjs.com/package/webpack-entry-plus
I actually wound up just going into index.js in the file-loader module and changing where the contents were emitted to. This is probably not the optimal solution, but until there's some other way, this is fine since I know exactly what's being handled by this loader, which is just fonts.
//index.js
var loaderUtils = require("loader-utils");
module.exports = function(content) {
this.cacheable && this.cacheable();
if(!this.emitFile) throw new Error("emitFile is required from module system");
var query = loaderUtils.parseQuery(this.query);
var url = loaderUtils.interpolateName(this, query.name || "[hash].[ext]", {
context: query.context || this.options.context,
content: content,
regExp: query.regExp
});
this.emitFile("fonts/"+ url, content);//changed path to emit contents to "fonts" folder rather than project root
return "module.exports = __webpack_public_path__ + " + JSON.stringify( url) + ";";
}
module.exports.raw = true;
u can do lik
var config = {
// TODO: Add common Configuration
module: {},
};
var x= Object.assign({}, config, {
name: "x",
entry: "./public/x/js/x.js",
output: {
path: __dirname+"/public/x/jsbuild",
filename: "xbundle.js"
},
});
var y= Object.assign({}, config, {
name: "y",
entry: "./public/y/js/FBRscript.js",
output: {
path: __dirname+"/public/fbr/jsbuild",
filename: "ybundle.js"
},
});
let list=[x,y];
for(item of list){
module.exports =item;
}
The problem is already in the language:
entry (which is a object (key/value) and is used to define the inputs*)
output (which is a object (key/value) and is used to define outputs*)
The idea to differentiate the output based on limited placeholder like '[name]' defines limitations.
I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.
All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.
Vinod Kumar's good workaround is:
module.exports = {
plugins: [
new FileManagerPlugin({
events: {
onEnd: {
copy: [
{source: 'www', destination: './vinod test 1/'},
{source: 'www', destination: './vinod testing 2/'},
{source: 'www', destination: './vinod testing 3/'},
],
},
}
}),
],
};

Yeoman generator: how do I access user supplied options?

I'm building a yeoman generator. I prompt the user to name the project like this:
SimplesiteGenerator.prototype.askFor = function askFor() {
var cb = this.async();
console.log(this.yeoman);
var prompts = [{
name: 'siteName',
message: 'What do you want to call your site?'
}];
this.prompt(prompts, function (props) {
this.siteName = props.siteName;
cb();
}.bind(this));
};
Further on, I build the file system:
SimplesiteGenerator.prototype.app = function app() {
this.mkdir( 'app');
this.mkdir('app/templates');
this.mkdir( 'img');
I'd like to build the filesystem within a directory that is given the same name as the project. How do I get the user-supplied option and pass it into app ?
You will need to make an empty global variable, then assign it the value of the users answer like so
var projectFolderName = '';
this.prompt(prompts, function (props) {
this.siteName = props.siteName;
projectFolderName = props.siteName;
cb();
}.bind(this));
Then inject this variable into your build path string via concatenation like so
SimplesiteGenerator.prototype.app = function app() {
this.mkdir( 'app/' + projectFolderName);
this.mkdir('app/templates');
this.mkdir( 'img');
}

Resources