migrate from webpack to vite with vuejs for chrome extension project - javascript

I am working on a chrome extension using vuejs currently i have a ready project to start with but it is with webpack.
In the webpack I have multi-entry points some of which lead to generating HTML files and others with javascript only.
with webpack it is clear what is the inputs and how they will be as output in Vite i tried but there is a lot of plugins outdated that work with vuejs 3
this link contains the project
https://stackblitz.com/edit/vue-v83gga
my webpack file is :
const path = require("path");
const fs = require("fs");
// Generate pages object
const pages = {};
function getEntryFile(entryPath) {
let files = fs.readdirSync(entryPath);
return files;
}
const chromeName = getEntryFile(path.resolve(`src/entry`));
function getFileExtension(filename) {
return /[.]/.exec(filename) ? /[^.]+$/.exec(filename)[0] : undefined;
}
chromeName.forEach((name) => {
const fileExtension = getFileExtension(name);
const fileName = name.replace("." + fileExtension, "");
pages[fileName] = {
entry: `src/entry/${name}`,
template: "public/index.html",
filename: `${fileName}.html`,
};
});
const isDevMode = process.env.NODE_ENV === "development";
module.exports = {
pages,
filenameHashing: false,
chainWebpack: (config) => {
config.plugin("copy").use(require("copy-webpack-plugin"), [
{
patterns: [
{
from: path.resolve(`src/manifest.${process.env.NODE_ENV}.json`),
to: `${path.resolve("dist")}/manifest.json`,
},
{
from: path.resolve(`public/`),
to: `${path.resolve("dist")}/`,
},
],
},
]);
},
configureWebpack: {
output: {
filename: `[name].js`,
chunkFilename: `[name].js`,
},
devtool: isDevMode ? "inline-source-map" : false,
},
css: {
extract: false, // Make sure the css is the same
},
};

i finally find out a solution for it as a pre-build template by vitesse written with typescript
https://github.com/antfu/vitesse-webext
in short answer if you want to have multiple entries of HTML files you can add them to the original vite.config.js file
regarding the content.ts file, it needs a different vite.config.content.ts file and we have to call it when we build the project like this
vite build && vite build --config vite.config.content.ts
regarding the vite.config.ts file, the code will be like this written in typescript
/// <reference types="vitest" />
import { dirname, relative } from 'path'
import type { UserConfig } from 'vite'
import { defineConfig } from 'vite'
import Vue from '#vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import WindiCSS from 'vite-plugin-windicss'
import windiConfig from './windi.config'
import { isDev, port, r } from './scripts/utils'
export const sharedConfig: UserConfig = {
root: r('src'),
resolve: {
alias: {
'~/': `${r('src')}/`,
},
},
define: {
__DEV__: isDev,
},
plugins: [
Vue(),
AutoImport({
imports: [
'vue',
{
'webextension-polyfill': [
['*', 'browser'],
],
},
],
dts: r('src/auto-imports.d.ts'),
}),
// https://github.com/antfu/unplugin-vue-components
Components({
dirs: [r('src/components')],
// generate `components.d.ts` for ts support with Volar
dts: r('src/components.d.ts'),
resolvers: [
// auto import icons
IconsResolver({
componentPrefix: '',
}),
],
}),
// https://github.com/antfu/unplugin-icons
Icons(),
// rewrite assets to use relative path
{
name: 'assets-rewrite',
enforce: 'post',
apply: 'build',
transformIndexHtml(html, { path }) {
return html.replace(/"\/assets\//g, `"${relative(dirname(path), '/assets')}/`)
},
},
],
optimizeDeps: {
include: [
'vue',
'#vueuse/core',
'webextension-polyfill',
],
exclude: [
'vue-demi',
],
},
}
export default defineConfig(({ command }) => ({
...sharedConfig,
base: command === 'serve' ? `http://localhost:${port}/` : '/dist/',
server: {
port,
hmr: {
host: 'localhost',
},
},
build: {
outDir: r('extension/dist'),
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r('src/background/index.html'),
options: r('src/options/index.html'),
popup: r('src/popup/index.html'),
},
},
},
plugins: [
...sharedConfig.plugins!,
// https://github.com/antfu/vite-plugin-windicss
WindiCSS({
config: windiConfig,
}),
],
test: {
globals: true,
environment: 'jsdom',
},
}))
the important part of it is this
vite.config.ts
...
build: {
outDir: r('extension/dist'),
emptyOutDir: false,
sourcemap: isDev ? 'inline' : false,
// https://developer.chrome.com/docs/webstore/program_policies/#:~:text=Code%20Readability%20Requirements
terserOptions: {
mangle: false,
},
rollupOptions: {
input: {
background: r('src/background/index.html'),
options: r('src/options/index.html'),
popup: r('src/popup/index.html'),
},
},
},
...
Thank you to anyone who tried to help and I hope this will be helpful to others
Regards

Related

Vite project builds locally but not in CI - Buffer issue

Locally, Vite builds just fine. However, in CI (which just runs the same script, npm run build), it fails.
I get this error in CI:
Error: "Buffer" is not exported by "__vite-browser-external", imported by "src/index.html?html-proxy&index=0.js".
file: /home/runner/work/explorer/explorer/src/index.html?html-proxy&index=0.js:2:13
1:
2: import { Buffer } from "buffer";
^
3: window.Buffer = Buffer;
Error: error during build:
RollupError: "Buffer" is not exported by "__vite-browser-external", imported by "src/index.html?html-proxy&index=0.js".
I added the line that is causing the error because of an issue when running vite serve locally (it errors) - StackOverflow suggested this solution. It builds fine even in CI without that line.
Here's my Vite config:
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import viteTsconfigPaths from 'vite-tsconfig-paths'
import svgrPlugin from 'vite-plugin-svgr'
import { createHtmlPlugin } from 'vite-plugin-html'
import EnvironmentPlugin from 'vite-plugin-environment'
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
export default defineConfig({
root: './src',
envDir: '..',
build: {
// relative to the root
outDir: '../build',
},
// relative to the root
publicDir: '../public',
server: {
open: true,
port: 3000,
proxy: {
'/api': 'http://localhost:5001',
},
},
define: { 'process.env': {} },
resolve: {
alias: {
events: 'events',
stream: 'stream-browserify',
zlib: 'browserify-zlib',
'util/': 'util',
},
},
optimizeDeps: {
esbuildOptions: {
define: {
// Node.js global to browser globalThis
global: 'globalThis',
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true,
}),
],
},
},
plugins: [
svgrPlugin({
exportAsDefault: true,
}),
react({
// Use React plugin in all *.jsx and *.tsx files
include: '**/*.{jsx,tsx}',
}),
createHtmlPlugin({
inject: {
data: {
VITE_GA_ID: process.env.VITE_GA_ID,
VITE_ZENDESK_KEY: process.env.VITE_ZENDESK_KEY,
},
},
}),
EnvironmentPlugin('all'),
NodeGlobalsPolyfillPlugin({
buffer: true,
process: true,
}),
viteTsconfigPaths(),
],
test: {
globals: true,
setupFiles: 'src/setupTests.js',
},
})
My build command is DISABLE_NEW_JSX_TRANSFORM=true vite build --emptyOutDir
My serve command is DISABLE_NEW_JSX_TRANSFORM=true vite serve

Huge chunk sizes due to dynamic json imports in production build

I have a vite SPA and use dynamic imports to load my json files. Since I need to load numerous very large json files, the index.js file in my /dist becomes too big in my production build.
What is the best way to import these json files dynamically but still keep small chunks? Can I import somehow the json files dynamically as own chunks, similar to images and videos with hashes?
Here my vite.config.js
import path from 'path'
import { defineConfig } from 'vite'
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'
import { createHtmlPlugin } from 'vite-plugin-html'
import svgr from 'vite-plugin-svgr'
import legacy from '#vitejs/plugin-legacy'
import react from '#vitejs/plugin-react'
import { name } from './package.json'
export default defineConfig({
base: '/widgets/' + name + '/',
server: {
open: true, // Define a BROWSER in your .env-File to specify which browser. Defaults to Chrome. https://vitejs.dev/config/#server-open
port: 3000,
},
resolve: {
alias: {
'#Assets': path.resolve(__dirname, 'src/assets'),
'#Components': path.resolve(__dirname, 'src/components'),
'#Examples': path.resolve(__dirname, 'src/examples'),
'#Scripts': path.resolve(__dirname, 'src/scripts'),
'#Styles': path.resolve(__dirname, 'src/assets/styles'),
'#Cms': path.resolve(__dirname, 'src/assets/styles/cms'),
},
},
css: {
devSourcemap: true, // needed for css imported in cms template
},
define: {
__DATA_PATH__: JSON.stringify(process.env.npm_package_config_dataPath),
},
build: {
rollupOptions: {
output: {
entryFileNames: `[name].js`,
chunkFileNames: `[name].js`,
assetFileNames: `[name].[ext]`,
},
},
},
plugins: [
legacy({
polyfills: true,
}),
react(),
createHtmlPlugin({
minify: true,
inject: {
data: {
title: name,
id: name,
},
},
}),
cssInjectedByJsPlugin(),
svgr(),
],
})
You can try this configuration:
// vite.config.ts
build: {
chunkSizeWarningLimit: 500, // default 500 KB
},
https://vitejs.dev/config/build-options.html#build-chunksizewarninglimit

How do I remove vue spec files from vite config

I've succesfully added vite to my project. It builds fine for prodiction. However in Production I have an error
Uncaught ReferenceError: describe is not defined
at index.ba9d79ff.js:1119:1426
I then saw the my .spec files where being added. I thought vite would of handled the removal of the test files. I want to remove my .spec files from production.
but not having such luck. I'm using Vue 2 with vite. I added
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
but the files are still being added. Is there something more I need to do?
My config
import { defineConfig } from "vite";
import { createVuePlugin as vue } from "vite-plugin-vue2";
import { VuetifyResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
// https://vitejs.dev/config/const
const path = require("path");
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [
// Vuetify
VuetifyResolver(),
],
}),
],
resolve: {
extensions: [
".mjs",
".js",
".ts",
".jsx",
".tsx",
".json",
".vue",
".scss",
],
alias: {
"#": path.resolve(__dirname, "./src"),
json2csv: "json2csv/dist/json2csv.umd.js",
"~bootstrap": "bootstrap",
},
},
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
extensions: etc,
css: {
preprocessorOptions: {
scss: {
// additionalData: `#import "src/scss/app.scss";`,
// additionalData: `#import "src/scss/_variables.scss";`,
sourceMap: false,
additionalData(source, fp) {
// All scss files ending with imports.scss
// will not re-import additionalData
if (fp.endsWith("_variables.scss")) return source;
// Use additionalData from legacy nuxt scss options
// return `#import "#/assets/mixin.scss"; ${source}`;
return `#import "src/scss/_variables.scss"; ${source}`;
},
},
},
},
server: {
port: 8090,
},
});

How use sql.js-httpvfs library in Gatsby?

I try to use sql.js-httpvfs library inside my project. However, I am not successed yet. I am not expert about node.js.
What I do?
Firstly, need to webpack.config to Gatsby for that I create gatsby-node.js file and add the below code inside it.
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
entry: "./src/index.js",
module: {
rules: [
{
test: "/.tsx?$/",
use: "ts-loader",
exclude: "/node_modules/",
},
],
},
output: {
filename: "bundle.js",
},
devServer: {
publicPath: "/dist",
},
});
};
Inside my index.js page, I add the code;
import { createDbWorker } from "sql.js-httpvfs";
const workerUrl = new URL(
"sql.js-httpvfs/dist/sqlite.worker.js",
import.meta.url
);
const wasmUrl = new URL("sql.js-httpvfs/dist/sql-wasm.wasm", import.meta.url);
function load() {
const worker = createDbWorker(
[
{
from: "inline",
config: {
serverMode: "full",
url: "../myTestDb.sqlite3",
requestChunkSize: 4096,
},
},
],
workerUrl.toString(),
wasmUrl.toString()
);
const result = worker.db.query(`select * from districts`);
document.body.textContent = JSON.stringify(result);
}
load();
But I got error.
There is no any created bundle.js or folder like dist.

Error: You must use the `#babel/plugin-transform-runtime` plugin when `babelHelpers` is "runtime" on npm link

I have 2 react libraries, and one consumes the other.
project-ui
propert-utils
project-utils is installed in project-ui
"devDependencies": {
"#company/project-utils": "git+ssh://git#github.com/company/project-utils.git#main",
},
"dependencies": {
"#company/project-utils": "git+ssh://git#github.com/company/project-utils.git#main",
}
both have the same .babelrc files
{
"env": {
"test": {
"presets": [["#babel/preset-env"], "#babel/preset-react"]
}
},
"presets": [
[
"#babel/preset-env",
{
"modules": false
}
],
"#babel/preset-react"
],
"ignore": ["node_modules/**"],
"plugins": ["#babel/plugin-transform-runtime"]
}
The rollup.config.js in the project-ui is as follows
import babel from '#rollup/plugin-babel';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import postcss from 'rollup-plugin-postcss';
import filesize from 'rollup-plugin-filesize';
import precss from 'precss';
import autoprefixer from 'autoprefixer';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import localResolve from 'rollup-plugin-local-resolve';
import externals from 'rollup-plugin-node-externals';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
import image from 'rollup-plugin-inline-image';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';
const OUTPUT_NAME = 'Example';
const ENVIRONMENT = process.env;
const PRODUCTION = ENVIRONMENT.production || ENVIRONMENT.production === 'true';
const formGlobals = {
formik: 'formik',
'lodash/throttle': 'throttle',
'react-number-format': 'NumberFormat',
'react-ga': 'ReactGA',
};
const GLOBALS = {
react: 'React',
'react-dom': 'ReactDOM',
'react-router-dom': 'reactRouterDom',
'prop-types': 'PropTypes',
formik: 'formik',
'lodash/throttle': 'throttle',
'react-number-format': 'NumberFormat',
'react-ga': 'ReactGA',
'react-dates': 'ReactDates',
'styled-components': 'styled',
'react-tag-autocomplete': 'ReactTags',
'react-spinkit': 'Spinner',
'react-select': 'Select',
'#fortawesome/fontawesome-svg-core': 'fontawesomeSvgCore',
'#fortawesome/react-fontawesome': 'reactFontawesome',
'#fortawesome/pro-regular-svg-icons': 'proRegularSvgIcons',
'#fortawesome/free-brands-svg-icons': 'freeBrandsSvgIcons',
'#fortawesome/pro-solid-svg-icons': 'proSolidSvgIcons',
};
const PLUGINS = ({ cssPlugin }) => {
return [
PRODUCTION && globals(),
PRODUCTION && builtins(),
PRODUCTION && externals(),
babel({
babelHelpers: 'runtime',
exclude: 'node_modules/**',
presets: ['#babel/env', '#babel/preset-react'],
}),
commonjs({
include: 'node_modules/**',
}),
PRODUCTION && peerDepsExternal(),
postcss({ extract: cssPlugin, plugins: [autoprefixer, precss] }),
PRODUCTION && json({ include: 'node_modules/**' }),
PRODUCTION && localResolve(),
resolve({
browser: true,
resolveOnly: [/^(?!react$)/, /^(?!react-dom$)/, /^(?!prop-types)/],
}),
PRODUCTION && filesize(),
image(),
PRODUCTION && terser(),
];
};
const EXTERNAL = [
...Object.keys(pkg.peerDependencies || {}),
...Object.keys(pkg.dependencies || {}),
'lodash/throttle',
'formik',
'react-dates/initialize',
'react-dates/lib/css/_datepicker.css',
];
const CJS_AND_ES_EXTERNALS = EXTERNAL.concat(/#babel\/runtime/);
const OUTPUT_DATA = (dir) => {
const umd = {
file: dir ? `/index.js` : pkg.browser,
format: 'umd',
};
const cjs = {
file: dir ? `/index.cjs.js` : pkg.main,
format: 'cjs',
};
const es = {
file: dir ? `/index.esm.js` : pkg.module,
format: 'es',
};
return [{ ...umd }, { ...cjs }, { ...es }];
};
const WATCH = {
chokidar: {
usePolling: true,
paths: 'src/**',
},
};
const OUTPUT_FILES = [
{
input: 'src/form/index.js',
output: 'form',
cssPlugin: false,
globals: formGlobals,
},
{
input: 'src/buttons/index.js',
output: 'buttons',
cssPlugin: false,
},
{
input: 'src/theme/index.js',
output: 'theme',
cssPlugin: false,
},
{
input: 'src/icons/index.js',
output: 'icons',
cssPlugin: false,
},
{
input: 'src/icons/index.js',
output: 'icons',
cssPlugin: false,
},
{
input: 'src/interactive/index.js',
output: 'interactive',
cssPlugin: false,
},
];
const arr = [];
const config = arr.concat.apply(
[],
OUTPUT_FILES.map(({ input, output, cssPlugin }) =>
OUTPUT_DATA(output).map(({ file, format }) => ({
input,
output: {
file: `${output}${file}`,
format,
name: OUTPUT_NAME,
globals: GLOBALS,
},
watch: WATCH,
external: ['cjs', 'es'].includes(format) ? CJS_AND_ES_EXTERNALS : EXTERNAL,
plugins: PLUGINS(cssPlugin),
}))
)
);
export default config;
The rollup.config.js in the project-utils is as follows
import babel from '#rollup/plugin-babel';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import postcss from 'rollup-plugin-postcss';
import filesize from 'rollup-plugin-filesize';
import precss from 'precss';
import autoprefixer from 'autoprefixer';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import localResolve from 'rollup-plugin-local-resolve';
import externals from 'rollup-plugin-node-externals';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';
import image from 'rollup-plugin-inline-image';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';
const OUTPUT_NAME = 'Example';
const ENVIRONMENT = process.env;
const PRODUCTION = ENVIRONMENT.production || ENVIRONMENT.production === 'true';
const GLOBALS = {
react: 'React',
'react-dom': 'ReactDOM',
'prop-types': 'PropTypes',
'whatwg-fetch': 'whatwgFetch',
'file-saver': 'fileSaver',
'resize-observer-polyfill': 'ResizeObserver',
'dinero.js': 'Dinero',
'#auth0/auth0-react': 'auth0React',
};
const PLUGINS = ({ cssPlugin }) => {
return [
PRODUCTION && globals(),
PRODUCTION && builtins(),
PRODUCTION && externals(),
babel({
babelHelpers: 'runtime',
exclude: 'node_modules/**',
presets: ['#babel/env', '#babel/preset-react'],
}),
commonjs({
include: 'node_modules/**',
}),
PRODUCTION && peerDepsExternal(),
postcss({ extract: cssPlugin, plugins: [autoprefixer, precss] }),
PRODUCTION && json({ include: 'node_modules/**' }),
PRODUCTION && localResolve(),
resolve({
browser: true,
resolveOnly: [/^(?!react$)/, /^(?!react-dom$)/, /^(?!prop-types)/],
}),
PRODUCTION && filesize(),
image(),
PRODUCTION && terser(),
];
};
const EXTERNAL = [
...Object.keys(pkg.peerDependencies || {}),
...Object.keys(pkg.dependencies || {}),
];
const CJS_AND_ES_EXTERNALS = EXTERNAL.concat(/#babel\/runtime/);
const OUTPUT_DATA = (dir) => {
const umd = {
file: dir ? `/index.js` : pkg.browser,
format: 'umd',
};
const cjs = {
file: dir ? `/index.cjs.js` : pkg.main,
format: 'cjs',
};
const es = {
file: dir ? `/index.esm.js` : pkg.module,
format: 'es',
};
return [{ ...umd }, { ...cjs }, { ...es }];
};
const WATCH = {
chokidar: {
usePolling: true,
paths: 'src/**',
},
};
const OUTPUT_FILES = [
{
input: 'src/api/index.js',
output: 'api',
cssPlugin: false,
},
{
input: 'src/utils/index.js',
output: 'utils',
cssPlugin: false,
},
{
input: 'src/hooks/index.js',
output: 'hooks',
cssPlugin: false,
},
{
input: 'src/hooks/hooks-api/index.js',
output: 'hooks/hooks-api',
cssPlugin: false,
},
];
const arr = [];
const config = arr.concat.apply(
[],
OUTPUT_FILES.map(({ input, output, cssPlugin }) =>
OUTPUT_DATA(output).map(({ file, format }) => ({
input,
output: {
file: `${output}${file}`,
format,
name: OUTPUT_NAME,
globals: GLOBALS,
},
watch: WATCH,
external: ['cjs', 'es'].includes(format) ? CJS_AND_ES_EXTERNALS : EXTERNAL,
plugins: PLUGINS(cssPlugin),
}))
)
);
export default config;
I have a single import to the project-utils in the project-ui
import { useResize } from '#company/project-utils/hooks';
Now, when I run npx rollup -c --watch on the project-ui everything works as expected. That import works fine, there are no console errors.
However, when I run npm link #company/project-utils it does link it up correctly but I get the following error in the console.
rollup v2.39.0
bundles src/form/index.js → form/index.js...
[!] (plugin babel) Error: You must use the `#babel/plugin-transform-runtime` plugin when `babelHelpers` is "runtime".
../project-utils/hooks/index.js
Error: You must use the `#babel/plugin-transform-runtime` plugin when `babelHelpers` is "runtime".
at error (/Users/aaron/git/project-ui/node_modules/rollup/dist/shared/rollup.js:5275:30)
at throwPluginError (/Users/aaron/git/project-ui/node_modules/rollup/dist/shared/rollup.js:18232:12)
at Object.error (/Users/aaron/git/project-ui/node_modules/rollup/dist/shared/rollup.js:18839:24)
at Object.error (/Users/aaron/git/project-ui/node_modules/rollup/dist/shared/rollup.js:18401:38)
at preflightCheck (/Users/aaron/git/project-ui/node_modules/#rollup/plugin-babel/dist/index.js:222:11)
I have ensured that I am on the same branch as the package.json defines for the project-utils .I have run a build npx rollup -c --environment=production and also tried to run a watch npx rollup -c --watch on the project-utils but still coming back with the same error.
This works fine for a colleague of mine but we are left scratching our heads why it's failing on my end.
Any help would be greatly appreciated.
The solution is to use babel.config.js and not .babelrc

Categories

Resources