How to add a plugin in Aurelia - plugins

I am trying to use wavesurfer.js in an Aurelia project. I am not able to use the wavesurfer.js. After building it says Container Element not found.
my app.js looks like this
import * as wavesurfer from '../node_modules/wavesurfer/dist/wavesurfer.js';
export class App {
wavesurferObj = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
scrollParent: true,
});
constructor() {
wavesurferObj.load('http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');
wavesurferObj.on(ready, function () {
wavesurferObj.play();
});
}
}
and my main.js looks like this
// regenerator-runtime is to support async/await syntax in ESNext.
// If you target latest browsers (have native support), or don't use async/await, you can remove regenerator-runtime.
import * as wavesurfer from '../node_modules/wavesurfer/dist/wavesurfer.js';
// import * as timeline from '../node_modules/wavesurfer/plugin/wavesurfer.timeline.js';
// import * as regions from '../node_modules/wavesurfer/plugin/wavesurfer.regions.js';
import 'regenerator-runtime/runtime';
import * as environment from '../config/environment.json';
import {
PLATFORM
} from 'aurelia-pal';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.feature(PLATFORM.moduleName('resources/index'));
aurelia.use.plugin(PLATFORM.moduleName('wavesurfer'));
// aurelia.use.plugin(PLATFORM.moduleName('timeline'));
// aurelia.use.plugin(PLATFORM.moduleName('regions'));
aurelia.use.developmentLogging(environment.debug ? 'debug' : 'warn');
if (environment.testing) {
aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing'));
}
aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app')));
}
and just the build section in Aurelia.json looks like this
"build": {
"options": {
"server": "dev",
"extractCss": "prod",
"coverage": false
},
"bundles": [{
"name": "vendor-bundle.js",
"dependencies": [{
"name": "wavesurfer",
"path": "../node_modules/wavesurfer/dist",
"main": "wavesurfer"
},
{
"name": "wavesurfer.timeline",
"path": "../node_modules/wavesurfer/plugin",
"main": "wavesurfer.timeline",
"deps": [
"wavesurfer"
]
},
{
"name": "wavesurfer.regions",
"path": "../node_modules/wavesurfer/plugin",
"main": "wavesurfer.regions",
"deps": [
"wavesurfer"
]
}
]
}]
},
Here is the error:
WaveSurfer is not defined.
Can someone indicate what is the right way to add this plugin please.
Thanks a lot in advance.

Without having a look at all of your actual code, i'm guessing you have at least 3 errors:
First one is using different variable names: wave surfer is imported as wavesurfer, but the way it's used is WaveSurfer, notice the case.
Using direct path to the dist file in a node_modules package:
import * as wavesurfer from '../node_modules/wavesurfer/dist/wavesurfer.js';
It should be:
import * as wavesurfer from 'wavesurfer';
3rd one is targeting an element via a CSS selector string #waveform. If this is not ready by the time you create an instance of class App, it will not work properly. Where is #waveform? from the document? from app.html? If it's from the document, it's ok, but if it's from app.html, you will need to change that code to something like this
<template>
....
<div ref="waveformElement"></div>
</template>
And in your app code:
import * as WaveSurfer from 'wavesurfer';
export class App {
bind() {
this.wavesurferObj = WaveSurfer.create({
container: this.waveformElement,
waveColor: 'violet',
progressColor: 'purple',
scrollParent: true,
});
this.wavesurferObj.load( 'http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');
this.wavesurferObj.on(ready, () => {
this.wavesurferObj.play();
});
}
}

Related

Unable to use Jest test in svelte component when carbon-icons-svelte is imported from inside node_modules error: Jest encountered an unexpected token

I would like to import an icon from package carbon-icons-svelte to my svelte component. It works very well in browser but I can't test this component. Testes worked good before import of carbon icons.
This is my configuration:
svelte.config.test.cjs
const preprocess = require('svelte-preprocess');
require('dotenv').config()
module.exports = {
preprocess: preprocess({
replace: [[/import.meta.env.([A-Z_]+)/, (importMeta) =>
{ return JSON.stringify(eval(importMeta.replace('import.meta', 'process')))} ]]
})
};
jest.config.cjs
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
transform: {
'^.+\\.svelte$': [
'svelte-jester',
{
preprocess: './svelte.config.test.cjs'
}
],
"^.+\\.(js)$": "babel-jest",
'^.+\\.(ts)$': [require.resolve('jest-chain-transform'),
{ transformers: ['../../../build-utils/importMetaTransformer.cjs', 'ts-jest'] }
]
},
testMatch: ["**/spec/**/*.js"],
moduleFileExtensions: ['js', 'ts', 'svelte'],
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"module": "es2020",
"lib": ["es2020", "DOM"],
"target": "es2019",
"importsNotUsedAsValues": "error",
"allowSyntheticDefaultImports": true,
"isolatedModules": true,
"resolveJsonModule": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"allowJs": true,
"checkJs": true,
"paths": {
"$/*": ["src/*"]
}
},
"include": [
"src/**/*.d.ts",
"src/**/*.js",
"src/**/*.ts",
"src/**/*.svelte",
"src/**/*.svelte-kit",
"./jest-setup.ts"
],
"exclude": ["node_modules"]
}
I have this information about an error in jest:
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/home/dev/src/iroco-app-client/node_modules/carbon-icons-svelte/lib/Information32/Information32.svelte:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<script>
^
SyntaxError: Unexpected token '<'
9 | import { createPopper } from '#popperjs/core';
10 | import Information32 from 'carbon-icons-svelte/lib/Information32/Information32.svelte';
> 11 |
| ^
I added to jest.config.test.cjs
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(carbon-icons-svelte))"]
after moduleNameMapper but still it doesn't work.
Thanks for your help.
running on node 16, i changed my babel to cjs and it worked for me, this is what it looks like
module.export = {
presets: [['#babel/preset-env', { targets: { node: 'current' } }], '#babel/preset-typescript']
};
my jest.config.js
const config = {
testEnvironment: 'jsdom',
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.ts$': 'ts-jest',
'^.+\\.svelte$': ['svelte-jester', { preprocess: true }]
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!(carbon-icons-svelte))',
'<rootDir>/node_modules/(?!(carbon-components-svelte))'
],
moduleFileExtensions: ['js', 'ts', 'svelte']
};
export default config;

Unable to resolve module when using babel module resolver + eslint + index files in react application

I am trying to use babel module resolver plugin with eslint + create react app but I am unable to start the application, getting the error
internal/modules/cjs/loader.js:1237
throw err;
^
SyntaxError: C:\Users\enisr\Desktop\projects\pcPartPicker\jsconfig.json:
Unexpected token } in JSON at position 166
at parse (<anonymous>)
I have set up a git repo showcasing the problem https://github.com/sgoulas/pcPartPicker
I have read the instructions in the docs and in the original repository and I am unable to configure it correctly.
My configuration files are the following:
.babelrc
{
"plugins": [
["module-resolver", {
"extensions": [
".js",
".jsx",
".es",
".es6",
".mjs"
],
"root": ["./src"],
"alias": {
"#components": "./src/components"
}
}
]
]
}
jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"],
"#components/*": ["./src/components/*"],
}
}
}
webpack.config.dev.js
var path = require("path");
module.exports = {
include: path.appSrc,
loader: require.resolve("babel-loader"),
options: {
plugins: [
[
"module-resolver",
{
root: ["./src/App"],
alias: {
"#components": "./src/components",
},
},
],
],
cacheDirectory: true,
},
};
My component:
import { GPUtable, CPUtable } from "#components/Tables";
const App = () => {
return (
<>
<GPUtable />
<CPUtable />
</>
);
};
export default App;
There are some minor fixes you need to make (below), but the main issue is that Create React App does not expose the webpack config, you'll need to eject to edit that.
npm run eject
Merge the babel configs: delete the babel key + value at the bottom of the package.json, and paste the value into your bablrc ("presets": ["react-app"],).
Add import React from 'react'; to the top of App.js
Confirmed locally that the app will run.
Other suggested fixes
Your jsconfig has a trailing comma after the array value in #components/*. You need to remove it because JSON doesn’t support them.
You need to fix the include path in weback.config.dev.js. appSrc isn't something defined on the node path module. Try using path.resolve(__dirname, 'src') - the example in their docs is creating/importing a paths object with appSrc pointing to this value.
You're missing test: /\.(js|jsx|mjs)$/, in webpack.config.dev.js.

Gatsby trailing slash redirect issue only on deployed version

In my Gatsby app, I want the following routes:
/branches - shows stores' branch locations.
/branches/:id - shows information about a particular branch.
To accomplish this, I have the following folder structure:
src
pages
branches
index.tsx
Inside index.tsx, I have:
import React from 'react'
import { Router } from '#reach/router'
const Comp = (props: { path: any }) => {
return <pre>{JSON.stringify(props, null, 2)}</pre>
}
export default () => {
return (
<Router>
<Comp path="/branches" />
<Comp path="/branches/:id" />
</Router>
)
}
(The Comp component is there just to show the functionality is working.)
In my gatsby-node.js file, I have this:
// Implement the Gatsby API “onCreatePage”. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
// page.matchPath is a special key that's used for matching pages
// only on the client.
if (page.path.match(/^\/branches/)) {
page.matchPath = '/branches/*'
// Update the page.
createPage(page)
}
}
So the result is that when I am running gatsby develop, everything works as expected. I can visit /branches and /branches/4 and I see what I expect, the Comp component displaying some routing information:
{
"path": "/branches",
"uri": "/branches",
"location": {
"pathname": "/branches/",
"search": "",
"hash": "",
"href": "http://localhost:1337/branches/",
"origin": "http://localhost:1337",
"protocol": "http:",
"host": "localhost:1337",
"hostname": "localhost",
"port": "1337",
"state": null,
"key": "initial"
}
}
However, when running deploying to S3 using gatsby build && gatsby-plugin-s3 deploy --yes, I get into a redirect loop:
What is the issue here and how can I resolve it?
(I have experimented with the gatsby-plugin-force-trailing-slashes and gatsby-plugin-remove-trailing-slashes plugins to no avail)

Mocking a class in typescript with jest

I am trying to unit test (with Jest) my handler module that makes use of a summary class.
My original summary class looks like:
import DynamoDBClient from './ddbClient/DynamoDBClient'
import { DynamoDB } from 'aws-sdk'
import { iSummaryReader, iObsSummariesAttributes } from './Summary.d'
import { JSONAPIResource } from '../JSONAPIResponse'
export default class Summary {
reader: iSummaryReader
constructor(reader: iSummaryReader) {
this.reader = reader
}
getSummary = async (keyName: string, keyValue: string): Promise<JSONAPIResource<iObsSummariesAttributes>> => {
return new Promise<JSONAPIResource<iObsSummariesAttributes>>((resolve, reject) => {
const gettingItem = this.reader.getItem(keyName, keyValue)
console.log(gettingItem)
gettingItem.then((resp) => {
resolve(resp)
}).catch((err: Error) => {
reject(err.message)
})
})
}
}
In my handler module I import with import Summary from './lib/Summary'
(Note: same line is used in handler.test.ts
Inside the handler function
try {
const dynamodbObj: iSummaryReader = new DynamoDBClient(documentClient, someTable)
const summary = new Summary(dynamodbObj)
const data: JSONAPIResource<iObsSummariesAttributes> = await summary.getSummary('id', someID)
}
My results depend on my approach if try an automatic mock
jest.mock('./lib/Summary', () =>
{
return {
getSummary: jest.fn()
}
})
I get the error
TypeError: Summary_1.default is not a constructor
If I create a manual mock under lib/__mocks__/Summary.ts with jest.mock('./lib/Summary') it does work until I get the point
expect(Summary).toHaveBeenCalledTimes(1)
Where it complains about me not being able to do this on summary. I also am unable to access my method to test that they are being called this way.
Note: My hanlder is for a lambda function so I am unable to inject the class that way where I have successfully tested that I can mock an injected class.
EDIT
The tsconfig.json is:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build",
"declaration": false,
"target": "es2015",
"moduleResolution": "node",
"module": "commonjs",
"noImplicitReturns": true,
"noImplicitThis": true,
"strictNullChecks": true,
"alwaysStrict": true,
"lib": [
"dom",
"es2015.promise",
"es2017.object",
"es2016"
],
},
"include": [
"src/**/*.ts"
],
}
I do not know why this was failing, but I the following steps seem to work to fix it.
Change the class export from default
From
`export default class Summary {`
to
`class summary`
+ export = summary at the end
Use import = require to import it.
import Summary = require('./lib/Summary')
Those two changes allowed it to find the jest.mock.

Target [Illuminate\Contracts\Routing\ResponseFactory] is not instantiable

I am trying to return a response like this:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
however, I got error:
Target [Illuminate\Contracts\Routing\ResponseFactory] is not instantiable.
Any idea?
Here is my composer.json:
{
"name": "laravel/lumen",
"description": "The Laravel Lumen Framework.",
"keywords": [
"framework",
"laravel",
"lumen"
],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.5.9",
"laravel/lumen-framework": "5.2.*",
"vlucas/phpdotenv": "~2.2",
"generationtux/jwt-artisan": "^0.1.7",
"barryvdh/laravel-cors": "^0.8.0",
"neomerx/cors-illuminate": "^1.1",
"fenos/notifynder": "3.1.*",
"franzose/closure-table": "^4.1",
"mlntn/lumen-artisan-serve": "~1",
"guzzlehttp/guzzle": "~6.0",
"league/flysystem": " ~1.0",
"bugsnag/bugsnag-laravel": "^2.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"phpunit/phpunit": "~4.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"GuzzleHttp\\": "/vendor/guzzlehttp/"
},
"classmap": [
"database/"
]
},
"autoload-dev": {
"classmap": [
"tests/",
"database/"
]
},
"config": {
"preferred-install": "dist"
}
}
I still get the error in 2020. Here's an updated version of the solution by #sunben:
In bootstrap/app.php, uncomment the following line
$app->register(App\Providers\AppServiceProvider::class);
Then in app\Providers\AppServiceProvider.php, update register method to add:
$this->app->singleton(\Illuminate\Contracts\Routing\ResponseFactory::class, function() {
return new \Laravel\Lumen\Http\ResponseFactory();
});
Might be late but found the solution.
In bootstrap/app.php, uncomment the following line
$app->register(App\Providers\AppServiceProvider::class);
Then in app\Providers\AppServiceProvider.php, update register method to add:
public function register()
{
$this->app->singleton('Illuminate\Contracts\Routing\ResponseFactory', function ($app) {
return new \Illuminate\Routing\ResponseFactory(
$app['Illuminate\Contracts\View\Factory'],
$app['Illuminate\Routing\Redirector']
);
});
}
The response helper may be used to conveniently generate other types of response instances. When the response helper is called without arguments, an implementation of the Laravel\Lumen\Http\ResponseFactory class is returned.
use Laravel\Lumen\Http\ResponseFactory;
Try like this
public function register() { $this->app->singleton(\Illuminate\Contracts\Routing\ResponseFactory::class, function() { return new \Laravel\Lumen\Http\ResponseFactory(); }); $this->app->bind(\Illuminate\Contracts\Routing\UrlGenerator::class, function ($app) { return new \Laravel\Lumen\Routing\UrlGenerator($app); }); }
call
use Tests\TestCase;
instead of
use PHPUnit\Framework\TestCase;
your function depends on another function, So you should extend like feature test and not unit tests.
Those who are still getting routing related error, just put the following line in your composer.json file and run the command composer update
"illuminate/routing": "^5.6"
composer update
and boom here we go, wish all things are working great now
https://stackoverflow.com/a/48678862/9751944
#sunben's answer worked for me but I added the following inside the register method
$this->app->bind(\Illuminate\Routing\RouteCollectionInterface::class, function ($app) { return new \Illuminate\Routing\RouteCollection; });