How do I use Web Component Shards? - polymer

There's a new project for, what it seems to me to be, a way to vulcanise elements in bundles, web-components-shards.
I'm interested in the gulp version, gulp-web-components-shards.
Both projects lack comprehensive instructions in the README, how the file structure should be, what the output should look like and how to use it, or how I can declare which elements are shared between bundles.
Considering this use case:
A sample File Structure
The Polymer elements
./app/elements
shared-element-1/shared-element-1.html
shared-element-2/shared-element-2.html
homepage-element-1/homepage-element-1.html
homepage-element-2/homepage-element-2.html
contact-element-1/contact-element-2.html
contact-element-1/contact-element-2.html
Note: shared-element-1.html & shared-element-2 are used in all routes
The routes:
./app/homepage.jade
./app/contact.jade
How should I set-up my gulp task so that is splits bundles I can use like so:
/* homepage.jade */
link(rel='import', href='/dist/shared-elements/shared-elements.html')
link(rel='import', href='/dist/homepage-elements/homepage-elements.html')
/* contact.jade */
link(rel='import', href='/dist/shared-elements/shared-elements.html')
link(rel='import', href='/dist/contact-elements/contact-elements.html')
Note: I've already opened an Issue - Still I think it would be nice to have an example usage snippet/explanation here as well.

In that web-component-shards seems to be a deprecated/abandoned, I'd take a look at Polymer CLI where this is a little more laid out in the documentation available: https://www.polymer-project.org/1.0/docs/tools/polymer-cli#app It allows us to structure the build of our app in a polymer.json files shaped like:
{
"entrypoint": "index.html",
"shell": "src/app-shell/app-shell.html",
"fragments": [
"src/view-one/view-one.html",
"src/view-one/view-two.html"
],
"sources": [
"src/**/*",
"images/**/*",
"bower.json"
],
"includeDependencies": [
"bower_components/webcomponentsjs/webcomponents-lite.min.js"
]
}
For you the most important parts would be the "fragments" as it would structure most closely to the app you've described. Then you could use the hooks specifically set up in the CLI to process your JADE and what not as well.

Related

Disable wavy yellow underline in vs code for HTML

How do I ignore this error. I have used the id attribute for some tags in order to reference them by id in javascript, but it shows this error:
CSS id selector '...' not found.
Please tell me how to ignore or disable this error.
maybe your css is not formatted properly.
try:
<style>
#phone {
your css here;
}
</style>
You need to make sure you mark the code with # to show that it's an id and not a class or something else.
Update: First section of answer no longer valid as of the lastest updates since original post which removed the css.validation option. see
If you are using the HTML CSS Support extension by ecmel, you can go to .vscode/settings.json and add
"css.validation": {
"id": false,
"class": false
}
This will turn off css validation for class name and id.
More information on this at the Visual Studio MarketPlace for this extension under Selector Validation here or the Github repository readme Selector Validation Section
Note:
1) Also don't forget to add a comma after the setting that comes before (as JSON format is comma separated).
Example:
{
"java.codeGeneration.generateComments": true,
"css.styleSheets": [
// (1)
"https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css",
"src/main/resources/static/css/styles.css"
],
"css.validation": {
"id": false,
"class": true
}
}
Sometimes you need to restart / close and reopen vscode after saving changed to the file for them take effect.
There is a way to configure styleSheets. This next bit is taken from their documentation see Additional Styles Section:
Additional Style Sheets
If it is not possible to specify local or remote styles in HTML or via
template inheritance, they can be specified in VS Code settings per
workspace folder in .vscode/settings.json and will suggest for all
HTML files within that workspace folder:
.vscode/settings.json
"css.styleSheets": [
// (1)
"https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css",
// (2)
"/site.css",
// (3)
"site.css",
// (4)
"./site.css"
]

purgecss can't recognize conditional classes

So I'm using TailwindCSS for a WP theme I'm developing.
I ran into an issue in creating the production grade theme files because, from how I understand the problem, purgecss can't recognize conditional classes used on template parts. For example, let's say I created a template part called "business-card.php" where I pass it a variable type (using set_query_var / get_query_var):
page-about.php
set_query_var('type', 'A');
get_template_part('template-parts/content/business', 'card');
set_query_var('type', 'B');
get_template_part('template-parts/content/business', 'card');
businesss-card.php
$type = get_query_var('type')
<div class="<?php echo type == 'A' ? 'text-color-A' : 'text-color-B' ?>">
--- insert some content here ---
</div>
So there will be two divs, one will have a text-color-A class, the other will have a text-color-B, both were created using a config file(rather than included in the base tailwind theme). This is fine in development -- since tailwind does actually create the utility color classes from the config file. But for some reason, when it's in production (i.e. purged & minified), it doesn't have those utility classes -- which were only used in the template part as conditional classes (and not in any other file).
PurgeCSS is intentionally very naive in the way it looks for classes in your HTML. It doesn't try to parse your HTML and look for class attributes or dynamically execute your JavaScript — it simply looks for any strings in the entire file that match this regular expression:
/[^<>"'`\s]*[^<>"'`\s:]/g
That means that it is important to avoid dynamically creating class strings in your templates with string concatenation, otherwise PurgeCSS won't know to preserve those classes.
So do not use string concatenation to create class names:
<div :class="text-{{ error ? 'red' : 'green' }}-600"></div>
Instead, dynamically select a complete class name:
<div :class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
As long as a class name appears in your template in its entirety, PurgeCSS will not remove it.
See the docs for more details:
Writing purgeable HTML
If you are using Tailwind 2.0+ you can configure whitelisted classes that will be ignored by purge CSS directly inside of your tailwind.config.js file.
An example of my own code where I whitelist the class text-ingido-400 can be seen below
// tailwind.config.js
module.exports = {
purge: {
content: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
options: {
safelist: ['text-indigo-400']
}
} ,
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
For more information you can check out the relevant documentation located at:
https://tailwindcss.com/docs/optimizing-for-production
You can use the PurgeCSS whitelist option to add those classes.
const purgecss = new Purgecss({
//... Your config
whitelist: ['text-color-A', 'text-color-B', 'etc']
})
Or the whitelistPatterns (Regex match)
whitelistPatterns: [/^text-color/], // All classes starting with text-color
You can find more information here
If you define your class names in a variable above where you want to use them it works akin to safe listing them in Tailwind or whitelisting them in PurgeCSS, is potentially easier to maintain, and works good in a pinch if you have a small number of possbile dynamic class names.
var classes =`grid-cols-1 grid-cols-2 grid-cols-3 grid-cols-4`
return (
<div className={`grid grid-cols-${items['grid-cols']}`}>
</div>
)
For some tailwindcss class, you can use inline style instead.
Inline style allow you to use dynamic value, like <div style="padding-left:{indent}rem">.
I think it works in php also. More details can be found here

Is it possible to create a bundle with Rollup that injects HTML from a template?

I'm trying to build a IIFE (immediately-invoked function expression) bundle using Rollup.
I would like to bundle all together my JS, CSS, and then some HTML which the Javascript depends on. Check this image to get an idea:
Is there a way to tell Rollup that my input (entry point) is seguro-vida-hipoteca.js, and have this file import my SCSS and HTML so it will be automatically injected when somebody uses my library?
That would be, the resulting CSS in the head, and the HTML to some div that I would expect to exist in the dom, or just at the end of body.
Is there a way to tell Rollup that my input (entry point) is seguro-vida-hipoteca.js?
Sure, that's what the input option is for.
Injecting Sass in the head is easily accomplishable with plugins such as rollup-plugin-postcss:
// rollup.config.js
import postcss from 'rollup-plugin-postcss';
export default {
// ...
plugins: [
postcss(),
],
}
import './style.scss'; // Now each stylesheet you import will
// be injected to <head>
About injecting/appending html, that is something you would normally do in your code and not through a plugin, although you can take advantage of Rollup to load template.html as a string (for example by using rollup-plugin-html):
import html from "rollup-plugin-html";
export default {
// ...
plugins: [
html({
include: "**/*.html",
}),
],
}
import template from './template.html';
document.querySelector('#mydiv').innerHTML = template;
Side note
This seems to be a good use case for WebComponents. More info here.

Airbnb, ESLint, Prettier conflict over Switch and Case indentation

I am setting up my React Redux project to use ESLint with Airbnb configs and Prettier. I've been modifying certain things to how I want them, but now I've run into a problem with indentations on switch & case statements that I can't seem to fix.
I am editing my project in VSCode. I click on the errors and fix with ESLint, reducing the indent by 4 spaces, but then more errors show up from Prettier, asking to re-indent everything by another 4 spaces.
I want to change the current indentation width. I want it set to 4 spaces when I use tabs. It's not a must, but if it is possible, I would prefer that the case keywords in switch blocks to be indented.
List of packages that pertain to my ESLint configuration:
prettier
eslint
eslint-config-airbnb
eslint-plugin-import
eslint-plugin-jsx-a11y
eslint-plugin-react
eslint-import-resolver-webpack
eslint-config-prettier
eslint-plugin-prettier
Relevant portion of my .eslintrc.json
"extends": ["airbnb", "prettier", "prettier/react"],
"plugins": ["react", "prettier"],
"rules": {
"react/jsx-filename-extension": [
1,
{
"extensions": [".js", "jsx"]
}
],
"prettier/prettier": "error",
"indent": ["error", 4, { "SwitchCase": 1 }],
"react/jsx-indent": ["error", 4],
"react/jsx-indent-props": ["error", 4],
"class-methods-use-this": 0,
"no-else-return": 0,
"no-plusplus": [2, { "allowForLoopAfterthoughts": true }],
"no-param-reassign": 0
}
My .prettierrc config-file:
The setting below is necessary for Prettier to format indentations harmoniously with the rest of the development environments configurations while using ESLint.
"prettier": {
"tabWidth": 4
}
Here is the script I am formatting:
It is a hangman game.
switch (action.type) {
case GUESS_LETTER:
return Object.assign(
{},
state,
state.guessWord.includes(action.guessLetter)
? addCorrectGuess(
state.rightLetters.slice(), // <-- error here!
action.guessLetter, // <-- error here!
state.guessWord // <-- error here!
) // <-- error here!
: addWrongGuess(
state.wrongLetters.slice(), // <-- error here!
action.guessLetter // <-- error here!
) // <-- error here!
);
}
My first attempt to get this working was to add { "SwitchCase": 1 } to the ESLint config file. That reduced the number of errors (which was almost the entire block), but there are still errors. I can't figure out where the conflict is exactly.
[UPDATE] To my eternal shame, I believe I discovered the problem. I simply removed the configuration for intends from the ESLint configuration. I removed this:
"indent": ["error", 4, { "SwitchCase": 1 }],
"react/jsx-indent": ["error", 4],
"react/jsx-indent-props": ["error", 4],
And now it seems to be behaving normally. I assume this is because it screws up Prettier when trying to handle indents. I only needed the configuration for Prettier.
Lesson: test more by removing configurations which may be causing conflict before posting.
To make sure this is marked as solved:
I simply removed the configuration for indents from the ESLint configuration. I removed this:
"indent": ["error", 4, { "SwitchCase": 1 }],
"react/jsx-indent": ["error", 4],
"react/jsx-indent-props": ["error", 4],
And now it seems to be behaving normally. I assume this is because it screws up Prettier when trying to handle indents. I only needed the configuration for Prettier.
Lesson: test more by removing configurations which may be causing conflict before posting.
I had the same problem as mentioned in the question above, however I figured out how to solve it in a way that not only could the "indent" setting be kept, but so it can be adjusted, allowing for tabWidth to be set as you like.
First I want to note, so we're all on the same page, what the set-up I am using for linting/formatting exactly is:
Source Code Editor: V.S. Code
Linting Utility: ESLint
Opinionated Formatter: Prettier
Style-Guide: AirBnB
Additionally I also equip the following, which I download using NPM:
eslint-plugin-prettier
eslint-config-prettier
eslint-config-airbnb
For those familiar with linting while using V.S. Code, you guys know that what I am using is actually the short list. There is all kinds of other configs, plugins & extensions that can be obtained. The important thing to note here, is that I am using a tried & true setup, that allows Prettier, and ESLint to work harmoniously together.
With that said, even having a good configuration, and all the correct extensions I still had a problem with the above rule, the same as the developer who posted the question. I knew the problem had to do with ESLint's rules, and how they were being configured in my .eslintrc.json file. After much research, and near mastering ESLint, I found that I was correct. There are a few ESLint rules, (3 ESLint rules, and 1 Prettier Setting), that you need to have configured properly, however; at the same time you need to make sure your .prettierrc file settings are in-sync with your .eslintrc.json file rules. Once you understand it all, it is actually not as complicated as it sounds.
STEP #1 Know what tabWidth you want and set it in .prettierrc
First off you need to decide what you want your styles tab-width to be. (Most Style-Guides set there tab-width at (2x Space-Width), but many dev's will change there settings to a (4x Space-Width). Any thing other than 2x and 4x is considered taboo.)
Go ahead and open your .prettierrc file (or what ever mimetype of prettier configuration file you use), then set 'tabWidth' to your liking, just make sure that you stick with a consistant tabWidth from here on out, becuase ESLint needs to be in sync with prettier.
Your '.prettierrc' file should look similar to this:
{
"printWidth": 90,
"tabWidth": 4,
"useTabs": false,
"trailingComma": "all",
"singleQuote": true,
"semi": true,
"bracketSpacing": false,
}
STEP #2: set the "max-len" rule in .eslintrc.json**
open up your .eslintrc.json file (or whatever version of ESLint configuration file mime-type that you use), and set the "max-len" rule in the rules property of your eslintrc.json. The rule is not in the file by default so you will have to write it in. To see how, review the Example I Created Below.
Be sure that the "tabWidth" property within ESLint's "max-len" rule, holds exactly the same value, as the "tabWidth" setting within your .prettierrc file.
There are some other rule options here that are important to set properly as well. The first, 'code', sets the max amount of chars each line can hold, aka(max-line-length). When "code" is set ESlint will not allow more characters than what "code" has been set to. The catch is that you absolutely must Make sure that the "printWidth" setting in your .prettierrc file, which you probably will have to write in, is set to the same value as the "code" property's value in your .eslintrc.json max-len rule.
"ignoreUrls" can be set either way and make sure the rule does throw an error by leaving the word "error" as it is.
Here is an example of my max-len rule in ESLint
"rules": {
"max-len": [
"error",
{
"code": 90,
"tabWidth": 4,
"ignoreUrls": true
}
],
}
See the .prettierrc example above, to view how to set "printWidth"
STEP #3: ESLint's "no-tabs" Rule
The "no-tabs" rule, is a 'must set', w/o it your linting & formatting > can unsynchronize.
You can set "allowIndentationTabs" as you like, Allowing for, or disallowing indentation tabs won't make a difference.
What the no-tabs rule should look like:
"rules": {
"no-tabs": ["error", {"allowIndentationTabs": true}],
"max-len": [
"error",
{
"code": 90,
"tabWidth": 4,
"ignoreUrls": true
}
],
}
STEP #4: ESLint's "indent" Rule, by far the most important rule of this discussion
Seriously this one is important. Its the one that gets thrown out in an attempt to fix the switch indentation problem, which doesn't give you control over other settings, like setting your own tab-width. The "indent" rule.
First make sure indent is active by setting error to error as you see it, you could also set it to warn, but its better to set it as error so prettier knows to fix it imeadiatly. The next setting is the width of your indentations, which has to be the same exact value as your tabWidth in your .prettierrc file, and as in the "max-len" ESLint rule.
"indent": ["error", 4, {"SwitchCase": 1}],
The last settings in the brackets, "SwitchCase" can be confusing. No one explained any of this to me at first so I had to figure it out on my own, and this screwed me up a bit. The number that "SwitchCase" gets set to is not like the 4 before it. The 4 that comes before it is the initial setting of the "indent" rule and can stand alone like this:
"indent": 4; // throws error
// or
"indent": ["warn", 4] // Throws warning, which is somtimes less annoying than an error
So it is important to note that the value 4 that you see in the "indent" rule, is how many spaces an indent will be. This led me to believe that the 1 after "SwitchCase" meant how many spaces that the switch keyword case will be indented.
Example:
switch (x) {
case 1:
break;
}
That is not how it works though. The number that rule "SwitchCase" is set to, tells the editor how many times to indent the keyword 'case'. So if the "indent" rule is set to 4, and the "SwitchCase" rule is set to 4, then ESLint will expect an indentation of 4x4=16. At the end of the day ESLint will actually expect more than 16, because ESLint is going to take on all the indentation from different levels of blocks that the switch statement is found in, this ends up leading to ESLint expecting 24-36 spaces of indentation, that's crazy.
"SwitchCase" needs to be set to 1.
"rules": {
"indent": ["error", 4, {"SwitchCase": 1}],
"no-tabs": ["error", {"allowIndentationTabs": true}],
"max-len": [
"error",
{
"code": 90,
"tabWidth": 4,
"ignoreUrls": true
}
],
}
If you set all the rules right that should work for you
If it is still not working, try starting with a clean slate, delete your .eslintrc.json file, and create a new eslintrc.json file, and build it anew. You shouldn't have to start over with a new .prettierrc file.
To Wrap Up
Prettier wants to indent everything uninformed like. So if tabWidth is set to 4, and tabWidth & indent is set to 4 in ESlint then every block gets indented 4 spaces be prettier, no more and no less.
The whole problem initially is that, the style guides often ask that the keyword case not be indented, so when ESLint is setup, that is what it is configured to do by the NPM config you install upon initializing ESLint. However that does not work with prettier.
This answer wound up much longer than I thought it would. Getting Prettier, ESLint & VS Code to work harmoniously together is a very involved task, especially for first timers. I use Babel on top of this AST stack (I made that term up lol, what else would you call it?). If you want to be able to lint documents that contain TC39 ECMAScript Stage-3 Proposals, this includes features such as Private-Members, Static Methods, ect..., then you will need to use configure ESLint to use Babel's parser.

twitter bootstrap css clashes while in chrome extensions

I am using bootstrap for a chrome extension I am writing. When imported as content script the css seem to clash with alot of the sites I am viewing (even in google search result page).
Wondering if there is anything i can do to scope this to just the dom elements I inject using content script?
The solution is to use <style scoped>.
Essentially it allows you to apply a style to a DOM node and its children, but not its parent nodes. There's a nice article on CSS-Tricks explaining how to use it.
The problem is that it's not very well supported, even in Chrome, so you'll have to use a jQuery polyfill. This is basically a jQuery plugin that simulates the functionality you'd expect from <style scoped>.
Here's a working JSFiddle doing exactly that using Bootstrap.
Here's an example of how you could implement it in your extension:
content_script.js:
$.scoped(); // Initialize the plugin
...
bootstrapped = document.createElement("div");
bootstrapped.innerHTML = "<style scoped>";
bootstrapped.innerHTML += "#import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');";
bootstrapped.innerHTML += "</style>";
document.body.appendChild(bootstrapped);
...
document.body.appendChild(myDOM); // Will not possess Bootstrap styles
bootstrapped.appendChild(myDOM); // Will possess Bootstrap styles
For now, make sure to include jQuery in your page, as well as the Scoped Plugin:
"content_scripts": [ {
"js": [ "jquery.min.js", "jquery.scoped.min.js", "content_script.js" ],
"matches": [ "http://*" ]
}]