babel enable import of each dir from root without relative - babeljs

My root dir structure is like so:
src
utils
types
clients
package.json
etc.
my current babel config i run is like:
{
presets: ['#babel/preset-env', '#babel/preset-typescript', '#babel/preset-react', '#babel/preset-flow'],
plugins: ['#babel/plugin-syntax-dynamic-import', '#babel/transform-runtime'],
env: {
build: {
ignore: ['**/*.spec.tsx', '**/*.spec.ts', '**/*.stories.tsx']
}
},
ignore: ['node_modules']
}
How do I allow various /src files directly imports from root. eg.
import { handyFunction } from 'utils'
import { api } from 'clients'
as opposed to doing this relatively:
import { handyFunction } from '../../../utils'
import { api } from '../../../clients'

You can use babel plugin module resolver as mentioned here https://www.npmjs.com/package/babel-plugin-module-resolver.

Related

Use process.env inside imported const in jest

I have a config file that exports some info for my app.
export const config: Config = {
isProd: process.env.NODE_ENV == 'production',
connection: {
port: parseInt(process.env.APP_PORT) || 2000,
},
};
And I want to import it and use inside my e2e jest test.
import {Test, TestingModule} from "#nestjs/testing";
import {INestApplication} from "#nestjs/common";
import * as request from "supertest";
import {AppModule} from "./../src/app.module";
import * as dotenv from "dotenv";
dotenv.config({path: ".env"});
import {config} from "../src/infrastructure/config/config"
console.log(process.env); // available here
console.log(config); // will return default values, not from .env
// ...
How can i make jest use env inside imported module?
Nestjs has great configuration modules that support .env:
https://docs.nestjs.com/techniques/configuration#custom-env-file-path
Makes it really easy to ref your configuration in all of your services as opposed to having to import.

Babel Not working for imports from node_modules

I just discovered RollUP and I am stuck with an issue where Babel does not run for imports from node_modules.
Here is an example:
My Javascript Code
import { _map } from "#varunsridharan/js-vars"
const myarray = _map.call([1,2,3,4],(x)=> x * 2);
console.log(myarray);
Rollup Config
import { babel } from '#rollup/plugin-babel';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import { uglify } from 'rollup-plugin-uglify';
import filesize from 'rollup-plugin-filesize';
import visualizer from 'rollup-plugin-visualizer';
export default {
input: './src/index.js',
output: {
file: './dist/myfile.min.js',
format: 'iife',
plugins: [
uglify( { mangle: true } ),
]
},
plugins: [
nodeResolve(),
babel(),
filesize(),
visualizer()
]
};
When I run rollup -c in CLI I get this output:
babelHelpers: 'bundled' option was used by default. It is recommended to configure this option explicitly, read more here: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers
198 | * Array Related Vars.
199 | */
> 200 | const Arr = Array;
| ^ Unexpected token: keyword «const»
201 | const _Arrayprop = Arr.prototype;
202 | const _filter = _Arrayprop.filter;
203 | const _push = _Arrayprop.push;
[!] (plugin uglify) Error: Unexpected token: keyword «const»
SyntaxError: Unexpected token: keyword «const»
at JS_Parse_Error.get (eval at <anonymous> (E:\localhost\www\javascript\dizzle\node_modules\uglify-js\tools\node.js:18:1), <anonymous>:69:23)
at reportError (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:107:11)
at reportClientError (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:87:10)
at execFunction (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:157:5)
at execHelper (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:139:5)
at execMethod (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:143:5)
at process.<anonymous> (E:\localhost\www\javascript\dizzle\node_modules\jest-worker\build\workers\processChild.js:64:7)
at process.emit (events.js:315:20)
at emit (internal/child_process.js:876:12)
at processTicksAndRejections (internal/process/task_queues.js:85:21)
Based on the output i was able to understand that babel did not run for the imported modules. so i checking the options provided for rollup babel plugin # (https://github.com/rollup/plugins/tree/master/packages/babel) and found that it has include AND exclude options and i tried with the below config
babel( {
include: [ "node_modules/#varunsridharan/*/**", "./src/**" ],
exclude: "node_modules/**",
} ),
Still, nothing happened so I tried without ./src/** in babel include config and found that babel is not running in my main javascript file which imports the node_modules's file
Node Module Project Link: https://github.com/varunsridharan/js-vars

AngularDart: How to configure routerProviders / routerProvidersHash for development and production environments?

There is one SO question about same problem. But I can't find production-ready code example how to use routerProviders / routerProvidersHash in real application.
As I understand we need to define two injectors and use one of them depending on compile time environment variable, like shown below.
// File: web/main.dart
// >>> Have to use 2 injectors:
#GenerateInjector([
routerProvidersHash,
ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injectorDev = self.injectorDev$Injector;
#GenerateInjector([
routerProviders,
ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injectorProd = self.injectorProd$Injector;
// <<<
void main() {
final env = ServerEnvironment();
if (env.isProduction) {
runApp(ng.AppComponentNgFactory, createInjector: injectorProd);
} else {
runApp(ng.AppComponentNgFactory, createInjector: injectorDev);
}
}
// File: lib/server_environment.dart
enum ServerEnvironmentId { development, production }
class ServerEnvironment {
ServerEnvironmentId id;
static final ServerEnvironment _instance = ServerEnvironment._internal();
factory ServerEnvironment() => _instance;
ServerEnvironment._internal() {
const compileTimeEnvironment = String.fromEnvironment('MC_ENVIRONMENT', defaultValue: 'development');
if (compileTimeEnvironment != 'development') {
id = ServerEnvironmentId.production;
} else {
id = ServerEnvironmentId.development;
}
}
bool get isProduction {
return id == ServerEnvironmentId.production;
}
}
File: build.production.yaml
targets:
$default:
builders:
build_web_compilers|entrypoint:
generate_for:
- web/main.dart
options:
compiler: dart2js
# List any dart2js specific args here, or omit it.
dart2js_args:
- -DMC_ENVIRONMENT=production
- --fast-startup
- --minify
- --trust-primitives
# Build execution
pub run build_runner build --config production --release -o web:build
Is the assumption of having two injectors is the right way to do?
Thank you in advance!
What I would do is make a different main.dart file for your different injector setup. You shouldn't have too much stuff in main.dart it should just serve as a mechanism to start your app. The branching should occur in build.production.yaml as specifying a different main for production (i.e. web/main_production.dart) and this file is the one with the non-hash route provider. This would remove the need for a "ServerEnvironment" and a if/else with a potentially confusing double injector setup in one file.
// File: web/main.dart
#GenerateInjector([
routerProvidersHash,
ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injector = self.injector$Injector;
void main() {
runApp(ng.AppComponentNgFactory, createInjector: injector);
}
and
// File: web/main_production.dart
#GenerateInjector([
routerProviders,
ClassProvider(Client, useClass: BrowserClient),
])
final InjectorFactory injector = self.injector$Injector;
void main() {
runApp(ng.AppComponentNgFactory, createInjector: injector);
}
with
File: build.production.yaml
targets:
$default:
builders:
build_web_compilers|entrypoint:
generate_for:
- web/main_production.dart
options:
compiler: dart2js
# List any dart2js specific args here, or omit it.
dart2js_args:
- --fast-startup
- --minify
- --trust-primitives
Ran as
# Build execution
pub run build_runner build --config production --release -o web:build

Babel 7 and babel-polyfill

After updating to babel 7 beta, looks like babel polyfill does not transpile before bundle. I updated all scoped packages like this one "#babel/polyfill": "7.0.0-beta.36". And changed imports for two files from import 'babel-polyfill' to import '#babel/polyfill'. How to use babel/pollyfill with babel env and babel 7. Should I use babel/polyfill when use useBuiltIns: 'usage', with targets?
.babelrc.js
const nodeEnv = process.env.NODE_ENV || 'development'
let presetEnvConfig, plugins
if (nodeEnv === 'test'){
presetEnvConfig = {targets: {node: 'current'}}
plugins = ['istanbul']
} else {
presetEnvConfig = {
targets: {
browsers: ['last 2 versions', 'ie >= 11']
},
modules: false
}
plugins = ['react-hot-loader/babel']
}
const config = {
presets: [
['#babel/preset-env', presetEnvConfig],
'#babel/react',
'#babel/stage-2'
],
plugins,
}
types.js
import keyMirror from '../../../utils/keyMirror'
export default keyMirror({
Unassign: null,
Reassign: null,
QuickAssignment: null,
}, 'TagAssignmentTypes')
index.js
<Assignment
assignee={assignee}
tagId={tagId && tagId.toString(16)}
assignmentType={assignmentTypes.Reassign}
onRequestClose={() => this.setState({isAssignmentInProgress: false})}
onChange={onChange}
/>
#babel/polyfill is a wrapper package which only includes imports of stable core-js features (in Babel 6 it also included proposals) and regenerator-runtime/runtime, needed by transpiled generators and async functions. This package doesn't make it possible to provide a smooth migration path from core-js#2 to core-js#3: for this reason, it was decided to deprecate #babel/polyfill in favor of separate inclusion of required parts of core-js and regenerator-runtime.
Instead of
import "#babel/polyfill";
you should use those 2 lines:
import "core-js/stable";
import "regenerator-runtime/runtime";
Don't forget install those dependencies directly!
npm i --save core-js regenerator-runtime
Change
#babel/stage-2 to #babel/preset-stage-2
The following worked for me, add
**.babelrc**
{
"presets": [
["#babel/env"]
]
}
**app.js**
import "core-js/stable";
import "regenerator-runtime/runtime";
*Install as pointed by gianmarco*
npm i --save core-js regenerator-runtime

Qbs: Can Module install files?

I want to have a module which will export all needed dependencies like include path, library path and will install needed runtime libraries.
Module {
Depends { name: "cpp" }
property path libLocation: ""
cpp.dynamicLibraries: [
"mylib"
]
cpp.staticLibraries: [
"mylib"
]
cpp.includePaths: [
libLocation + "include/",
]
cpp.libraryPaths: [
libLocation + "lib/",
]
Group {
name: "runtime libraries"
qbs.install: true
prefix: 'lib_location/'
files: ["*.dll"]
}
}
Everything works, but files are not installed. Is it possible to do that?
Update 1:
Files are correctly installed:
if full or relative paths are specified directly(as literals)
by using Project's properties.
Working solution:
Module {
...
Group {
name: "runtime libraries"
prefix: "D:/Projects/MyProject/Dependencies/SDL2pp/mingw/bin/" // works!
//prefix: project.dependenciesPath + "SDL2pp/mingw/bin/" // also works!
files: "*.dll"
qbs.install: true
}
}
But when I'm trying to use Module's property it says: "Reference Error: Can't find variable: ..."
Module {
...
property bool installDlls: true
property string libPath: ""
Group {
name: "runtime libraries"
prefix: libPath // Can't find variable
files: "*.dll"
qbs.install: installDlls // Can't find variable
}
}
Also, It is not work if FileInfo module is used for building a path. Outside the Group path was corectly resolved.
import qbs
import qbs.FileInfo
Module {
...
Group {
name: "runtime libraries"
prefix: FileInfo.joinPaths(project.dependenciesPaths, './SDL2pp/mingw/bin/') // silently not works
files: "*.dll"
qbs.install: true
}
}
Conclusion
I've found 2 solutuins of it:
hadrcoded path as a literal. Unportable solution
using Project's property. Portable, but depends on Project item.
I don't know why Module's properties can't be used inside a Group. Are there some limitations or it's a bug?
Late but found this post trying to do the same, maybe it helps other people.
Found out that using a Module's property inside a Group can be done by giving the Module an id and referencing the property using the id like this
Module {
id: mymodule
...
property bool installDlls: true
property string libPath: ""
Group {
name: "runtime libraries"
prefix: mymodule.libPath
files: "*.dll"
qbs.install: mymodule.installDlls
}
}
I'm using Qbs 1.12.1