How to use installed modules in aurelia - aurelia

I am using the skeleton-typescript sample and work through the documentation. I am trying to set up a value converter with numeral as it is shown in the docs.
import numeral from 'numeral';
export class CurrencyFormatValueConverter {
toView(value) {
return numeral(value).format('($0,0.00)');
}
}
I have installed numeral via jspm install numeral. It is added package.json within the jspm dependencies and I manually added it to bundles.js.
After saving the typescript file I get the error: Cannot find module 'numeral'.. What am I missing?

You need d.ts for numeral.js. and since there is no d.ts on Typings this can resolve problem:
$ jspm install npm:#types/numeral.
It works in my skeleton with value converters. Import can be done like import * as numeral from 'numeral';

You should add it in your configuration like:
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('numeral');
aurelia.start().then(() => aurelia.setRoot());
}
You will find the exact package names in your package.json:
jspm": {
"dependencies": {
...
"numeral": "xxxx"
...
}
}

Related

astro-i18next Tfunction showing keys instead of translation

I use t() function to translate text.
The function is acting like there are no locales in astros /public folder.
My file structure
My translation.json file for en:
{
"index": {
"testHeader": "Test Header"
}
}
Here is my index page code:
---
import Layout from "../layouts/Layout.astro";
import { t, changeLanguage } from "i18next";
changeLanguage("en");
---
<Layout>
<h1>{t("index.testHeader")}</h1>
</Layout>
My astro-i18next.config.mts:
/** #type {import('astro-i18next').AstroI18nextConfig} */
export default {
defaultLocale: "en",
locales: ["en", "cs"],
};
My astro.config.mjs:
import { defineConfig } from 'astro/config';
import astroI18next from "astro-i18next";
import tailwind from '#astrojs/tailwind';
// https://astro.build/config
import react from "#astrojs/react";
// https://astro.build/config
export default defineConfig({
integrations: [astroI18next(), react(), tailwind({
config: './tailwind.config.cjs',
})]
});
the t() function shows the passed key instead of translation.
I runned npx astro-i18next generate which did nothing
I had a similar issue; I fixed it with a config change and a downgrade.
(since it's still in beta, gotta keep an eye on that)
NOTE: The current version of "astro-i18next" is "1.0.0-beta.17".
Add the following to your astro-i18next.config.*: baseLanguage: "en"
Downgrade your version to 1.0.0-beta.13, between versions 10 to 17 only this one worked for me.
Good but not Necessary: add this to your package.json scripts: "i18n": "npx astro-i18next generate"
Run this command and should be successful: pnpm i && pnpm run i18n && pnpm run build
Considering this fix, I'm looking forward for similar issues to be resolved in stable release; However, for the time being this should get you going.
I fixed it using npm update.
For some reason my app's dependencies weren't updated.

How to use npm package dependency

I am learning to create npm packages by creating a session check function sessionFn that will popup a modal 1 minute before the session expires.
The function works as expected on the main app (a nuxtJS app) but when I make use it as an npm module I have to pass moment as an argument even though moment is listed as a dependency and is imported on the module.
I am missing something, why is my module not picking up moment? I want to use the module like sessionFn(this, to.path); instead of sessionFn(this, to.path, moment); moment is undefined when I don't pass it
Package files
package.json
{
"name": "hello-stratech",
"version": "1.0.17",
"description": "Hello Stratech",
"main": "index.js",
"keywords": [
"npm",
"hello",
"stratech"
],
"author": "Simo Mafuxwana",
"license": "ISC",
"dependencies": {
"moment": "^2.22.2"
}
}
index.js (main js file)
import moment from "moment";
module.exports = {
greeting(name) {
alert("Hello.. " + name);
},
department(dev) {
...
},
sessionFn(context) {
const exp = context.$store.state.session.exp;
let userSystemTime = new Date();
userSystemTime = moment.utc(userSystemTime)
const diff = moment(userSystemTime).diff(moment(exp), 'minutes');
if (diff = 1) {
// open modal
}
}
}
Usage
This is how I use the package in the main app
import moment from 'moment';
import { sessionFn } from "hello-stratech";
export default {
...
watch: {
$route(to) {
sessionFn(this, to.path, moment);
}
}
...
}
You dont need to import and pass moment into your function since you are importing it in your function file. You are not even using the passed argument in your function. So you can just safely dont pass it. You are also not using second argument that u pass to.path, so u can omit it too.
As a suggestion you should install and use eslint, which will catch such things. You can setup a nuxt project with eslint using create nuxt app for example.
There is also a bug in esm 3.21-3.22 that prevent commonjs and es6 imports work together https://github.com/standard-things/esm/issues/773 . That should be fixed when a new esm will be released
Try making moment as devDependancy through npm i moment --save-dev instead of dependency.
That way moment will only be needed when the package is development (means when you are developing the project) but not when it is used.
Hope it fixes your issue
for more depth knowledge

pass environment variables during babel build phase for importing different files

I'm building a web (react with webpack & babel) and mobile apps (react-native with expo) for a project. I therefore created a common library for business logic and redux/api library.
Some code will be slightly different between web and mobile. In my case it's localStorage vs AsyncStorage, which I use for authentication among other things...
I'm trying to pass an environment variable for the build stage to switch import of certain files so that the correct file is loaded for each build which are simply path linked (ie no pre-build of my library, I just do import '../mylib') ex:
if(PLATFORM === 'mobile'){
import StorageModule from './mobile-storage-module`
} else {
import StorageModule from './mobile-storage-module`
}
export default StorageModule
Try 1
#babel/preset-env to say if it's mobile or web so that it imports different libraries depending on build like so:
My .babelrc has this:
{
"presets": [
[
"#babel/preset-env",
{
"platform": "mobile"
}
]
]
}
And then in local storage file I do this:
export default () => {
const platform = process.env.platform
if (platform === 'mobile') {
return import './storage-modules/storage-mobile'
}
return import './storage-modules/storage-web'
}
That didn't work, and this also didn't work for me.
Try 2
I installed react-native-dotenv and created a .env file with:
PLATFORM=mobile
And set the plugin in my .babelrc:
{
"presets": [
"babel-preset-expo",
"react-native-dotenv"
]
}
And in my example file, I tried this:
import { PLATFORM } from 'react-native-dotenv'
export default PLATFORM === 'mobile' ? import './storage-modules/storage-mobile' : import './storage-modules/storage-web'
But now my build doesn't work. Any idea how I do dynamic imports during the build process that works for babel in react-native app and webpack build (also uses babel)?
First, #babel/preset-env does not do what you think it does. This is not for specifying your own variables, it is a plugin to automatically use the right target and pollyfills for the browsers you want to support.
The easiest way to get environment variables is with the webpack define plugin (which is part of webpack, so no need to install anything extra)
Just add this to your webpack config.
plugins: [
new webpack.DefinePlugin({
'process.env': {
platform: 'mobile',
},
}),
],
Next, you can't use normal import statements inside of ifs.
import gets resolved before any code runs, either on build by webpack, or in supported environments on script load.
To import something on runtime, you need to use dynamic imports.
Here is an example of how this could look like.
export default new Promise(async resolve => {
resolve(
process.env.platform === 'mobile'
? (await import('./mobile.js')).default
: (await import('./desktop.js')).default
);
});
You can now import from this file like you normally would, but be aware that the default export is a promise.
As your question's title says "during babel build phase", I assume you would like to make different builds for desktop and mobile (not one build for both and load the needed modules dynamically run-time). So I would go like this:
Define the run scripts in package.json for desktop and mobile:
"scripts": {
"devmobile": "cross-env NODE_ENV=development PLATFORM=mobile webpack --progress",
"dev": "cross-env NODE_ENV=development webpack --progress",
}
... or you can create two different webpack.config.js files for desktop and mobile builds but I think the above is easier...
Then npm run devmobile to build for mobile and npm run dev for desktop.
Since I'm on Windows I use the cross-env package but this is the recommended way to be OS independent.
Then I would use Webpack's NormalModuleReplacementPlugin:
(based on this exmaple)
In your webpack.config.js:
// defining the wanted platform for the build (comfing form the npm run script)
const targetPlatform = process.env.PLATFORM || 'desktop';
// then use the plugin like this
plugins: [
new webpack.NormalModuleReplacementPlugin(/(.*)-PLATFORM(\.*)/, function(resource) {
resource.request = resource.request.replace(/-PLATFORM/, `-${targetPlatform}`);
}),
]
...then if you have these two files:
./storage-modules/storage-mobile.js
./storage-modules/storage-desktop.js
import the needed one in your script like this:
import './storage-modules/storage-PLATFORM';
This way the generated build will only contain the needed file for the current PLATFORM used for the build process.
Another possible solution could be the ifdef-loader but I haven't tested it. Maybe worth to try, seems easy.
If you want one build though and import the needed module dynamically, you could do something like this in your app.js (or whatever):
// this needs to have defined when the app is running
const targetPlatform = process.env.PLATFORM || 'desktop';
import(
/* webpackChunkName: "[request]" */
`./storage-modules/storage-${targetPlatform}`
).then(storageModule => {
// use the loaded module
});
or:
(async () => {
const storageModule = await import(
/* webpackChunkName: "[request]" */
`./storage-modules/storage-${targetPlatform}`
);
// use the loaded module
})();
For this to work Babel has to be configured.
More on Webpack with dynamic imports here.
You can use transform-inline-environment-variablesto pass platform to babel
"build-mobile": "PLATFORM=mobile ...",
"build-app": "PLATFORM=app ...",

Angular5 / Webworker - Tried to find bootstrap code, but could not

I try to follow all these tutorials about webworker, but no one works. This is one of them: https://blog.angularindepth.com/angular-with-web-workers-step-by-step-dc11d5872135
I follow step by step but after I run npm start I get a
ERROR in Error: Tried to find bootstrap code, but could not. Specify either statically analyzable bootstrap code or pass in an entryModule to the plugins options.
at Object.resolveEntryModuleFromMain (D:\PROJECTS_TIQ\w3\worky\node_modules\#ngtools\webpack\src\entry_resolver.js:121:15)
at Promise.resolve.then.then (D:\PROJECTS_TIQ\w3\worky\node_modules\#ngtools\webpack\src\angular_compiler_plugin.js:240:54)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at Function.Module.runMain (module.js:678:11)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
this is my main.ts .. I think the problem is here, but what..?
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { bootstrapWorkerUi } from '#angular/platform-webworker';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapWorkerUi('webworker.bunde.js')
.catch(err => console.log(err));
also.. this tutorial talks about some kind of AotPlugin that should be in the webpack.config.js .. but when I do npm eject there is no AotPlugin imported in the confg(?)

Skeleton Plugin / Module Not found Issue after build

I created a plugin and I uploaded to NPM by using this skeleton. When I try to use it the module is not found:
import 'aurelia-virtual-scroll';
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-virtual-scroll');
My plugin index.js file looks like below:
export function configure(config) {
config.globalResources('./aurelia-virtual-scroll');
}
In the same folder I have that aurelia-virtual-scroll.js file.
The error I display is the one below:
Error: Cannot find module './aurelia-virtual-scroll/aurelia-virtual-scroll'.
at webpackContextResolve....
Should this happen? Am I missing something?
Here is my base code for the plugin.
And here is the skeleton for webpack where I am trying to use it
your class needs to be imported/exported in the index and you don't need to import it in the main file.
import { PLATFORM } from 'aurelia-pal';
export { AureliaVirtualScroll } from './aurelia-virtual-scroll';
export function configure(config) {
config.globalResources(PLATFORM.moduleName('./aurelia-virtual-scroll'));
}