Browser-sync - serve "node_modules" out of "src" directory - browser-sync

I'm using browsersync via lite-server, and have the following configuration:
{
"port": 8000,
"files": [
"./src/**/*.{html,htm,css,js}"
],
"server": {
"baseDir": "./src",
"routes": {
"node_modules": "../node_modules" <--- Attempt to serve node_modules
}
}
}
Project layout is like this:
node_modules
src
|-app
|-index.html
|-systemjs.config.js
package.json
bs-config.json
The problem is that inside index.html any reference like
<script src="node_modules/....js"> fails with a 404.
How can I serve paths outside of .src directory?

You can expose whole project folder by adding one more element to baseDir as Edvin mentioned.
But it would be better if you will expose only /node_modules using routes:
module.exports = {
server : {
baseDir : './dist',
routes : {
'/vendor' : './node_modules'
}
}
}

You can use multiple directory in baseDir config:
{
"server": {
"baseDir": ["./", "./src" ]
}
}

Related

How configure TypeORM ormconfig.json file to parse Entities from js dist folder or ts src folder?

I set my TypeORM config entities path like:
"entities": ["src/entities/**/*.ts"]
This works good when I use ts-node. ts-node src/main.ts
After compile typescripts using tsc, I got a dist folder with the compiled application:
However, typeORM still tries to get entities from the src folder instead of dist. throwing a lot of unexpectec syntax errors for parsing a TS file instead of a JS. So I change the fallowing string to the entities condiguration:
"entities": ["dist/entities/**/*.js"]
It works with node node dist/main.js but it does not works with ts-node src/main.ts
How can I configure ormconfig.json to be able to work with both (node at dist folder and ts-node at src folder)?
I'd suggest using an ormconfig.js instead of the JSON version and use an environment variable or similar to switch between the two configs. eg; something like the following stripped down example.
const srcConfig = {
"entities": [
"src/entities/**/*.ts"
],
}
const distConfig = {
"entities": [
"dist/entities/**/*.js"
],
}
module.exports = process.env.TS_NODE ? srcConfig : distConfig;
Note you'll need to set the TS_NODE env var somewhere; I did notice there's a PR not yet merged that will do it.
In addition to the existing answer:
I didn't like the idea to much to always work on the dist folder. Why? Because when I run commands from the command line I don't want to check whether dist is up-to-date, meaning was recently compiled.
So, I like my my typeorm commands like typeorm schema:sync work on the src! You can do that by running them via ts-node.
So, instead of
typeorm schema:sync
use
// Linux
ts-node ./node_modules/.bin/typeorm schema:sync
// Windows
ts-node ./node_modules/typeorm/cli.js schema:sync
Background
typeorm cli uses node, which relies on the files being compiled to javascript. So, that would only work on the /dist folder, which is the compiled version. However, that requires a watcher or similar running to capture changes of your ORM files. The described way here compiles typescript on-the-fly making a compilation not required. Source: https://github.com/typeorm/typeorm/blob/master/docs/faq.md#how-to-use-typeorm-with-ts-node
Based upon lock answer:
My full ormconfig.js
//npm install --save "detect-ts-node"
const detectTSNode = require('detect-ts-node');
const commonConfig = {
"type": "mssql",
"host": "127.0.0.1",
"port": 1433,
"username": "sa",
"password": "$$$$$$",
"database": "$$$$$$",
"synchronize": true,
"logging": false,
"options": {
"encrypt": false,
"enableArithAbort": false
}
};
const srcConfig = {
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
};
const distConfig = {
"entities": [
__dirname + "/dist/entity/**/*.js"
],
"migrations": [
__dirname + "/dist/migration/**/*.js"
],
"subscribers": [
__dirname + "/dist/subscriber/**/*.js"
],
"cli": {
"entitiesDir": __dirname + "/dist/entity",
"migrationsDir": __dirname + "/dist/migration",
"subscribersDir": __dirname + "/dist/subscriber"
}
};
const result = {};
let key;
// Append common configs to final object
for (key in commonConfig) {
if (commonConfig.hasOwnProperty(key)) {
result[key] = commonConfig[key];
}
}
if (detectTSNode) {
// if ts-node append src configuration
for (key in srcConfig) {
if (srcConfig.hasOwnProperty(key)) {
result[key] = srcConfig[key];
}
}
} else {
// else append dist configuration
for (key in distConfig) {
if (distConfig.hasOwnProperty(key)) {
result[key] = distConfig[key];
}
}
}
module.exports = result;
Usage in console.ts (my main file name)
import { createConnection } from "typeorm";
const conf = require('../ormconfig.js');
// Print the result for debuggin purposes
console.log(conf);
createConnection(conf).then(async connection => {
console.log("do your job here")
}).catch(error => {
console.log(error)
});

Using environment variables in nx based nodejs app

I've setup a project with several nodejs and angular apps inside a nrwl/nx workspace.
I'm trying to work with the environment files
inside the nodejs apps.
I've setup the import like this:
import {environment} from './environments/environment';
Then I ran ng serve my-node-app and it shows the environment for non production.
Now I tried to do ng serve my-node-app --prod to see how the app works with a production setup - but I get the error:
Configuration 'production' could not be found in project my-node-app.
Here's the project's angular.json config:
"ui-server": {
"root": "apps/ui/server",
"sourceRoot": "apps/ui/server/src",
"projectType": "application",
"prefix": "ui-server",
"schematics": {},
"architect": {
"build": {
"builder": "#nrwl/builders:node-build",
"options": {
"outputPath": "dist/apps/ui/server",
"main": "apps/ui/server/src/main.ts",
"tsConfig": "apps/ui/server/tsconfig.app.json",
"assets": ["apps/ui/server/src/assets"]
},
"configurations": {
"production": {
"optimization": true,
"extractLicenses": true,
"fileReplacements": [
{
"replace": "apps/ui/server/src/environments/environment.ts",
"with": "apps/ui/server/src/environments/environment.prod.ts"
}
]
}
}
},
"serve": {
"builder": "#nrwl/builders:node-execute",
"options": {
"buildTarget": "ui-server:build"
}
},
"lint": {
"builder": "#angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"apps/ui/server/tsconfig.app.json",
"apps/ui/server/tsconfig.spec.json"
],
"exclude": ["**/node_modules/**"]
}
},
"test": {
"builder": "#nrwl/builders:jest",
"options": {
"jestConfig": "apps/ui/server/jest.config.js",
"tsConfig": "apps/ui/server/tsconfig.spec.json"
}
}
}
}
Am I missing something?
I've found this post when I was looking how to fetch the environmental variables defined in .env file.
process.env.ENVIRONMENTAL_VARIABLES in frontend part can be accessed when rendering on the server (e.g. Angular Universal), having .env in the root of Nrwl monorepo and webpack properties, such as:
const dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new dotenv(),
],
};
Don't forget to change your angular.json:
...
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.browser.config.js",
"replaceDuplicatePlugins": true
},
...
I've named the custom webpack as webpack.browser.config.js.
Now, let say you have a server/..., which you're using for some backend stuff, then you won't have them accessible there. You need to install dotenv package and in the server/main.ts, let say that's your server's root, require this package, that way:
require('dotenv').config();
Note: until Angular 8 we were able to set up also webpack-server related logic, in a file such as webpack.server.config.js. Therefore, it was doable to apply basically same code related to dotenv, which was in webpack.browser.config.js. However, it doesn't work anymore. Angular CLI Builders are being used to build & server SSR apps instead.
Deploying to Firebase/using Cloud Functions for Firebase (and possibly other Serverless/FaaS)?
Then in your functions folder you need to paste the .env file as well. I assume here that from functions you're deploying.
For debugging I'd advise:
console.log(require('dotenv').config({ debug: true }));
Might save you a lot of time.

how to prevent lite-server from opening browser window on startup?

I'm using the lite-server with npm run lite
my config file,
module.exports = {
"server": { "baseDir": "./src" }
};
whenever I start the server, it opens up a new browser window. How do I prevent lite server opening browser window on server startup?
thanks.
It seems like browserSync has option open: false
https://www.browsersync.io/docs/options/#option-open
try in your bs-config.js
module.exports = {
"server": { "baseDir": "./src" },
"open": false
};
Or in bs-config.json in your project's folder:
{
"server": { "baseDir": "./src" },
"open": false
}
Lite-server uses
BrowserSync
And allows for configuration overrides via a local
bs-config.json
or
bs-config.js
file in your project.
The default behavior of the server serves from the current folder, opens a browser, and applies an HTML5 route fallback to ./index.html. so we need to set the configuration
For example, to change the server port, watched file paths, and base directory for your project, create a bs-config.json in your project's folder:
{
"port": 8000,
"files": ["./src/**/*.{html,htm,css,js}"],
"server": { "baseDir": "./src" }
}
So for browser not opening you have to set like this
{
"port": 8000,
"files": ["./src/**/*.{html,htm,css,js}"],
"server": { "baseDir": "./src" },
"open":false
}

JSPM System.import 404s

I am trying to learn JSPM as it seems like it is the future for installing client-side JavaScript. I am NOT attempting to use ES6 or TypeScript but am actually using CoffeeScript which I compile into 'standard' JavaScript for the browser. I am running node.js in express with my public files contained in ./public and accessible from the path /.
Having installed jspm my package.json configuration is:
"jspm": {
"directories": {
"baseURL": "public",
"packages": "public/lib"
}
}
It is configured like so:
System.config({
baseUrl: '/',
defaultJSExtensions: true,
transpiler: false,
paths: {}
});
With this setup I run: jspm install lodash which installs the package in public/lib/npm/lodash#4.5.1. In my application JavaScript I would expect to be able to run:
System.import('lodash');
and would expect that to return a Promise. However, I get a 404 on /lodash.js. So, in an effort to fix this I decided to use the explicit path to lodash: lib/npm/lodash#4.5.1/lodash. That seems to resolve the lodash 404 but then I get a 404 for /buffer.js and /process.js which I assume are dependencies of lodash.
Surely there has to be a better way than this? What am I missing here?! Part of the difficulty I am having is that most of the examples seem to use ES6 import directives which are irrelevant to me.
It seems that you are missing some paths on your systemjs config:
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: false,
paths: {
"github:*": "lib/github/*",
"npm:*": "lib/npm/*"
},
map: {
"lodash": "npm:lodash#4.6.1",
...
"npm:lodash#4.6.1": {
"buffer": "github:jspm/nodelibs-buffer#0.1.0",
"process": "github:jspm/nodelibs-process#0.1.2"
},
...
}
});
Also, you should have the lodash dependency declared on your package.json:
{
"jspm": {
"directories": {
"baseURL": "public",
"packages": "public/lib"
},
"dependencies": {
"lodash": "npm:lodash#^4.6.1"
}
}
}

Renaming the optimized files in requirejs folder level optimization

I'm using requirejs with Grunt in my project. I could able to successfully perform the folder level optimization through grunt-requirejs tool as below.
requirejs : {
std: {
options: {
mainConfigFile: 'src/js/main.js',
appDir: "src",
baseUrl: "js",
dir: "dist",
modules: [
{
name: "main"
}
],
removeCombined: true,
wrap: true,
almond: true,
replaceRequireScript: [{
files: ['dist/index.html'],
module: 'main'
}]
}
}
}
All the js files are concatenated and minified in main.js and css files in style.css. How can I rename these files main.js and style.css into something like app.min.js and app.min.css. Can I able to accomplish this using r.js or I've to use some external plugin?

Resources