ComponentName/ComponentName.js rather than ComponentName/index.js - node.js

I prefer to not use index.js as a file name for the main file of a component in React and in node.js, but instead use the name of the parent directory (for example: ...somePath.../ComponentName/ComponentName.js would just be ...somePath.../ComponentName).
Is there any way to have
require('..somePath../ComponentName')
and
import ComponentName from '..somePath../ComponentName'
work without having to put in the file name too, similar to how you can drop the index.js from the import path.
I am guessing there would be two different solutions for node.js and React, but hopefully there is just one solution.

Maybe this is because of my IDE (I use VScode), but the extension for any file is not needed. This example works in React. Note: Does not work with the styles sheet.
Components
├── Header
│ ├── index.js
├── Footer
│ ├── index.js
import Header from '../Header';
import Footer from '../Footer';

Related

Flask url_for 'static' in templates folder?

Maybe there's a better way to do this, but I'm trying to organize my Flask application so that both static Javascript and HTML templates sit in the same folder (similar to components)
This is just for organization purposes, I won't be rendering the statics in jinja2
So, instead of this :
├── templates/
│ ├── login.html
├── static/
│ ├── login.js
I'm looking for this (just an idea):
├── components/
│ ├── login/
│ │ ├── login.html
│ │ └── login.js
Or maybe this, so I can make a wrapper that renders a component just by its folder name, ex: return render_component('login')
├── components/
│ ├── login/
│ │ ├── template.html
│ │ └── login.js
The concept is that inside login.html template it adds a script tag with url_for to login.js
I'm also open to different ideas/ways to achieve this component structure
I'm sure there are other ways to achieve this but one way is to use blueprint structure and contain all static files for that specific blueprint inside the blueprint folder.
app
|- collections
| - blueprint_one
| - configs
| - static
| - css
| - js
| js_file_one.js
| - templates
| - blueprint_one
| html_file_one.html
| blue_print_one_view_file_one.py
| __init__.py
| - blueprint_two
| - blueprint_three
|- static
| - js
| - css
|- templates
__init__.py
Above folder structure allows you to separate out not only the static files but also the Flask view files.
Below are examples of activating/importing files:
1) app/init.py
app = Flask(__name__, static_folder='static')
app.config.from_pyfile('app_config.py')
# Do all your db set up and etcs..
# Import blueprints below set ups to prevent circular import
app.collections.blueprint_one import blueprint_one
app.collections.blueprint_two import blueprint_two
# Now register blueprints that you've imported
app.register_blueprint(blueprint_one, url_prefix='/blueprint_one')
app.register_blueprint(blueprint_two, url_prefix='/blueprint_two')
2) blueprint_one/init.py
# Create a blueprint
from flask import Blueprint
blueprint_one = Blueprint('blueprint_one_name', __name__, template_folder='templates', static_folder='static')
# Import required views to use
from . import blue_print_one_view_file_one.py
3) blueprint_one/blue_print_one_view_file_one.py
# Import blueprint
from app.collections.blueprint_one import blueprint_one
# Any view functions using above blueprint
#blueprint_one.route('/login/, methods=['GET'])
def login():
return render_template('blueprint_one/html_file_one.html')
4) blueprint_one/templates/blueprint_one/html_file_one.html
// Note: instead of .static, you can use blueprint_one.static.
<script type="text/javascript" src="{{ url_for('.static', filename = 'js/js_file_one.js') }}"></script>
5) app/static and app/templates still can be used as you are using it currently.
This solution doesn't solve the problem of putting js and html into same folder but at least you can divide each feature into component like blueprint for more modularized project structure.
There isn't a best way to do this so I like to suggest that you review the way flask projects are supposed to be set up.
http://flask.pocoo.org/docs/1.0/tutorial/layout/
Also I think this question may have an answer that solves your problem here.
Flask url_for URLs in Javascript
Now here's a few thoughts.
To me it sounds like you want to use Templating in files that are in your static folder. This is not what the static folder is intended for. Static means unchanging, so the files in your static folder should not change. Templates are intended to be dynamic which usually means that they change. If you plan to render templates from files in your static directory you will encounter numerous issues and possibly even not be able to do it. One of the most prominent issues I can see you possibly encountering is that browsers will not want to grab the new javascript files if it thinks they're in your static directory. Browsers may assume they haven't changed. Also Flask does some magic behind the scenes. When a url for a file in your static directory is processed from a client who has already requested the file flask returns HTTP CODE 304 which essentially means "File hasn't changed".
I could go on and on about why you shouldn't do this. Instead, if none of information above solves your question, I would like to suggest that you put your javascript templates in a sub-directory of your template directory. Then use the following code to return them.
#app.route('/js/<file_name>',methods=['GET'])
def get_js_templates(file_name):
return render_template('js/'+file_name)
I am by no means an expert in any capacity but I have done full stack development using the flask web framework. If you have more questions leave a comment on this post.

How to get the current path of the running Yeoman generator

I have my own Yeoman generator.
I created a sub-generator to create a new view folder.
Basically, the usage is:
open a new terminal
cd into the parent folder
run the yeoman command yo my-generator:view
follow the instructions
This view sub-generator prompt a folder name.
For example:
If I want to create the view authentication on the default views directory.
cd views
yo my-generator:view
The result should be:
views //- Already created by the main generator
├── authentication
│ ├── authentication.controller.js
│ ├── authentication.template.html
Now, if I want to create a sub-view login for the authentication view.
cd views/authentication
yo my-generator:view
The result should be:
views //- Already created by the main generator
├── authentication
│ ├── authentication.controller.js
│ ├── authentication.template.html
│ ├── login
│ │ ├── login.controller.js
│ │ ├── login.template.html
Instead, the current (wrong) result is:
views //- Already created by the main generator
├── authentication
│ ├── authentication.controller.js
│ ├── authentication.template.html
├── login
│ ├── login.controller.js
│ ├── login.template.html
My struggle here is that I don't know how to get the current path when I run the command.
Actually, I just create the new folder with a default prefix path which is app/views/.
This is why Authentication example works.
However when my current path is deeper in the views folder, it will add the new folder at the root of the views folder.
If I could get the current path (of the cmd), I should be able to add this path as the prefix instead of setting a default and not static one.
This is why Login example doesn't works.
Some code example:
$that is the current generator object
$that.viewNameCamel is the name of the folder set by the user
I use a .txt file as template and then create the controller.js file.
const filePrefix = 'app/views/' + $that.viewNameCamel + '/' + $that.viewNameCamel + '.';
const exampleData = {
controllerAlias: 'vm',
otherVar: 'example'
};
$that.fs.copyTpl(
$that.templatePath('controller.txt'),
filePrefix + 'controller.js',
exampleData
);
Tried:
$that.env.cwd
process.cwd()
__dirname
path.js library
Similar:
Issue 1037
Question 28481715
So guys, do you have a clue on how do I get the current folder path ?
Is there an alternative solution here ?
Thanks !
EDIT 1:
The problem here is the .yo-rc.json present on the root directory of the projet.
The file rewrite the path so I should delete it to fix the problem.
However if I delete this file, the user configuration will no longer be saved.
And I need it for later sub-generator usage.
Is there another way to save the user configuration ?
Or once again, is there another way to get the current real path ?
I know this is kinda old but for any one who comes later,
from the documentation https://yeoman.io/authoring/file-system.html
If you want to know from where the user is running yo, then you can get the path with this.contextRoot. This is the raw path where yo was invoked from; before we determine the project root with .yo-rc.json.
from my experience removing the .yo-rc.json would mean that you need to manually check if the path provided is ok, having a fixed root point is something helpful.
Just remove the .yo-rc.json file from your root directory. This is the file that is responsible for locating your root irrespective of where you are in the file system.
I am not sure about the repercussions of removing it but nothing seem to have happened to the generators I built.
Now you can use process.cwd() and it will get the correct working directory.
For your use case to have a prefix app/views, you probably need to write some Javascript to append or not append the prefix based on where you are, which should be trivial.

Less loader image url

I'm having trouble adding an image url to a variable in my LESS file.
I am using a project called Guide4You where I would like to add a new LESS file with my own images. This project uses node with webpack.
For my project I use this folder structure:
├── root
│ ├── load_image.png
│ ├── styles
│ │ └── substyles
│ │ ├── load.less
In the less file I have the following code:
#test: url("../../load_image.png");
Whenever I try to compile the code into webpack I get the following error:
[ './root/load_image.png
Module parse failed:
C:\projects\root\\load_image.png
Unexpected character \'�\' (1:0)\nYou may need an appropriate loader to handle this file type.
Is it possible that the less-loader sees my url as a reference to another loader and tries to execute it?
You need an appropriate loader that would match that png of yours. To solve this problem, use either url-loader or file-loader so that it matches your png.
Documentation: https://github.com/webpack-contrib/url-loader, https://github.com/webpack-contrib/file-loader

How to wire Angular2 + Webpack + Node + Express?

First of all, I have it wired and working, but I am somewhat discontent with the result and have a feeling it can be improved.
(The current result can be found here - https://github.com/MarkKharitonov/Angular2WebpackNodeExpress/tree/v0.0.1.)
The directory structure is:
C:.
│ .gitignore
│ package.json
│ tsconfig.json
│ tslint.json
│ typings.json
│ webpack.config.js
│
├───dist
│ └───server
│ api.js
│ api.js.map
│ main.js
│ main.js.map
│
└───src
├───client
│ app.component.ts
│ index.html
│ main.ts
│ polyfills.ts
│ tsconfig.json
│ vendor.ts
│
└───server
api.ts
main.ts
tsconfig.json
Right now the dist folder has only the server side files compiled from ./src/server. They are placed there by the IntelliJ IDEA, because ./src/server/tsconfig.json requests compilation on save.
The client side bundling occurs in memory courtesy of webpack-dev-server. The ./src/client/tsconfig.json does not request compilation on save.
The things I dislike about my current setup are described here - https://github.com/MarkKharitonov/Angular2WebpackNodeExpress/tree/v0.0.1#problems, namely:
webpack is going to take care of any plain .js files under ./src/client - they would be bundled and placed under ./dist/client automatically. But what about plain .js files under ./src/server ? Do I need a task runner for that (gulp, grunt, whatever ...) or is there a solution within webpack?
I have three tsconfig.json files - ./src/client/tsconfig.json, ./src/server/tsconfig.json and ./tsconfig.json. The three files share most of the options, but not all. Right now I copy them in each of the three files - not very good.
In addition, because the typings folder is at the root I have to start all the top level TypeScript files (.\src\client\main.ts, .\src\client\polyfills.ts, .\src\client\vendor.ts and .\src\server\main.ts) with /// <reference path="../../typings/index.d.ts" />.
Hence the questions:
Can webpack also handle the server side files, but differently from the client side ones? I.e. transpile - yes, copy to dist - yes, bundle - no? Please, bear in mind I am using webpack-dev-server.
Is it possible to inherit tsconfig.json configuration so that I could avoid duplicating many options across the three files I have?
Is it possible to avoid the inclusion of /// <reference path="../../typings/index.d.ts" /> in the top level TypeScript files when the file layout is similar to mine ?
I know these are three questions instead of one, but I feel they are all closely related and the answer to one could also be the answer to another.
I don't think you need/want webpack to handle server-side files. Transpiling and copying over of the server side files to /dist is handled by Typescript compiler (via outDir config), already. There will be no bundling of server-side files since no server files were indicated as entry points in the webpack config.
Is not currently possible. However, looks like there is an issue to track this: https://github.com/Microsoft/TypeScript/issues/9876
Unsure, related to #3 in a way (but not really). I'd imagine no as long as you want to keep the client and server files truly seperate.

Express.js Project Structure

I found that Express has an application generator, however the documentation does not explain the purpose of each directory and file. If someone could just give me a short explanation of which files I should be putting where, that would be much appreciated. Here's the generated app structure:
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.jade
├── index.jade
└── layout.jade
7 directories, 9 files
The app.js file is the entry-point of your application.
The package.json file contains all of your dependencies and various details regarding your project.
The bin folder should contain the various configuration startup scripts for your application.
For example, instead of applying all the Express middleware in the app.js file, you module.exports = {} them from their own configuration file and require them in app.js. [additional info LINK]
The views folder contains all of your server-side views.
The public folder contains all of your front-end code.
The routes folder contains all the routes that you have created for your application.
As stated in the official documentation, be aware that this is just one way to organize your code.
You should test it out and see if it fits your project.
This thread gives a deeper answer about the www file specifically: What does "./bin/www" do in Express 4.x?
Basically, running your app from the www file (which calls app.js) allows you to start your app with different configurations. You might have a "www" file representing the way the app should be run when on the web, a "dev" file that you, as the developer, would run, a "test" file you would run when running tests, etc. Read the thread linked above for more detail!
This structure is a standard organization for web-app
public contains all client static files (css, client javascript (ex. jQuery), images, fonts...)
routes contains the main back-end code (server side), which compute data before calling a template engine (see below) or respond to the client (via json of xml).
views contains each page template, see jade template. These files are used by scripts in "route"
app.js contains the express core, such as uri parser, modules, database...
package.json is the project descriptor file (used by npm for dependencies and sharing)
If the application generator provide a full example, don't hesitate to open each file (starting from app.js) to understand the project's organization.

Resources