Vue 3 and Installing UUID demo - uuid

I'm new Vue 3 and finding the examples which are often written for Vue 2 to be incompatible with Vue 3. In this question, I can't find any information about the compatibility of UUID on the documentations github site. But assuming the version that installed with Vue 3 is the correct version.
After installing Vue 3 using npm, I created a new project by running "vue create myProject". The Hello World page displayed correctly. Then installed uuid again using "npm i vue-uuid" which was successful.
I added the code as described on the github page for uuid. Got errors about "use" was unknown so modified the main.js code as shown below. Now I get an error that reads "Uncaught TypeError: Cannot set property '$uuid' of undefined".
I'm lost and wondering why it has to be so hard? Any help would be appreciated.
main.js
import { createApp } from 'vue'
import App from './App.vue'
//import Vue from "vue";
import UUID from "vue-uuid"
//Vue.use(UUID);
createApp(App).use(UUID).mount('#app')
App.Vue
<template>
<div class="uuid-panel">
<h3 class="uuid">{{ uuid }}</h3>
<button class="button" #click="uuid = $uuid.v1()">Generate V1</button>
<button class="button" #click="uuid = $uuid.v3()">Generate V3</button>
<button class="button" #click="uuid = $uuid.v4()">Generate V4</button>
<button class="button" #click="uuid = $uuid.v5('Name 1', NAMESPACE)" >Generate V5</button>
</div>
</template>
<script>
import { uuid } from 'vue-uuid'
const NAMESPACE = "65f9af5d-f23f-4065-ac85-da725569fdcd"
export default {
name: 'App',
data () {
return {
NAMESPACE,
uuid: uuid.v1(),
v1: this.$uuid.v1(),
v3: this.$uuid.v3(),
v4: this.$uuid.v4(),
v5: this.$uuid.v5("Name 2", NAMESPACE)
};
}
}
</script>
And package.json
"name": "myProject",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build"
},
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-uuid": "^2.0.2"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0"
}
}

You can use uuid
npm install uuid
then in the script part:
import { v4 as uuidv4 } from "uuid";
That's it! Calling uuidv4() will give you, your desired random UUID.

Related

Getting the error "Nested CSS was detected, but CSS nesting has not been configured correctly" in React app?

I've been upgrading my CRA project to TailwindCSS 3, but now CSS nesting no longer works. Upon starting the server, the console spits out:
(8:3) Nested CSS was detected, but CSS nesting has not been configured correctly.
Please enable a CSS nesting plugin *before* Tailwind in your configuration.
See how here: https://tailwindcss.com/docs/using-with-preprocessors#nesting
However, I don't see what must be done to correct this. I've tried setting up a plain CRA project with Tailwind (following this guide) just to make sure I have no conflicts, and still no success.
postcss.config.js:
module.exports = {
plugins: {
"tailwindcss/nesting": {},
tailwindcss: {},
autoprefixer: {},
},
};
As you can see, I have added the nesting plugin before Tailwind. It appears to me as if the plugin isn't being detected whatsoever. I've also tried replacing it with postcss-nesting with same outcome.
Note: I've also tried using the array syntax with require('tailwind/nesting') like the guide suggests.
Interestingly, removing all plugins from postcss.config.js (or using a require that fails to resolve) still outputs the same error, implying that this file isn't needed to get Tailwind to load. Maybe I am missing something that causes the whole postcss.config.js file to not be loaded in the first place?
index.js:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
ReactDOM.render(
<React.StrictMode>
<div className="a">
aaa
<div className="b">bbb</div>
</div>
</React.StrictMode>,
document.getElementById("root")
);
index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
.a {
#apply text-blue-500;
.b {
#apply text-green-500;
}
}
package.json: (omitted things for brevity)
{
"name": "tailwindtest",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"devDependencies": {
"autoprefixer": "^10.4.2",
"postcss": "^8.4.5",
"tailwindcss": "^3.0.12"
}
}
This is mostly just bad news.
Create React App's Tailwind support means that they will detect tailwind.config.js in the project and add tailwindcss to their existing postcss configuration. Source in CRA
The guide that Tailwind offers on their site creates a dummy postcss.config.js - Making changes in this file does not change the actual postcss configuration. (misleading if anything)
This is a known issue currently - Github discussion on Tailwind support PR between Adam Wathan (Tailwind founder) and Ian Sutherland (CRA maintainer). But it does not seem like there is an intention to be fixed soon.
If you want to use nesting (or any PostCSS plugin really) is to eject from CRA using:
npm run eject
After ejecting you can find CRA's postcss configuration in config/webpack.config.js - look for postcss-loader. Editing the configuration there can enable any postcss features.
PS: Look out for postcss-preset-env in the default configuration while enabling nesting. Tailwind requires you to edit configuration if this is present.
I use CRA and to fix the issue I used postinstall to run a script after npm install or yarn. The script is changing the web pack config of CRA after all dependencies are installed(a temporary solution of cause).
You can find the web pack config in node_modules/react-scripts/config/webpack.config.js.
The script adds my postcss packages to the actual CRA web pack config.
WHY? CRA does not respect any postcss config in your repo
Have also a look at this comment to see how you should use postinstall https://github.com/facebook/create-react-app/issues/2133#issuecomment-347574268.
I also added tailwindcss/nesting before tailwindcss because tailwind is throwing a warning when it sees any nested css. The warning was blocking my CI since CI=true in CRA means all warnings are treated as errors.
Here is the script that is running in my repo.
FILE="node_modules/react-scripts/config/webpack.config.js"
function replace {
TARGET_FILE=$1
PATTERN_TO_FIND=$2
VALUE_FOR_REPLACEMENT=$3
OLD_FILE_CONTENT=$(cat "$TARGET_FILE") # we need to collect the content of the file so we can overwrite it in the next command
echo "$OLD_FILE_CONTENT" | sed -e "s/$PATTERN_TO_FIND/$VALUE_FOR_REPLACEMENT/g" > "$TARGET_FILE"
}
# add postcss-nesting
replace "$FILE" "'postcss-flexbugs-fixes'," "'postcss-flexbugs-fixes','postcss-nesting',"
# add tailwind/nesting
replace "$FILE" "'tailwindcss'," "'tailwindcss\/nesting', 'tailwindcss',"
acording to #aricma answer, is easier if you create a script.js file on parent directory (same as package.json) and add this on package.json
"scripts": {
"postinstall": "node script.js",
...
}
and this on script.js
const fs = require('fs');
fs.readFile('node_modules/react-scripts/config/webpack.config.js', 'utf8', (err, data) => {
if (err) {
return console.log(err);
}
const result = data.replace("'postcss-flexbugs-fixes',", "'postcss-flexbugs-fixes','postcss-nesting',").replace("'tailwindcss',", "'tailwindcss/nesting', 'tailwindcss',");
fs.writeFile('node_modules/react-scripts/config/webpack.config.js', result, 'utf8', (err) => {
if (err) {
return console.log(err);
}
return console.log(true);
});
return console.log(true);
});

React Types not being recognized by ESLint in Webstorm

I have started a new create-react-app (CRA) project to replace an existing React project that did not use CRA. The project is using TypeScript and my IDE is WebStorm.
My package.json file contains the following modules in devDependencies:
"#types/react": "~16.9.50",
"#typescript-eslint/eslint-plugin": "~4.3.0",
"eslint": "6.6.0",
"eslint-config-airbnb-typescript": "~11.0.0",
"eslint-plugin-import": "~2.22.1",
"eslint-plugin-jsx-a11y": "~6.3.1",
"eslint-plugin-react": "~7.21.3",
"eslint-plugin-react-hooks": "~4.1.2",
"typescript": "~4.0.3"
An example of one component is as follows:
import React, { FunctionComponent } from 'react';
const Content: FunctionComponent = () => (
<div>Hello</div>
);
export { Content };
ESLint / WebStorm complains with the following error:
ESLint: 'FunctionComponent' is defined but never used.(#typescript-eslint/no-unused-vars)
My code still compiles without any errors or warnings and my website works without any issues. My previous project did not have any issues recognizing TypeScript types. I have the #types modules installed. I think the relevant parts of .eslintrc, tsconfig.json and the relevant settings in WebStorm are identical.
Does anyone have any insight?
I resolved the issue by upgrading to react-scripts 4.0

How to make cherry picking react component library like lodash & date/fns

I have made one small library which includes 20-25 different components & made an npm package of it.
my react project, where I want to use these components, has many pages[routes] used lazy-loading so each page has its own bundle.
but when I write the statement on my home page[App.js].
import { MyModal } from 'my-react-lib';
each and every component is loaded into home page bundle. so my initial loading performance is worst. [2Mb initial bundle size]
I have read the concept of tree shaking and event tried to implement in webpack & even with rollup but they only make bundle.js but not as per mine requirement.
I am willing to achieve cherry-picking like import-export. same as date-fns & lodash does.
import format from 'date-fns/format';
import debounce from 'lodash/debounce';
how to achieve this?
import MyModal from 'my-react-lib/MyModal';
import OtherComponent from 'my-react-lib/OtherComponent';
Rollup allows you to split your library into several independent chunks. You have to provide an object, mapping names to entry points, to the input property of the rollup configuration. It looks like this:
input: {
index: 'src/index.js',
theme: 'src/Theme',
badge: 'src/components/Badge',
contentCard: 'src/components/ContentCard',
card: 'src/elements/Card',
icon: 'src/elements/Icon',
...
src/index.js looks like this:
export { default as Theme } from './Theme'
export { default as Badge } from './components/Badge'
...
Have a look at rollup’s documentation: https://rollupjs.org/guide/en/#input
The output is set to a directory:
output: [
{
dir: 'dist/es',
format: 'es',
},
],
Then you declare the entry point in your package.json as follows:
"module": "dist/es/index.js",
The modules of your library can then be imported:
import { Theme, Badge } from 'your-component-library'
You may need to package them separately.
For example the Material-UI, there are many parts of it. When we use it in the normal way
npm install #material-ui/core
If you look at their source, you would find out that there are multiple packages, each with it's own package.json file
For example the #material-ui/core pacakge.json
{
"name": "#material-ui/core",
"version": "4.9.7",
"private": false,
"author": "Material-UI Team",
...
"dependencies": {
"#babel/runtime": "^7.4.4",
"#material-ui/styles": "^4.9.6",
"#material-ui/system": "^4.9.6",
"#material-ui/types": "^5.0.0",
"#material-ui/utils": "^4.9.6",
Which means that they are actually separate and have dependencies with each other.
Well, that's the scope.

load socket.io with Angular 2 AOT

I've created a project in angular2 with socket.io to emit / listen socket communication. Everything works fine in JIT ( or npm start) but when I try to compile the code via rollup to lunch it as AOT for production usage It don't work.
Node version : 6.9.4
npm version : 3.10.6
typings.json
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#7.0.0+20170110233017",
"socket.io-client": "registry:dt/socket.io-client#1.4.4+20161116080703"
},
"ambientDependencies": {
"node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts#138ad74b9e8e6c08af7633964962835add4c91e2",
"socket-io-client": "github:DefinitelyTyped/DefinitelyTyped/socket.io-client/socket.io-client.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
"es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654"
}
}
systemjs.config.js
map : {"socket.io-client": 'npm:socket.io-client'}
packages : { "socket.io-client": {
main: './socket.io.js',
"defaultExtension": "js"
} }
package.json :
"socket.io-client": "^1.7.2"
mycomponent.ts
import * as io from 'socket.io-client';
var url = 'http://localhost:4500';
export var socket = io(url);
"node_modules/.bin/ngc" -p tsconfig-aot.json executes successfully but
"node_modules/.bin/rollup" -c rollup-config.js gives error : cannot call a namespace ('io')
If i change my component import line and set import io from socket.io-client then i get error module 'socket.io-client' has no default export
I would appreciate if someone can guide me through as this is my second day of troubleshooting and trying as per other forums.
Thanks in Advance,
Kapil
Keep import:
import * as io from 'socket.io-client';
And add plugin to rollup.js:
{
name: 'replace io imports',
transform: code => ({
code: code.replace(/import\s*\*\s*as\s*io/g, 'import io'),
map: { mappings: '' }
})
},

React.addons.TestUtils.renderIntoDocument always returns null

I am learning Jest & trying to integrated unit tests into my existing ES6 React application. For some reason, React.addons.TestUtils.renderIntoDocument is always returning null. Can anyone see what i am doing wrong?
Many thanks.
package.json
{
"name": "test.jest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-jest": "^5.2.0",
"jest-cli": "^0.4.5"
},
"dependencies": {
"react": "^0.13.3"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react"
],
"testFileExtensions": [
"js",
"jsx"
],
"moduleFileExtensions": [
"js",
"jsx",
"json"
]
}
}
__tests__/foo-test.jsx
/* global describe, it, expect */
'use strict'
import React from 'react/addons'
const { addons: { TestUtils } } = React
describe('Foo', () => {
it('is a react element', () => {
let component = TestUtils.renderIntoDocument(
<div>foo</div>
)
expect(TestUtils.isElement(component)).toBeTruthy()
})
})
Results
$ npm test
> test.jest#1.0.0 test /home/markus/Desktop/test.jest
> jest
Using Jest CLI v0.4.5
FAIL src/__tests__/foo-test.jsx (1.287s)
● Foo › it is a react element
- Expected false to be truthy.
at Spec.<anonymous> (/home/markus/Desktop/test.jest/src/__tests__/foo-test.jsx:15:44)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
1 test failed, 0 tests passed (1 total)
Run time: 1.555s
npm ERR! Test failed. See above for more details.
Update
The ES6 example is also not working. Throws a ton of warnings before failing when it tries to read from a null value. The ES5 example, however, does work. Might be an upstream babel-jest problem?
Results
$ npm test
> # test /home/markus/Desktop/jest/examples/react-es6
> node ../../bin/jest.js
Using Jest CLI v0.4.5
FAIL __tests__/CheckboxWithLabel-test.js (1.697s)
Warning: getDOMNode(...) is deprecated in plain JavaScript React classes. Use React.findDOMNode(component) instead.
Warning: isMounted(...) is deprecated in plain JavaScript React classes. Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks.
Warning: replaceProps(...) is deprecated in plain JavaScript React classes. Instead, call React.render again at the top level.
Warning: replaceState(...) is deprecated in plain JavaScript React classes. Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236).
Warning: setProps(...) is deprecated in plain JavaScript React classes. Instead, call React.render again at the top level.
● CheckboxWithLabel › it changes the text after click
- TypeError: Cannot read property 'textContent' of null
at Spec.<anonymous> (/home/markus/Desktop/jest/examples/react-es6/__tests__/CheckboxWithLabel-test.js:19:24)
at jasmine.Block.execute (/home/markus/Desktop/jest/vendor/jasmine/jasmine-1.3.0.js:1065:17)
at jasmine.Queue.next_ (/home/markus/Desktop/jest/vendor/jasmine/jasmine-1.3.0.js:2098:31)
at null._onTimeout (/home/markus/Desktop/jest/vendor/jasmine/jasmine-1.3.0.js:2088:18)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
1 test failed, 0 tests passed (1 total)
Run time: 1.946s
npm ERR! Test failed. See above for more details.
Seems like "isElement" checks for a React component instance, not a rendered tree. See the example below:
import ReactDomTestUtils from 'react-dom/test-utils';
isDOMComponent:
const reactTree = ReactDomTestUtils.renderIntoDocument(<div />);
expect(ReactDomTestUtils.isDOMComponent(reactTree)).toBe(true);
expect(ReactDomTestUtils.isElement(reactTree)).toBe(false);
isElement:
const reactElement = <div />;
expect(ReactDomTestUtils.isDOMComponent(reactElement)).toBe(false);
expect(ReactDomTestUtils.isElement(reactElement)).toBe(true);
I am not sure, but i think it had something do do with my node.js version. Neither v0.12.4 nor iojs v2.2.1 was working. But node v0.10.38 seems to work. Here's hoping for an update :)

Resources