Access app.js function in adonisjs edge template - frontend

Can somebody explain to me how you access a function in the .edge template from the app.js file?
In resources/js/app.js I have
function myFunc() {
console.log("works???")
}
In the edge template I have
Some click
And I get the error
VM6192 :19 Uncaught ReferenceError: myFunc is not defined
at HTMLAnchorElement.onclick (VM6192 :19)
Note that I have the
<!-- Renders scripts -->
#entryPointScripts('app')
And the function is in the http://localhost:8080/assets/app.js path
I did manage to do something like window.myFunc = myFunc, inside app.js, but I need to call some async functions and I want the already compiled functions by webpack.

It seems that you do either:
map your function to window, in the app.js file (window.myFunc = myFunc), or
add an eventListener to the button you want
document.getElementById('my-btn').addEventListener('click', myFunc);
In order to make es6 work, with features like async/await, you need to add babel;
install the babel polyfill: https://babeljs.io/docs/en/babel-polyfill#installation
install core-js: https://github.com/zloirock/core-js#installation
create a .babelrc file with this configuration
{
"presets": [
[
"#babel/env",
{
"targets": {
"edge": "17",
"firefox": "60",
"chrome": "67",
"safari": "11.1"
},
"useBuiltIns": "usage",
"corejs": "3.16"
}
]
]
}
run node ace serve --watch again

Related

Nestjs: Repl with monorepo mode

I have a nest app that is using monorepo mode. I would like to take advantage of the new repl feature that was released in nest 9.0+.
My directory structure looks as such:
apps/
--inventory-ops/src/app.module
--ticket-office/src/app.module
I have followed the instructions found in the docs creating a repl.ts, but when I run the repl commannd:
npm run start -- --entryFile repl
I get this error output:
Error: Cannot find module '/dist/apps/ticket-office/repl'
Looking at my dist folder, the only build target is main.js, which would explain it not being able to find the repl module. Do I need to update something in my webpack config to make sure repl.ts gets built as well? Any help would be appreciated.
I managed to solve this by adding a new project in nest-cli.json, for example:
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "#nestjs/schematics",
"sourceRoot": "apps/gateway/src",
"monorepo": true,
"root": "apps/gateway",
"compilerOptions": {
"webpack": true,
"tsConfigPath": "apps/gateway/tsconfig.app.json"
},
"projects": {
"gateway": {
"type": "application",
"root": "apps/gateway",
"entryFile": "main",
"sourceRoot": "apps/gateway/src",
"compilerOptions": {
"tsConfigPath": "apps/gateway/tsconfig.app.json"
}
},
"ticket-office": {
"type": "application",
"root": "apps/ticket-office",
"entryFile": "main",
"sourceRoot": "apps/ticket-office/src",
"compilerOptions": {
"tsConfigPath": "apps/ticket-office/tsconfig.app.json"
}
},
"ticket-office:repl": { // <<--- HERE
"type": "application",
"root": "apps/ticket-office",
"entryFile": "repl", // <<-- HERE
"sourceRoot": "apps/ticket-office/src",
"compilerOptions": {
"tsConfigPath": "apps/ticket-office/tsconfig.app.json"
}
},
}
}
Then you can run nest start ticket-office:repl
I hope this helps.
EDIT:
Adapted the answer to your question.
Try to run this:
nest start <your-app> --config nest-cli.json --debug --watch -- --entryFile repl
I faced the same issue and this worked for me.
I don't really know why NestJS take repl file into consideration for building only when explicitly the cli config is provided. It's probably a bug with the CLI.
Alternative
Also, you can add a custom parameter to your command and start the REPL mode conditionally:
script:
nest start <your-app> --watch repl
main.ts file:
async function bootstrap() {
if (process.argv[process.argv.length - 1] === 'repl') {
return repl(AppModule);
}
// Non REPL mode Nest app initialisation
...
}
bootstrap();

JEST with Handlebars configuration

I am trying to add Jest to existing project and i have problem with configuration.
To solve problem with modules and es6 i added rollup-jest package (we are using rollup on our project)
To solve problem with handlebars i tried to use jest-handlebars package but i got problem
Code transformer's `process` method must return an object containing `code` key
with processed string. If `processAsync` method is implemented it must return
a Promise resolving to an object containing `code` key with processed string.
Code Transformation Documentation:
https://jestjs.io/docs/code-transformation```
Has anybody aby similar problem with jest plus handlebars configuration or can anybody help me with code transformator?
EDIT:
i added preprocessor.js file with:
module.exports = {
process(src) {
const code = `
const Handlebars = require('handlebars');
module.exports = Handlebars.compile(\`${src}\`);
`
return {
code: code
};
},
};
and change my packaged.json to:
``` "jest": {
"preset": "rollup-jest",
"collectCoverage": true,
"modulePaths": [
"./",
"./node_modules"
],
"moduleFileExtensions": [
"js",
"hbs",
"ts"
],
"transform": {
"\\.js$": "rollup-jest",
"^.+\\.hbs$": "<rootDir>/jestHbsTransformer.js",
"^.+\\.ts?$": "ts-jest"
}
}
}```
and it is still not working ;)
enter code here

Make "import/extensions" require the .js extension in a Node.js TypeScript project

First of all, some facts:
Node.js requires that all local imports include the imported module's extension (e.g. import hello from './hello.js', not import hello from './hello').
TypeScript will compile imports with or without the .js extension, which means a missing .js extension is a runtime error.
TypeScript doesn't transform imports to add the .js extension or convert .ts to .js.
In my Node.js project, I want to make missing a missing .js extension be a build-time error using the import/extensions ESLint rule. However, when I enable this rule using the following configuration:
{
"root": true,
"env": {
"node": true
},
"parser": "#typescript-eslint/parser",
"plugins": [
"#typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:#typescript-eslint/eslint-recommended",
"plugin:#typescript-eslint/recommended"
],
"settings": {
"import/resolver": {
"typescript": {},
"node": {
"extensions": [".js"]
}
}
},
"rules": {
"import/extensions": ["error", "ignorePackages"]
}
}
running eslint gives me the following error:
/sandbox/src/index.ts
1:19 error Missing file extension "ts" for "./hello.js" import/extensions
Source files:
// index.ts
import hello from "./hello.js";
hello();
// hello.ts
export default function hello() {
console.log("Hello");
}
CodeSandbox link: https://codesandbox.io/s/elated-germain-13glp7
I fixed this with the following config:
{
"root": true,
"env": {
"node": true
},
"extends": [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:#typescript-eslint/eslint-recommended",
"plugin:#typescript-eslint/recommended"
],
"rules": {
"import/extensions": ["error", "ignorePackages"],
"import/no-unresolved": "off"
}
}
The main thing is to disable the "import/no-unresolved" rule and remove "settings"."import/resolver"."node". ("import/no-unresolved" is redundant as unresolved imports are resolved at the compilation stage.) Other items removed here were already being added as a result of extending the #typescript-eslint plugins.
I found an eslint plugin that can fix missing .js extensions for imports in .ts files, instead of just showing an error:
https://github.com/AlexSergey/eslint-plugin-file-extension-in-import-ts
https://www.npmjs.com/package/eslint-plugin-file-extension-in-import-ts
Install:
npm i -D eslint-plugin-file-extension-in-import-ts
Add to .eslintrc file:
{
"plugins": [
"file-extension-in-import-ts"
],
"rules": {
"file-extension-in-import-ts/file-extension-in-import-ts": "error"
}
}
NOTE: I ran into an issue similar to https://github.com/import-js/eslint-plugin-import/issues/1292 when using this package, and it will incorrectly try to add .js extensions on these paths when fixing automatically.
You could try ts-add-js-extension package to append .js extension to the transpiled JavaScript files. After you install you can do
ts-add-js-extension add --dir={your-transpiled-outdir}

Testing svelte components with import.meta.env

I'm struggeling now for a couple of days to get my testsetup running. Rough outline: Vite, Svelte (with ts), Jest.
I'm using import.meta.env.SOMENAME for my environment vars although this works fine for development as soon as a component uses import.meta.env the test will fail with:
SyntaxError: Cannot use 'import.meta' outside a module
I've tried different transformers, babel-plugins and configs but never succeeded...
My jest config:
"jest": {
"globals": {
"ts-jest": {
"isolatedModules": true
}
},
"verbose": true,
"transform": {
"^.+\\.svelte$": [
"svelte-jester",
{
"preprocess": true
}
],
"^.+\\.ts$": "ts-jest",
"^.+\\.js$": "babel-jest"
},
"setupFilesAfterEnv": ["<rootDir>/setupTests.ts"],
"moduleFileExtensions": ["js", "ts", "svelte"]
}
babel.config.js
module.exports = {
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current"
}
}
]
]
};
svelte.config.cjs
const sveltePreprocess = require('svelte-preprocess')
module.exports = {
emitCss: true,
preprocess: sveltePreprocess()
};
Among other things I tried to use #babel/plugin-syntax-import-meta but ended up with the same error. Also vite-jest looked very promising but again I couldn't make it work.
I appreciate every hint I can get. If I can provide any additional info please let me know. Also my knowledge of vite and babel is very limited so REALLY appreciate any help IU can get on this topic.
Update (Solution)
So If you use babel you could use babel-preset-vite. The approach with esbuild-jest from Apu is also good solution that many people use. Unfortunately those things didn't work for me so I decided to use a workaround with vite's define.
This workaround consists of two steps.
replace import.meta.env with process.env (if this is a deal breaker for you then I hope you have luck with the solutions above) You only have to replace the instances in files you want to test with jest.
Update Vite config with define. This step is necessary or your build will break (dev will still work)
vite.config.js
const dotEnvConfig = dotenv.config();
export default defineConfig({
define: {
"process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
"process.env.VITE_APP_SOMENAME": `"${process.env.VITE_APP_SOMENAME}"`
},
...
)};
I know this is just a workaround but maybe this helps someone. Thanks & Good Luck.
A more recent alternative to Jest that understands import.meta.env is Vitest.
It should require almost no additional configuration to get started and it's highly compatible with Jest so it requires few changes to the actual tests.
The advantages of Vitest over Jest for this use case are:
It's designed specifically for Vite and will process tests on demand
It will reuse your existing Vite configuration:
Any define variables will be replaced as expected
Extensions that Vite adds to import.meta will be available as usual
I was having issues with svelte component testing as well using jest. babel is not good at resolving import.meta. I used esbuild-jest to transform both ts and js files. It solves the issue with the import.meta. Here is my jest.config.cjs.
npm i esbuild esbuild-jest -D
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');
const config = {
"transform": {
"^.+\\.svelte$": [
"svelte-jester",
{
"preprocess": true
}
],
"^.+\\.(ts|tsx|js|jsx)$": ["esbuild-jest"]
},
"moduleFileExtensions": [
"js",
"ts",
"tsx",
"svelte"
],
"setupFilesAfterEnv": [
"#testing-library/jest-dom/extend-expect"
],
"collectCoverageFrom": [
"**/*.(t|j)s",
"**/*.svelte"
],
coverageProvider: 'v8',
"coverageDirectory": "./coverage",
"coveragePathIgnorePatterns": [
"/node_modules/",
"/.svelte-kit/"
],
"moduleNameMapper": pathsToModuleNameMapper(compilerOptions.paths, {prefix: '<rootDir>/'})
};
module.exports = config;

Trying to build Jest is throwing "Caching was left unconfigured."

I have the following .babelrc.js in the root folder:
{
"plugins": [
"#babel/plugin-transform-flow-strip-types",
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-strict-mode",
"#babel/plugin-transform-runtime"
],
"cache": "true"
}
but when it tries to run node ./packages/jest-cli/bin/jest.js I see:
Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
for various types of caching, using the first param of their handler functions:
What am I missing?
Use new babel.config.js
https://new.babeljs.io/docs/en/next/babelconfigjs.html
module.exports = function(api) {
api.cache(true)
return {
plugins: [
"#babel/plugin-transform-flow-strip-types",
"#babel/plugin-transform-modules-commonjs",
"#babel/plugin-transform-async-to-generator",
"#babel/plugin-transform-strict-mode",
"#babel/plugin-transform-runtime"
]
}
}

Resources