Why the "define" options not work in vite2 when i package project? - vue.js

i define the process.config in vite.config.js such as this
define: {
'process.env': {
publishDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
version: pkg.version,
title: pkg.title
}
},
in dev mode ,it works,
but in prod mode, the process.config is unfound.

Because you are not doing things as vite documentation suggests:
Type: Record<string, string>
For example, process.env.FOO and __APP_VERSION__ are good fits. But process or global should not be put into this option.
it's implemented as straightforward text replacements without any syntax analysis
The map should be a string to string, not string to object. So you can write:
define: {
'process.env.publishDate': JSON.stringify(dayjs().format('YYYY-MM-DD HH:mm:ss'))
},

Related

How to split Prisma Model into separate file?

I'm learning Prisma ORM from video tutorials and official docs. They are explain and write All model code in one file called schema.prisma. It's ok but, when application grow it became messy. So, how should I separate my Model definition into separate file?
At this point in time Prisma doesn't support file segmentation. I can recommend 3 solutions though.
Option 1: Prismix
Prismix utilizes models and enums to create relations across files for your Prisma schema via a prismix configuration file.
{
"mixers": [
{
"input": [
"base.prisma",
"./modules/auth/auth.prisma",
"./modules/posts/posts.prisma",
],
"output": "prisma/schema.prisma"
}
]
}
Placing this inside of a prismix.config.json file which will define how you'd like to merge your Prisma segmentations.
Option 2: Schemix
Schemix Utilizes Typescript configurations to handle schema segmenting.
For example:
// _schema.ts
import { createSchema } from "schemix";
export const PrismaSchema = createSchema({
datasource: {
provider: "postgresql",
url: {
env: "DATABASE_URL"
},
},
generator: {
provider: "prisma-client-js",
},
});
export const UserModel = PrismaSchema.createModel("User");
import "./models/User.model";
PrismaSchema.export("./", "schema");
Inside of User.model
// models/User.model.ts
import { UserModel, PostModel, PostTypeEnum } from "../_schema";
UserModel
.string("id", { id: true, default: { uuid: true } })
.int("registrantNumber", { default: { autoincrement: true } })
.boolean("isBanned", { default: false })
.relation("posts", PostModel, { list: true })
.raw('##map("service_user")');
This will then generate your prisma/schema.prisma containing your full schema. I used only one database as an example (taken from documentation) but you should get the point.
Option 3: Cat -> Generate
Segmenting your schema into chunk part filenames and run:
cat *.part.prisma > schema.prisma
yarn prisma generate
Most of these if not all of them are referenced here in the currently Open issue regarding support for Prisma schema file segmentation https://github.com/prisma/prisma/issues/2377
This is not yet possible with Prisma. See this outstanding issue for possible workarounds https://github.com/prisma/prisma/issues/2377.
There is a library called Prismix that allows you to write as many schema files as you'd like, here you go the link

How to set provider.apiGateway.shouldStartNameWithService in a serverless.ts file?

I am kicking off a new project with a new Serverless TypeScript monorepo! Used the aws-nodejs-typescript template, which gave a serverless.ts config file. After some weeks, I am now getting the nice warning below from Serverless on command line:
Serverless: Deprecation warning: Starting with next major version, API Gateway naming will be changed from “{stage}-{service}” to “{service}-{stage}”.
Set “provider.apiGateway.shouldStartNameWithService” to “true” to adapt to the new behavior now.
More Info: https://www.serverless.com/framework/docs/deprecations/#AWS_API_GATEWAY_NAME_STARTING_WITH_SERVICE
Ok! Looks great, and I like the new naming. And since it’s a new project, better to apply the new naming now, before we release anything. However, it looks like the TypeScript definitions are rather strict, and do not seem to allow for the new variable yet:
Loading failed with: TSError: ⨯ Unable to compile TypeScript:
serverless.ts(44,7): error TS2322: Type ‘{ minimumCompressionSize: number; shouldStartNameWithService: true; }’ is not assignable to type ‘ApiGateway’.
Object literal may only specify known properties, and ‘shouldStartNameWithService’ does not exist in type ‘ApiGateway’.
awsProvider.d.ts(51, 9): The expected type comes from property ‘apiGateway’ which is declared here on type ‘Provider’
Is there a way to set the new property without reverting everything to YAML, which would be somewhat painful at this point?
Update 1
Many thanks to #NexGen for the pointer! Here is a minimal serverless.ts (emphasis on the TS!) showing the solution.
import type { Serverless, ApiGateway } from 'serverless/aws';
const serverlessConfiguration: Serverless = {
service: {
name: 'foo',
},
frameworkVersion: '2',
custom: {
webpack: {
webpackConfig: './webpack.config.js',
packager: 'yarn',
includeModules: true,
},
alerts: {
stages: ['stage', 'prod'],
definitions: {
functionErrors: { treatMissingData: 'notBreaching' },
},
alarms: ['functionErrors'],
},
},
package: {
individually: true,
},
plugins: [
'serverless-webpack',
'serverless-jest-plugin',
'serverless-plugin-aws-alerts',
],
provider: {
name: 'aws',
runtime: 'nodejs12.x',
region: 'us-west-2',
stage: "${opt:stage, 'dev'}",
apiGateway: {
minimumCompressionSize: 1024,
shouldStartNameWithService: true,
} as ApiGateway,
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
},
},
};
module.exports = serverlessConfiguration;
It is really simple to apply this change, all what you need to do is to add this to your serverless.yml file.
provider:
apiGateway:
shouldStartNameWithService: true
provider: {
name: 'aws',
runtime: 'nodejs12.x',
apiGateway: {
shouldStartNameWithService: true
} as ApiGateway,
stage: 'dev'
}

ESLint: set custom formatter in .eslintrc.js

I am using create-react-app with craco (Create-React-App-Configuration-Override)
Craco is not very exotic. It simply allows me to use my own eslintrc file with create-react-app.
I am trying to use a custom eslint formatter, specifically eslint-formatter-friendly does what I need (link to files at line numbers via iTerm/Guake terminals), but there are plenty of alternative formatters: http://npmsearch.com/?q=eslint-formatter
I tried setting a format: 'unix' or formatter: 'unix' in my .eslintrc.js file - but this didn't work, eslint explicitly gave an error saying something like "unrecognized top-level property".
I looked for any way I could specify formatter in the .eslintrc.js file, but I figured out that's not an option. After searching and scanning through the source for gulp-eslint, eslint-grunt and grunt-eslint, eventually I looked more closely at the source for for craco - where is reads a little eslint configuration: https://github.com/sharegate/craco/blob/master/recipes/use-an-eslintrc-config-file/craco.config.js
The source that processes this: https://github.com/sharegate/craco/blob/master/packages/craco/lib/features/webpack/eslint.js
All I needed to do was use this craco.config.js:
/* globals module */
const { ESLINT_MODES } = require("#craco/craco");
const reactHotReloadPlugin = require('craco-plugin-react-hot-reload');
module.exports = {
plugins: [{
plugin: reactHotReloadPlugin
}],
eslint: {
mode: ESLINT_MODES.file,
loaderOptions: {
formatter: require("eslint-formatter-friendly")
}
},
};

responsive-loader with nuxt.js

I want to integrate responsive-loader into my Nuxt.js project which runs in SPA mode. (Optional I want to add Vuetify Progressive Image support also).
It will be a static hosting with Netlify.
Versions:
"nuxt": "^2.3.4"
"responsive-loader": "^1.2.0"
"sharp": "^0.21.1"
I found some solutions how to do it (https://stackoverflow.com/a/51982357/8804871) but this is not working for me.
When I run npm run build
I get an error message: "TypeError: Cannot set property 'exclude' of undefined"
My build section looks the following:
build: {
transpile: [/^vuetify/],
plugins: [
new VuetifyLoaderPlugin()
],
extractCSS: true,
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient, isServer }) {
// Default block
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
if (isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vuetify/]
})
]
}
// Default block end
// here I tell webpack not to include jpgs and pngs
// as base64 as an inline image
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
/*
** Configure responsive-loader
*/
config.module.rules.push({
test: /\.(jpe?g|png)$/i,
loader: "responsive-loader",
options: {
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
});
}
}
The error is probably found in this section:
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
Like said I get this error message: "TypeError: Cannot set property 'exclude' of undefined".
I run this project along with vuetify. I also would like to enable the Progressive image support together with responsive loader. Does anybody know how to setup both rules together?
https://github.com/vuetifyjs/vuetify-loader#progressive-images
The easiest way to integrate responsive-loader into a Nuxt.js project is to use this module: https://www.npmjs.com/package/nuxt-responsive-loader
Disclaimer: I created the module
The problem with your config that it relies on rule.loader property but rule can be defined in use or oneOf config sections as well.
Another one problem is that nuxt internal config has several rules with url-loader(for images, videos, fonts ...).
In your case the rule, you tried to find, has use section and url-loader is defined there, that's why your find function found nothing and threw this error:
{
"test": /\.(png|jpe?g|gif|svg|webp)$/,
"use": [{
"loader": "url-loader",
"options": {
"limit": 1000,
"name": "img/[hash:7].[ext]"
}
}]
}
About responsive-loader, you should remove extensions you want to process with responsive-loader from url-loader rule to avoid unexpected behavior and conflicts, here is extend function working example:
extend(config, ctx) {
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/';
// find by reg ex string to not rely on rule structure
let urlRule = config.module.rules.find(r => r.test.toString() === imgTest);
// you can use also "oneOf" section and define both loaders there.
// removed images from url-loader test
urlRule.test = /\.(svg|webp)$/;
config.module.rules.push({
test: /\.(png|jpe?g|gif)$/,
loader: "responsive-loader",
options: {
// place generated images to the same place as url-loader
name: "img/[hash:7]-[width].[ext]",
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
})
}
Yes, it looks dirty, but I think it's only way for now to change some loader.
What about vuetify - I think both loaders will conflict with each other and probably the solution is to use single loader that will work with your images.
Hope it helps.
Update for Nuxt >= 2.4.0:
They modified the rules array please update the following line:
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/i';
Then the code should work normally again.

Vue PWA plugin adjusting iconPaths and manifest destination

I have attached 2 screenshots, one of my vue.config.js and another of a section of the unminified output my build is producing.
Whats happening is this: I want to change the icon paths and the path to the manifest. For whatever reason the official way of changing this is not working. Right now they are blank spaces, however it was not working when it was anything else either ( just tried with 'foo/bar' as the path as I was typing this to triple check ).
I am confused because I seem to be doing everything exactly as I should according to the official docs. Is there anything another set of eyes can spot that I am missing?
Greetings Erik White
At some point I had the same difficulty and solved it as follows:
Copy the images into the "public" folder
example:
We add the folder "favicon" to "public", "favicon" contains 5 images
[project]/public/favicon/favicon-32x32.png
[project]/public/favicon/favicon-16x16.png
[project]/public/favicon/apple-touch-icon-152x152.png
[project]/public/favicon/safari-pinned-tab.svg
[project]/public/favicon/msapplication-icon-144x144.png
To add images in your html: modify the "vue.config.js" and add.
// Inside vue.config.js
module.exports = {
  // ... other vue-cli plugin options ...
  pwa: {
  // ...
    iconPaths: {
      favicon32: 'favicon/favicon-32x32.png',
      favicon16: 'favicon/favicon-16x16.png',
      appleTouchIcon: 'favicon/apple-touch-icon-152x152.png',
      maskIcon: 'favicon/safari-pinned-tab.svg',
      msTileImage: 'favicon/msapplication-icon-144x144.png'
    }
  // ...
  }
}
To change the path and name of "manifest.json" modify the "vue.config.js" and add:
// Inside vue.config.js
module.exports = {
  // ... other vue-cli plugin options ...
  pwa: {
  // ...
    manifestPath: 'my_new_manifest.json',
  // ...
  }
}
To change the properties of the "manifest.json", (name, images, color, etc) modify the "vue.config.js" and add:
// Inside vue.config.js
module.exports = {
// ... other vue-cli plugin options ...
pwa: {
// ...
manifestOptions: {
name: 'etc ..',
short_name: 'etc ..',
theme_color: '# f44647',
background_color: '# f44647',
start_url: 'index.html',
display: 'standalone',
orientation: 'portrait',
icons: [
{
src: './favicon/favicon-32x32.png',
sizes: '32x32',
type: 'image/png'
},
{
src: './favicon/favicon-16x16.png',
sizes: '16x16',
type: 'image/png'
},
{
src: './favicon/apple-touch-icon-152x152.png',
sizes: '152x152',
type: 'image/png'
},
{
src: './favicon/safari-pinned-tab.svg',
sizes: '942x942',
type: 'image/svg+xml'
},
{
src: './favicon/msapplication-icon-144x144.png',
sizes: '144x144',
type: 'image/png'
},
]
},
// ...
}
}
NOTE
chucks is not a supported parameter.
excludeChucks is not a supported parameter.
If you need to test a service worker locally, build the application and run a simple HTTP-server from your build directory. It's recommended to use a browser incognito window to avoid complications with your browser cache.
Remember to see the VUE documentation, it is very detailed, I leave you a link below #vue/cli-plugin-pwa
Nevermind, solved by updating my dependencies.
guessing this was fixed in a patch i didnt catch