Nuxt 3 "component library" module does not expose mixins of exported components in NX monorepo - mixins

I'm facing a problem with my Nuxt 3 component library.
It contains several Vue components which are then added to the exported components
export const useComponents = (nuxt: Nuxt) => {
const __dirname = dirname(fileURLToPath(import.meta.url));
let componentsDirectory = join(__dirname, "../", '/components');
nuxt.hooks.hook("components:dirs", (dirs) => {
dirs.push({
path: join(componentsDirectory, "../", 'atoms'),
prefix: 'base',
});
dirs.push({
path: join(componentsDirectory, "../", 'layout'),
prefix: 'base',
});
dirs.push({
path: join(componentsDirectory, "../", 'molecules'),
prefix: 'base',
});
})
}
However, some of those components are using mixins, which are located next to the components and relatively imported.
When using that component library in my application, it does not find the mixins and I'm getting this exception:
when using import loginButtonsMixing from "~/src/molecules/loginButtonsMixing.js";
[vite:load-fallback] Could not load
/home/user/workspace/my-project/apps/my-app/molecules/loginButtonsMixing.js
(imported by
../../../libs/general/base/src/molecules/LoginButtons.vue): ENOENT: no
such file or directory, open
'/home/user/workspace/my-project/apps/my-app/molecules/loginButtonsMixing.js'
It looks inside the app directory, instead of the library directory.
And when I'm using import loginButtonsMixing from "./loginButtonsMixing.js";
Could not resolve './loginButtonsMixing.js' from
../../../libs/base/src/molecules/LoginButtons.vue at error
(/home/user/workspace/my-project/node_modules/rollup/dist/es/shared/rollup.js:1858:30)
at ModuleLoader.handleResolveId
(/home/user/workspace/my-project/node_modules/rollup/dist/es/shared/rollup.js:22156:24)
at
/home/user/workspace/my-project/node_modules/rollup/dist/es/shared/rollup.js:22119:26
The path looks more or less correct, but rollup seems to fail.
How do I tell the Nuxt module to expose them as well?

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.

url-loader without webpack?

I have a component library that will be shipping with a few small assets (images). Those assets are imported into various components in the library.
The build script uses babel (without webpack) to transpile the js(x) to a build directory, and is currently dumping the images into build/assets/images.
This works when testing the build, but when using the component in another project (using webpack) the component tries to refer the node_modules folder:
Example component:
import myImage from './assets/images/myImage.png';
const MyComponent = () => (
<img src={myImage} />
);
export MyComponent;
Usage:
import MyComponent from 'myLibrary/MyComponent';
export default () => (
<MyComponent />
);
The error message:
myImage.png:1 GET http://localhost:9001/node_modules/myLibrary/assets/images/myImage.png 404 (Not Found)
As I understand the 'best' way to include assets is to use the url-loader so they're converted to data uri's. However, trying to use the url-loader without Webpack isn't working:
babel.config.js
...
plugins: [
[
"url-loader",
{
"extensions": ["png", "jpg", "jpeg", "gif", "svg", "pdf"],
"limit": 0
}
]
]
...
Error: Cannot find module 'babel-plugin-url-loader'
I found this and it works for PNG and SVG files - worked perfectly for what I needed!
https://www.npmjs.com/package/babel-plugin-inline-import-data-uri

Jest: Cannot use import statement outside a module

I got an error when I run test using Jest, I tried to fix this error for 2 hours. But, I couldn't fix it. My module is using gapi-script package and error is occurred in this package. However, I don't know why this is occurred and how to fix it.
jest.config.js
module.exports = {
"collectCoverage": true,
"rootDir": "./",
"testRegex": "__tests__/.+\\.test\\.js",
"transform": {
'^.+\\.js?$': "babel-jest"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"lib"
]
}
babel.config.js
module.exports = {
presets: [
'#babel/preset-env',
]
};
methods.test.js
import methods, { typeToActions } from '../lib/methods';
methods.js
import { gapi } from "gapi-script";
...
Error Message
C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ gapi, gapiComplete } from './gapiScript';
SyntaxError: Cannot use import statement outside a module
What is wrong with my setting?
As of this writing, Jest is in the process of providing support for ES6 modules. You can track the progress here:
https://jestjs.io/docs/en/ecmascript-modules
For now, you can eliminate this error by running this command:
node --experimental-vm-modules node_modules/.bin/jest
instead of simply:
jest
Be sure to check the link before using this solution.
I solved this with the help of Paulo Coghi's answer to another question -
Does Jest support ES6 import/export?
Step 1:
Add your test environment to .babelrc in the root of your project:
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Step 2:
Install the ECMAScript 6 transform plugin:
npm install --save-dev #babel/plugin-transform-modules-commonjs
Jest needs babel to work with modules.
For the testing alone, you do not need jest.config.js, just name the testfiles xxx.spec.js or xxx.test.js or put the files in a folder named test.
I use this babel.config.js:
module.exports = function (api) {
api.cache(true)
const presets = [
"#babel/preset-env"
]
return {
presets
}
}
Adding "type": "module" in package.json or using mjs as stated in other answers is not necessary when your setup is not too complicated.
I have also faced the same issue and this was resolved by adding following command-line option as a environment variable.
export NODE_OPTIONS=--experimental-vm-modules npx jest //linux
setx NODE_OPTIONS "--experimental-vm-modules npx jest" //windows
Upgrading Jest (package.json) to version 29 (latest as of now) solved this problem for me.

How to access vendor extensions in api.mustache regarding imports when endpoints are regrouped by tags

Problem
The issue concerns swagger codegen and using multiple files to define specs.
I have two REST APIs with two different files specs1.yml and specs2.yml.
These specs have some models/schemas/definitions (I use swagger 2.0) in common.
I'd like to factorize these definitions in a core.yml file.
I can then reference these in specs1 and specs2.
The issue is that swagger codegen generates these models as part of specs1 and specs2. What I'd like is processing the core.yml file, generating classes in a core package, and then having the specs1/2 generated classes referencing the classes in the core package when it's a common one.
Technical Stack
Maven / Java / JAXRS-CXF REST API
Maven 3.6.0
Java 1.8.0_201
swagger-jaxrs 1.5.16
CXF 3.1.14
swagger-codegen-maven-plugin 2.4.7
Code Example
Swagger Specs YML
I have a tag named e.g. "Super Tag" in my swagger specs definition.
Multiple endpoints are regrouped under that tag. For the sake of a minimal PoC of my issue, let's go with one endpoint:
specs1.yml
swagger: "2.0"
tags:
- name: "Super Tag"
x-core-imports: [ErrorResponse] # Trying this at tag level
x-imports: [ABody] # Trying this at tag level
paths:
/someEndpointPath:
post:
x-core-imports: [ErrorResponse] # --> import bla.core.api.models.ErrorResponse
x-imports: [ABody] # --> import bla.project.api.models.ABody
tags:
- "Super Tag"
operationId: postToSomeEndpoint
consumes:
- application/json
produces:
- application/json
parameters:
- name: body
in: body
required: true
schema:
$ref: '#/definitions/ABody' # This model is defined in this file
responses:
204:
description: "Successful response"
400:
description: "Bad request error"
schema:
$ref: '../CORE.yml#/definitions/_ErrorResponse'
# I'm importing this model definition from another file
definitions:
ABody:
type: object
field:
type: string
Swagger Codegen Debugging
I tried seeing where the vendor extensions would be added with regards to imports: [{ "import": ... }] (which is what's read from the api.mustache template, see below)
> java -DdebugSupportingFiles -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i specs.yml -l java > result.json
I can see
result.json
"apiInfo" : {
"apis" : { [
"parent" : [ ],
"generatorClass" : "io.swagger.codegen.languages.JavaClientCodegen",
"supportJava6" : false,
"sortParamsByRequiredFlag" : true,
"groupId" : "io.swagger",
"invokerPackage" : "io.swagger.client",
"classVarName" : "superTag",
"developerEmail" : "apiteam#swagger.io",
"generateModelDocs" : true,
"hasImport" : true,
"generateModelTests" : true,
"generateApiTests" : true,
"classFilename" : "SuperTagApi",
"usePlayWS" : false,
"generateModels" : true,
"serializableModel" : false,
"playVersion" : "play25",
"inputSpec" : "specs.yml",
"artifactUrl" : "https://github.com/swagger-api/swagger-codegen",
"developerOrganization" : "Swagger",
"baseName" : "SuperTag",
"package" : "io.swagger.client.api",
"imports" : [ {
"import" : "io.swagger.client.model.ABody"
}, {
"import" : "io.swagger.client.model.ErrorResponse"
} ]
...
] }
}
Swagger Templates
We can see in the api.mustache template
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
I'm using the maven swagger codegen plugin with the following options:
<modelPackage>com.mysite.myproject.api.models</modelPackage>
<apiPackage>com.mysite.myproject.api</apiPackage>
So in my generated java class I will get:
SuperTagApi.class
package com.mysite.myproject.api;
import com.mysite.myproject.api.models.ErrorResponse;
import com.mysite.myproject.api.models.ABody;
What I'd like to do is have a means to tell swaggercodegen that I want one class imported as it is now, but the second imported from another package.
To do that, my idea was using vendor extensions (as you can see above) and manually list the classes that I want imported from a given package (that will actually be generated from the CORE.yml file) and the ones that are defined in my specs.yml where I want the original generated package name.
I tried adding x-core-imports vendor-extension to multiple different places trying to get access to them. None put them at the same level as the imports: [{ "import": ... }] section of the result.json... This is because different endpoints/methods are regrouped under the same file when their tag is identical.
I modified my api.mustache like so:
{{^vendorExtensions.x-imports}}
{{#imports}}import {{import}};
{{/imports}}
{{/vendorExtensions.x-imports}}
{{#vendorExtensions.x-imports}}
{{#vendorExtensions.x-core-imports}}
import com.mysite.core.api.models.{{.}};
{{/vendorExtensions.x-core-imports}}
import com.mysite.myproject.api.models.{{.}};
{{/vendorExtensions.x-imports}}
Do you know at which level in the yml file I have to put my vendor extensions to be able to access them from api.mustache? (Without modifying swagger codegen, just modifying templates and yml specs files)

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