Vite.js build with lib option not loading react app - rollup

Below is my current vite config.js/ package.json and tsconfig.json with build with lib configuration, it worked properly using with normal vite build but fails does not work on build lib.
The files are generated in dist folder but app doesn't loads
vite.config.js
`/* eslint-disable import/no-extraneous-dependencies */
import reactRefresh from '#vitejs/plugin-react-refresh';
import path from 'path';
import { Alias, defineConfig } from 'vite';
import * as tsconfig from './tsconfig.paths.json';
function readAliasFromTsConfig(): Alias[] {
const pathReplaceRegex = new RegExp(/\/\*$/, '');
return Object.entries(tsconfig.compilerOptions.paths).reduce(
(aliases, [fromPaths, toPaths]) => {
const find = fromPaths.replace(pathReplaceRegex, '');
const toPath = toPaths[0].replace(pathReplaceRegex, '');
const replacement = path.resolve(__dirname, toPath);
aliases.push({ find, replacement });
return aliases;
},
[] as Alias[],
);
}
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, "src/main.tsx"),
name: "Aagam",
},
rollupOptions: {
external: ["react"],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
react: 'React',
},
},
},
minify: true,
sourcemap: false,
},
plugins: [reactRefresh()],
resolve: {
alias: readAliasFromTsConfig(),
},
css: {
modules: { localsConvention: 'camelCase' },
preprocessorOptions: {
scss: {
additionalData: `$injectedColor: orange;`
}
}
}
});
> `
package.json
"name": "reporting-ui-component",
"version": "1.0.0",
"files": [
"dist"
],
"typings": "./dist/reporting-ui-component.d.ts",
"main": "./dist/reporting-ui-component.umd.js",
"module": "./dist/reporting-ui-component.es.js",
"scripts": {
"dev": "vite",
"build": "tsc && vite build && tsc -P tsconfig.dts.json",
"serve": "vite preview",
"start": "npm run dev",
"lint:fix": "eslint src --ext .jsx,.js,.ts,.tsx --quiet --fix",
"lint:format": "prettier --loglevel warn --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\" ",
"lint": "yarn lint:format && yarn lint:fix ",
"type-check": "tsc",
"lint-staged": "npx lint-staged -r",
"validate": "npm run style",
"validate-commit": "npm run lint-staged",
"style": "npx -q eslint src --ext .ts,.tsx --fix"
}
tsconfig.dts.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"declaration": true,
"declarationDir": "dist",
"emitDeclarationOnly": true
},
"include": ["src"]
}
It would be great if you could provide some solution to it?
I am getting error on running above config

In order to make sure your project is rendered from the output generated by lib, make sure to refer the start point of your app i.e. index.html to have the below script
<script src="/dist/<your-file-name>.umd.js"></script>
in place of previous path
<script type="module" src="/src/main.tsx"></script>
and it should start working

Related

Nuxt 'npm run dev' running but the webpage is not responding and won't load

I have been working with nuxt for my personal website. but suddenly the page won't load even though my nuxt dev running perfectly on the console. here is my nuxt-config.js:
// import { auth } from 'firebase'
import colors from 'vuetify/es5/util/colors'
export default {
srcDir: 'src/',
components: {
// global: true,
dirs: [
'~/components',
'~/components/main',
'~/components/user',
'~/components/feedback',
'~/components/auxiliary',
],
},
buildDir: 'functions/.nuxt',
mode: 'universal',
/*
** Headers of the page
*/
head: {
custom title page
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || '',
},
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
/*
** Customize the progress-bar color
*/
loading: { color: '#5f24', size: '30px' },
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
*/
plugins: [
'~/plugins/components.js',
'~/plugins/icons-fa.js',
'~/plugins/filter.js',
],
/*
** Nuxt.js dev-modules
*/
buildModules: ['#nuxtjs/vuetify'],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
// Doc: https://github.com/nuxt-community/dotenv-module
'#nuxtjs/dotenv',
['vue-scrollto/nuxt', { duration: 1000 }],
[
'#nuxtjs/firebase',
{
config: {
serverDev: {
apiKey: process.env.FIREBASE_API_KEY_DEV,
authDomain: process.env.FIREBASE_AUTH_DOMAIN_DEV,
databaseURL: process.env.FIREBASE_DATABASE_URL_DEV,
projectId: process.env.FIREBASE_PROJECT_ID_DEV,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET_DEV,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_DEV,
appId: process.env.FIREBASE_APP_ID_DEV,
measurementId: process.env.FIREBASE_MEASUREMENT_ID_DEV,
},
serverPrd: {
apiKey: process.env.FIREBASE_API_KEY_PRD,
authDomain: process.env.FIREBASE_AUTH_DOMAIN_PRD,
databaseURL: process.env.FIREBASE_DATABASE_URL_PRD,
projectId: process.env.FIREBASE_PROJECT_ID_PRD,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET_PRD,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_PRD,
appId: process.env.FIREBASE_APP_ID_PRD,
measurementId: process.env.FIREBASE_MEASUREMENT_ID_PRD,
},
},
services: {
auth: true,
firestore: true,
storage: true,
analytics: true,
functions: true,
},
onFirebaseHosting: true,
customEnv: true,
},
],
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
baseURL: process.env.BASE_URL,
credentials: false,
},
/*
** vuetif module configuration
** https://github.com/nuxt-community/vuetify-module
*/
vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
dark: false,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3,
},
},
},
icons: {
iconfont: ['mdi', 'fa'],
},
},
/*
** Build configuration
*/
build: {
extractCSS: true,
extend(config, ctx) {},
transpile: ['vuetify/lib'],
babel: {
plugins: [['#babel/plugin-proposal-private-methods', { loose: true }]],
},
},
env: {
baseURL: process.env.BASE_URL,
apiKey: null,
FIRE_ENV: process.env.FIRE_ENV,
// Declare another env here
},
pageTransition: {
name: 'fade',
mode: 'out-in',
},
pluginOptions: {
ssr: {
nodeExternalsWhitelist: [/^vuetify/],
},
},
}
and here is my package-lock.json:
{
"name": "",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "FIRE_ENV=serverDev nuxt",
"build": "FIRE_ENV=serverPrd nuxt build",
"start": "FIRE_ENV=serverPrd nuxt start",
"generate": "FIRE_ENV=serverPrd nuxt generate",
"build:firebase": "FIRE_ENV=serverPrd npm run clean && npm run build && npm run copy && cd \"functions\" && npm i",
"clean": "npm run clean:public && npm run clean:functions && npm run clean:static",
"clean:functions": "rimraf \"functions/node_modules\" && rimraf \"functions/.nuxt\"",
"clean:public": "rimraf \"public/**/*.*!(md)\" && rimraf \"public/_nuxt\"",
"clean:static": "rimraf \"src/static/sw.js\"",
"copy": "npm run copy:nuxt && npm run copy:static",
"copy:nuxt": "mkdir public/_nuxt && cp -r functions/.nuxt/dist/* public/_nuxt",
"copy:static": "cp -r src/static/* public",
"start:firebase": "FIRE_ENV=serverPrd firebase serve --only functions,hosting",
"deploy": "FIRE_ENV=serverPrd firebase deploy --only functions,hosting"
},
"dependencies": {
"#loadingio/loading.css": "^2.0.1",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/firebase": "^7.6.1",
"#vue/compiler-dom": "^3.2.45",
"core-js": "^3.9.1",
"express": "^4.18.2",
"firebase": "^8.10.1",
"firebase-admin": "^11.4.1",
"firebase-functions": "^4.1.1",
"nuxt": "^2.15.3",
"vue": "^2.7.14",
"vue-scrollto": "^2.20.0"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.3",
"#mdi/js": "^5.9.55",
"#nuxtjs/vuetify": "^1.12.3",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"material-design-icons-iconfont": "^6.1.0",
"prettier": "^2.2.1"
}
}
there are no error or warning, either on the server and client.
I have tried removing the package-lock.json, node_modules folder and .nuxt folder then npm install again but it still not working. I also tried using npm -i --legacy-peer-deps also not helping. any ideas what is wrong with my project? or shall i migrate to nuxt3?
Thank you

wrangler dev failed using #cfworker/web

I'm trying to deploy a project on Cloudflare workers using wrangler. I'm using the #cfworker/web package for routing. I've only setup a route at / for testing but it doesn't seem to work.
Here's the dev output:
> wrangler dev
./node_modules/#cfworker/web/dist/application.js 31:30
Module parse failed: Unexpected token (31:30)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| }
| catch (err) {
> console.error(err?.stack ?? err);
| if (err instanceof HttpError) {
| return err.toResponse();
# ./node_modules/#cfworker/web/dist/index.js 3:0-33 3:0-33
# ./src/index.ts
Error: webpack returned an error. Try configuring `entry` in your webpack config relative to the current working directory, or setting `context = __dirname` in your webpack config.
my package.json:
{
"name": "my-project",
"main": "./src/index.ts",
"scripts": {
"dev": "wrangler dev",
"preview": "wrangler preview --watch",
"build": "wrangler build",
"publish": "wrangler publish"
},
"devDependencies": {
"#babel/cli": "^7.13.16",
"#babel/core": "^7.14.0",
"#babel/plugin-proposal-class-properties": "^7.13.0",
"#babel/plugin-proposal-nullish-coalescing-operator": "^7.16.5",
"#babel/plugin-proposal-optional-chaining": "^7.13.12",
"#babel/plugin-transform-runtime": "^7.13.15",
"#babel/preset-env": "^7.14.1",
"#babel/preset-typescript": "^7.13.0",
"#cloudflare/workers-types": "^2.2.2",
"babel-loader": "^8.2.2",
"typescript": "^4.2.4",
"webpack": "^5.36.2",
"webpack-cli": "^4.7.0"
},
"dependencies": {
"#cfworker/web": "^1.6.11"
}
}
my webpack.config.js:
const path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.ts',
output: {
filename: 'worker.js',
path: path.join(__dirname, 'dist'),
},
performance: {
hints: false,
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
module: {
rules: [
{
test: /\.(ts|js)x?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-typescript',
],
plugins: [
'#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-optional-chaining',
'#babel/plugin-proposal-nullish-coalescing-operator',
],
},
},
],
},
}
I can't figure out if there's something wrong with my webpack config or if there something else.
I managed to get it working by changing the webpack config at line
exclude: /(node_modules|bower_components)/,
to
include: /(node_modules\\#cfworker\\web|src)/,
It seems that the #cfworker/web module is using optional chaining and nullish coalescing and was excluded from the babel-loader.

Why am I getting "Cannot find module..." Typescript error for ".vue" file on webpack-dev-server recompilation?

I've setup a small webpack project which creates a Vue app bundle which is included in a static HTML file where the app is injected. I want to have components written in Typescript so I've included ts-loader in the webapck configuration. The build process - using the "webpack" command - works ok, but I'm having some trouble when I use webpack-dev-server.
When I initially start the server, everything works fine: the bundle is created and served on my local server and the browser displays the app correcly. However, when I make a change in the source code and save, I get a Typescript error when the code is recompiled telling me that a module or declaraton is missing for the ".vue" file for my component:
TS2307: Cannot find module './components/Banner.vue' or its corresponding type declarations.
To start the server I use the following command:
webpack serve --open
Project's folder structure
=======
webpack.config.js
const { VueLoaderPlugin } = require('vue-loader')
const path = require('path')
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
entry: {
app: './src/app.js',
},
output: {
filename: '[name].bundle.js',
},
plugins: [
new VueLoaderPlugin(),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.vue$/,
use: ['vue-loader']
},
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: [/node_modules/],
options: { appendTsSuffixTo: [/\.vue$/] }
},
],
},
}
app.js
import Vue from 'vue'
import App from './App.vue'
const app = new Vue({
render: (h) => h(App)
})
app.$mount('#app')
App.vue
<template>
<div id="app">
<h1>{{ welcomeMessage }}</h1>
<Banner />
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Banner from './components/Banner.vue'
export default Vue.extend({
components: {
Banner,
},
data: () => ({
welcomeMessage: 'Hello world!'
})
})
</script>
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node"
}
}
#types/vue-shims.d.ts
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
package.json
{
"name": "2021-06-21-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"dev": "webpack serve --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^8.3.0",
"typescript": "^4.3.4",
"vue-loader": "^15.9.7",
"vue-template-compiler": "^2.6.14",
"webpack": "^4.46.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"vue": "^2.6.14"
}
}

Vue3 / Vite: How to package components for publishing on npm

I'm trying to export two web components in a public package on npm, using Vite with TypeScript.
Vite has a Library Mode (https://vitejs.dev/guide/build.html#library-mode) which works well. The ESM and UMD files are both being transpiled into my /dist directory. My question is how to export the web components in the entry point file.
I have an entry point file called export.js
import AwesomeHeader from './components/AwesomeHeader.vue'
import AwesomeFooter from './components/AwesomeFooter.vue'
export default { // I feel like the problem is here.
components: {
AwesomeHeader: AwesomeHeader,
AwesomeFooter: AwesomeFooter,
}
}
The idea is that I'll npm publish the project and use it like this.
npm i #sparkyspider/awesome-components #(ficticious example)
import {AwesomeHeader, AwesomeFooter} from '#sparkyspider/awesome-components' // does not find
(AwesomeHeader and AwesomeFooter are not found as exports in the node_module, even though the JavaScript files are referenced / found)
My package.json below:
{
"name": "#sparkyspider/awesome-components",
"version": "1.0.8",
"files": [
"dist"
],
"main": "./dist/awesome-components.umd.js",
"module": "./dist/awesome-components.es.js",
"exports": {
".": {
"import": "./dist/awesome-components.es.js",
"require": "./dist/awesome-components.umd.js"
}
},
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"serve": "vite preview"
},
"dependencies": {
"vue": "^3.0.5"
},
"devDependencies": {
"#vitejs/plugin-vue": "^1.2.2",
"#vue/compiler-sfc": "^3.0.5",
"typescript": "^4.1.3",
"vite": "^2.3.3",
"vue-tsc": "^0.0.24"
},
}
You are having object { component: ... } as default export, instead of exporting AwesomeHeader and AwesomeFooter, which you try to import.
export { AwesomeHeader, AwesomeFooter } in export.js will work.
More on export: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
And you can't destruct default export: https://stackoverflow.com/a/43987935/8810271

How to build express use webpack?

I am a beginner, just started to learn express and webpack, I tried to use the initial express file
Trying to use webpack for packaging, I keep getting errors
The reason for this is because I want to run my system in a non-node.js environment
Is my direction wrong?
The express project is create with express --view=ejs myapp
I didn't make any changes
webpack.config.js
const path = require('path');
const clientConfig = {
resolve: {
fallback: {
"fs": false,
"tls": false,
"net": false,
"path": false,
"zlib": false,
"http": false,
"https": false,
"stream": false,
"crypto": false,
"crypto-browserify": require.resolve('crypto-browserify'), //if you want to use this module also don't forget npm i crypto-browserify
}
},
entry: {
'index': './app.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js'
}
}
module.exports = [clientConfig];
package.json
{
"name": "myapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"webpack": "webpack"
},
"browser": {
"crypto": false
},
"dependencies": {
"cookie-parser": "~1.4.4",
"crypto-browserify": "^3.12.0",
"debug": "~2.6.9",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1",
"path": "^0.12.7",
"twig": "~0.10.3"
},
"main": "app.js",
"devDependencies": {
"webpack": "^5.26.3",
"webpack-cli": "^4.5.0"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
Thanks for any guidance and comments
You can't run Express in a non-nodejs environment. Express depends upon the nodejs run-time library such as the http module so it can't run without that library. webpack can't overcome that.
You can use webpack to build either plain Javascript with no external dependencies or with dependencies that you have independent libraries for that can be included in the webpack bundle or with dependences that are present in whatever environment you want to run it in.