How can I drop console in a VITE2 project? - vuejs3

I tried to drop console for my Vite2 project. I googled and found the terserOptions, however, it didn't work. So I just create a blank template from the offical site with the following code.
yarn create vite my-vue-app --template vue
And then add some console.log on Helloworld page.
the vite.config.js is below:
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
export default defineConfig({
base: "./",
plugins: [vue()],
bulid: {
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
},
});
After I build the project, the console.log still there. So what's the right way to drop_console on a project built by vite2?

You need to specify in build.minify to use terser.
If not set, terserOptions is ignored as it defaults to using esbuild.
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
export default defineConfig({
base: "./",
plugins: [vue()],
bulid: {
minify: 'terser', // <-- add
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true,
},
},
},
});
This setting removes console.* at build time.

If you want to use esbuild, you can use this:
esbuild: {
drop: ['console', 'debugger'],
}

Related

Vite import generetad chunks in index.js with url

in my Vue3 project I import the components in the router index.js like that:
{
path: settingsStore.startUri,
name: "home",
component: () => import("../views/Home/Home.vue"),
},
My vite.config looks like that:
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import vuetify from "vite-plugin-vuetify";
const path = require("path");
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
vuetify({
autoImport: true,
}),
],
define: {
"process.env": {},
__VUE_I18N_FULL_INSTALL__: true,
__VUE_I18N_LEGACY_API__: false,
__INTLIFY_PROD_DEVTOOLS__: false,
},
resolve: {
alias: {
"#": path.resolve(__dirname, "src"),
},
},
build: {
rollupOptions: {
output: {
entryFileNames: "news-[name].js",
assetFileNames: "news-[name].[ext]",
manualChunks: undefined,
chunkFileNames: "chunks/[name].js",
},
},
},
optimizeDeps: {
include: ["vue", "axios"],
},
});
When I run npm run build it creates a chunk directory with some smaller .js files beeing imported in the index.js but as relativ paths like that:
import("./chunks/Home.js")
But I need to import the files from an url like that:
import("https://example.com/chunks/Home.js")
Does anyone know if thats possible and how can I do that?
I tried a lot, read a lot of documentations but didnt find an answer

Laravel vite won't process custom css

I am trying to inject my custom css in built css file but it does not process resources/css/app.css file
vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/sass/app.scss',
'resources/js/app.js',
],
refresh: true,
}),
],
resolve: {
alias: {
'$': 'jQuery'
},
},
});
resources/css/app.css
h2.swal2-title {
font-size: 1.2em !important;
}
This css does not add to generate css file by npm run build
Any idea?

TailwindCSS 3.0 Upgrade overriding button styles

Problem:
Button class being overridden by default tailwind base classes. Not sure why my classes on the element aren't being applied.
Question:
How can I get my styles to apply properly?
Screenshot:
As you can see background color on .documentCategory__row is being overridden by button, [type=button] on index.scss which is being defined within #tailwind/base.
/* index.scss */
:root {
--color-primary: #00a3e0;
--color-secondary: #470a68;
--color-success: #87d500;
--color-accent: #e87722;
/* Dark themes below */
--color-dark-primary: rgba(31, 41, 55, 1);
--dark-text: rgba(187, 193, 198, 1);
}
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
I'm not sure if this has to do with me switching to dart-scss so here is my webpack configuration in case I am missing something
import path from 'path'
import { Configuration as WebpackConfiguration, HotModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
hot: true,
},
output: {
publicPath: '/',
},
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new HotModuleReplacementPlugin(),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config
If there are other files I am missing that are needed let me know!
without seeing what your index.tsx looks like I can only make a guess, but here's what caused this issue in our app:
in our index.tsx we were importing index.css after importing our component tree with import App from 'src/App. thus the css was loaded into the site in the wrong order. imports from components first (css modules, normal css imports), tailwind last.
go to your entry file (probably index.tsx) and try moving your import 'index.scss' line above importing the root component.
like this for example
/* index.tsx */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'; // this file holds all tailwind styles
import { App } from 'src/App';
// ...
read more here:
https://github.com/tailwindlabs/tailwindcss/discussions/7304#discussioncomment-2256226
Even i faced the same issue but I am using Vue3 + element-ui-plus, after spending more than 6 hours my solution is to set :native-type='null':
<el-button type='primary' round #click='handleClick' :native-type='null'>Click Me</el-button>
but this is kinda "hack", this either need to be fixed by Tailwind or by element-ui team. Anyhow, for now enjoy ;)
And the discussion is on here
I got the same issue using tailwindcss v3 and NextUI, and button's background were "transparent". By adding type = {null}, to button's I solve the issue

Tailwind css classes not showing in Storybook build

I am trying to build my storybook with tailwind css. When running build-storybook the components are rendered with the tailwind classes. Unfortunately, when I build storybook and run the create build storybook-static with npx http-server storybook-static the classes are not loaded into the stories and the components are displayed not styled.
This is a repro repo of my project:
https://gitlab.com/ens.evelyn.development/storybook-issue
This is my main.js :
const path = require('path')
module.exports = {
"stories": [
"../src/components/**/**/*.stories.mdx",
"../src/components/**/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials",
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
"#storybook/addon-actions",
"storybook-tailwind-dark-mode"
]}
My Projectstructure looks like this:
.storybook
src
components
subdir
Button
index.tsx
button.stories.js
styles
index.css (<-- tailwindcss file)
Any hints or advice is very appreciated.
UPDATE: My original answer could be useful to others, so I'll leave it for reference. However, in this case, the problem was in tailwind.config.js.
Change
purge: {
mode: 'all',
content: [
'./src/components/**/**/*.{ts, tsx}'
],
},
to
purge: ['./src/**/*.{js,jsx,ts,tsx}'],
ORIGINAL:
Just tested it out and storybook builds as expected for me. I think the key difference in our configurations is that I am not making changes to Storybook's webpack config in main.js. Rather, I am using #storybook/addon-postcss for postcss#^8 (required for tailwind#^2):
// main.js
module.exports = {
...
addons: [
...
{
name: '#storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
],
};
I specify the necessary plugins in a postcss.config.js (in my project root):
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
It's also worth noting that I import Tailwind directly in Storybook's preview.js instead via my own css file:
// preview.js
import 'tailwindcss/tailwind.css';
export const parameters = {...}
Hopefully, making those changes will get Tailwind working for you.
For comparison (see comments below), here are the contents of my build storybook-static directory:
The above solutions will not work for Tailwind version > 3.0 because of JIT compiler.
Solution 1: Easy solution
in .storybook/preview.js file add this line to compile tailwind generated css files like this -
import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
Here tailwindcss/tailwind.css is the tailwind css file. Look, important is I've to add !postcss-loader! to compile tailwind generated css.
You can add also your custom scss file like this if any -
import '!style-loader!css-loader!sass-loader!../src/scss/style.scss';
Here ../src/scss/style.scss is custom scss file.
For most of the people this will work in Tailwind version > 3.0 without any issue.
Solution 2: Kinda Hack solution
Create a custom styled element in preview page
import tailwindCss from '!style-loader!css-loader!postcss-loader!sass-loader!tailwindcss/tailwind.css';
const storybookStyles = document.createElement('style');
storybookStyles.innerHTML = tailwindCss;
document.body.appendChild(storybookStyles);
Hope, this will help for new Tailwind users who are working in Tailwind greater than v3.0.
I had a similar problem. My problem was solved by adding:
import "../src/index.css"; to .storybook/preview.js
The following configuration will enable so Tailwind generate CSS as new tailwind classes are added to the markup in dev mode (hot reload).
In summary, I don't think #storybook/addon-postcss works with Tailwind JIT and Storybook hot reload, and the workaround is to use the postcss-loader webpack loader.
Install these deps:
#storybook/builder-webpack5
#storybook/manager-webpack5
postcss-loader
webpack (must be version 5)
// .storybook/main.js
const path = require("path");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.#(js|jsx|ts|tsx)"],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/addon-interactions",
// {
// name: "#storybook/addon-postcss",
// options: {
// postcssLoaderOptions: {
// implementation: require("postcss"),
// },
// },
// },
],
framework: "#storybook/react",
core: {
builder: "webpack5",
},
webpackFinal: (config) => {
config.module.rules.push({
test: /\.css$/,
use: [
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
},
],
include: path.resolve(__dirname, "../"),
});
return config;
},
};
// .storybook/preview.js
import "../styles/globals.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
if you using storybook with TSdx and tailwind css you should be able to import a CSS into components
To be able to import your CSS into components, you will need to tell
TSDX how to include it with your code. For that, you will need to
install rollup-plugin-postcss (as TSDX uses rollup).
Create a CSS file in your src directory which we will use in any
component in which we want to use Tailwind.
Alright, so now let's add rollup-plugin-postcss:
yarn add -D rollup-plugin-postcss
TSDX is fully customizable and you can add any rollup plugin, but be aware that it overrides the default behavior
Now you'll create a
tsdx.config.js
// tsdx.config.js
const postcss = require('rollup-plugin-postcss');
module.exports = {
rollup(config, options) {
config.plugins.push(
postcss({
config: {
path: './postcss.config.js',
},
extensions: ['.css'],
minimize: true,
inject: {
insertAt: 'top',
},
})
);
return config;
},
};
This is giving a postCSS path, which tells it what files you want it to run on. The minimize key is to allow you to minimize the output. The most important key here is the "inject". you set it to "top" to tell postCSS where inside the of our page the CSS will be inserted. It's paramount for Tailwind as it needs to have the utmost priority of any other stylesheet.
Next, for part 2, you will create a tailwind.css (can be named anything else) file under the src directory and paste this in:
// src/tailwind.css
#tailwind base;
#tailwind components;
#tailwind utilities;
Add the CSS import statement to your component
// src/Thing.tsx
import React, { FC, HTMLAttributes, ReactChild } from 'react';
// ! Add the CSS import statement !
import './tailwind.css`;
// ...
// we'll add some Tailwind classes on our components to test
export const Thing: FC<Props> = ({ children }) => {
return (
<div className="flex items-center justify-center w-5/6 m-auto text-2xl text-center text-pink-700 uppercase bg-blue-300 shadow-xl rounded-3xl">
{children || `the snozzberries taste like snozzberries`}
</div>
);
};
For those who are still having this problem and is using postcss >= 8, I suggest you to do as following.
Add this to tailwind.config.js
// eslint-disable-next-line #typescript-eslint/no-var-requires
const path = require("path")
module.exports = {
content: [path.join(__dirname, "./src/**/*.(js|jsx|ts|tsx)")],
theme: {
extend: {},
},
variants: {}
plugins: [],
}
Add this to preview.js
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css"
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}
This has helped me fix the problem and I hope it can help you too
I couldn't work this out and the above answered didn't work for me, so I eventually just set my build-storybook script to run tailwind itself after the build. package.json scripts looked like this in the end:
"build-storybook": "build-storybook -s public && $(npm bin -g)/tailwindcss -i storybook-static/static/css/main.*.chunk.css -o storybook-static/static/css/main.*.chunk.css -m",
Bit of a mess, but $(npm bin -g)/ here uses my globally installed (npm i -g tailwindcss) version of tailwindcss as the version installed to the project wasn't working in builds for me.
-i and -o specifies the input and output files, and -m minifies the output.
I can foresee this causing problems if more than one CSS file gets built (maybe using storybook-static/static/css/**/*.css would work instead?), but this might help someone just get something working.
When you try to create a storybook while using Tailwind CSS, you will notice that the CSS is not being applied. There is a simple solution that has helped me.
Your preview.js should be like.
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
And you will need to add the following line in the preview.js to fix it.
// Add the below import line
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
However this will be a temporary fix.
To get this resolved completely, you will need to add the below mentioned package.
yarn add -D #storybook/addon-postcss
For reference, click here
How to add postcss
The solutions mentioned above worked but only partially.
I was facing 2 issues:
If I added new classes to stories then tailwind was not adding corresponding styles associated with the classes.
Hot reloading wasn't working.
Solution:
Add the path to the stories folder in the tailwind.config.js file.
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./stories/**/*.{js,ts,jsx,tsx}", //needed to make hot reload work with stories
],
theme: {},
plugins: [],
}

is it possible to use rollup for processing just css?

I know that Rollup is used to bundle .js files. But is it possible to use it just to process css? (css, scss, less, etc).
What i mean is if i had for example in my src folder (the entry folder) a file called index.css and i want rollup to precess it at dist folder (the output folder) like index.css (but processed, for example if there is an imported .sass file or css variables).
How can i do this?
Example rollup.config.js
import { uglify } from 'rollup-plugin-uglify'
import babel from 'rollup-plugin-babel'
import resolve from 'rollup-plugin-node-resolve';
import postcss from 'rollup-plugin-postcss'
const config = [
{
input: 'src/styles/index.scss',
output: {
file: 'dist/style.css',
name: "style",
},
plugins: [
postcss({
plugins: []
})
]
},
];
export default config
src/index.scss:
#import 'other';
h1 {
color: green;
}
src/other.scss
h2 {
color: red;
}
and in the dist folder should be an index.css with the all the code for both css files (and processed).
Something like this:
dist/index.css
h1 {
color: green;
}
h2 {
color: red;
}
You need something like this
import postcss from 'rollup-plugin-postcss'
const config = [
{
input: 'src/styles/index.scss',
output: {
file: 'dist/style.css',
format: 'es'
},
plugins: [
postcss({
modules: true,
extract: true
})
]
},
];
export default config
Just to add to the answer of #Iván and if anyone else gets the error message The emitted file "Filename.css" overwrites a previously emitted file of the same name.:
The postCSS plugin has the option extract: true (like also shown in Iváns answer). When set to true it will create a separate CSS file. So what you can basically do is the following:
Create JS file
Import your styles in the JS file (e.g.: import "../css/index.css" ##Adapt path to your needs)
Now add postCSS to your plugin config:
...
plugins: [
postcss({
modules: true,
extract: true
}),
resolve({
jsnext: true,
browser: true,
}),
commonjs(),
production && terser(),
],
...
This will output a separate CSS file.
Now add the CSS file to your template
Extra: A full config could look like this:
import resolve from "#rollup/plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
const production = !process.env.ROLLUP_WATCH;
export default [
{
input: "project/static/src/inputs/index.js",
output: [
{
format: "esm",
name: "map",
file: "project/static/src/outputs/index.min.js",
},
],
plugins: [
postcss({
modules: true,
extract: true
}),
resolve({
jsnext: true,
browser: true,
}),
commonjs(),
production && terser(),
],
},
];

Resources