How do I change the input dir in ViteJS? - vite

I'm trying to build/compile a demo page for my plugin with ViteJS. How do I pinpoint ViteJS to my file that needs to be compiled?
my-plugin/
├─ demo/
│ ├─ resources/js/
│ │ ├─ app.js <---- This needs to be read (`npm run build:demo`)
│ ├─ public/js/
│ │ ├─ app.js <---- This should be my ViteJS demo output (outDir)
├─ node_modules/
├─ dist/ <---- This works ✅ (`npm run build:dist`)
│ ├─ index.mjs
│ ├─ index.umd.js
├─ src/
│ ├─ index.js
├─ index.html <---- This is the demo index.html that is needed for GitHub (cannot change the location)
├─ package.json
I have added these lines of code in
// package.json
...
"scripts": {
"build:dist": "LIB_NAME=dist vite build",
"build:demo": "LIB_NAME=demo vite build",
"build": "npm run build:dist && npm run build:demo",
},
...
I want to run npm run build:demo. But I get errors, like:
[vite]: Rollup failed to resolve import "/demo/public/js/app.js" from "index.html".
This is most likely unintended because it can break your application at runtime...
My vite.config.js looks like this:
import { defineConfig } from 'vite';
import vue from '#vitejs/plugin-vue';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
const path = require('path');
const config = {
dist: {
build: {
lib: {
entry: path.resolve(__dirname, './src/index.js'),
name: 'VueResponsiveVideoBackgroundPlayer',
fileName: 'vue-responsive-video-background-player',
},
rollupOptions: {
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// Add external deps here
globals: {
vue: 'Vue',
},
exports: 'named',
},
},
outDir: './dist',
},
plugins: [
vue(),
cssInjectedByJsPlugin(),
],
},
demo: {
// <--------- This is the part where I have to change something
// root: './demo/resources/js/',
build: {
outDir: './demo/public/js',
},
plugins: [
vue(),
cssInjectedByJsPlugin(),
],
},
};
const currentConfig = config[process.env.LIB_NAME];
if (currentConfig === undefined) {
throw new Error('LIB_NAME is not defined or is not valid');
}
// https://vitejs.dev/config/
export default defineConfig({
...currentConfig,
plugins: [
vue(),
cssInjectedByJsPlugin(),
],
});
It would be awesome, if I could somehow say to ViteJS please use ./demo/resources/js/app.js as the input and after the compile set the output to ./demo/public/js.app.js.
Here is the source if you need it.

Yeah I found the solution:
It took me a while, but have look at my vite.config.js file.
// https://www.raulmelo.dev/blog/build-javascript-library-with-multiple-entry-points-using-vite-3
import { defineConfig } from 'vite';
import vue from '#vitejs/plugin-vue';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
const path = require('path');
const config = {
// npm run build:dist for npm
dist: {
build: {
outDir: './dist',
lib: {
entry: path.resolve(__dirname, './src/index.js'),
name: 'VueResponsiveVideoBackgroundPlayer',
fileName: 'vue-responsive-video-background-player',
},
rollupOptions: {
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// Add external deps here
globals: {
vue: 'Vue',
},
// in index.js we use a named + default export.
// We hide the error message with 'named'
exports: 'named',
},
},
},
},
// npm run build:demo for the demo page
demo: {
build: {
outDir: './demo/public/build',
rollupOptions: {
input: './demo/resources/js/app.js',
output: {
chunkFileNames: 'js/[name].js',
entryFileNames: 'js/[name].js',
},
},
},
},
};
const currentConfig = config[process.env.LIB_NAME];
if (currentConfig === undefined) {
throw new Error('LIB_NAME is not defined or is not valid');
}
// https://vitejs.dev/config/
export default defineConfig({
...currentConfig,
plugins: [
vue(),
cssInjectedByJsPlugin(),
],
});

Related

How do I use `unpkg` with ViteJS?

I'm migrating my Vue plugin from Vue CLI to Vitejs.
With vue-cli-service build I generate three files: index.common.js, index.umd.js and index.umd.min.js
In package.json I refer to these files with:
"main": "dist/index.common.js",
"unpkg": "dist/index.umd.min.js",
But now migrating to ViteJS npm run build creates js files with random strings index.25e1eb44.js.
How do I use unpkg with ViteJS in package.json?
By reading other code, I found a good solution:
import { defineConfig } from 'vite';
import vue from '#vitejs/plugin-vue';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
const path = require('path');
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.js'),
name: 'VueResponsiveVideoBackgroundPlayer',
fileName: 'vue-responsive-video-background-player',
},
rollupOptions: {
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// Add external deps here
globals: {
vue: 'Vue',
},
},
},
},
plugins: [
vue(),
cssInjectedByJsPlugin(),
],
});
For more, read here: https://vitejs.dev/config/build-options.html#build-commonjsoptions

Executing node module script in packaged electron app

I was trying to execute node_modules/some_package/some_js.js from renderer using contextBridge. It works in dev server, but in packaged app.
Here is my preload.js code.
import { exec, fork } from "child_process";
import { contextBridge } from "electron";
import path from "path";
contextBridge.exposeInMainWorld("pwr", {
node: () => {
const __dirname = path.resolve();
const child_argv = ["codegen", ""];
const child_execArgv = ["codegen"];
fork(__dirname + "/node_modules/playwright-core/cli.js", child_argv);
},
here is my client-side(renderer) code...
const handleClick = () => {
//#ts-ignore
pwr.node();
};
here is package.json
"scripts": {
"dev": "vite",
"build": "tsc && vite build && electron-builder"
},
and this is vite config file
rmSync(path.join(__dirname, 'dist'), { recursive: true, force: true }) // v14.14.0
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
'#': path.join(__dirname, 'src'),
'styles': path.join(__dirname, 'src/assets/styles'),
},
},
plugins: [
react(),
electron({
main: {
entry: 'electron/main/index.ts',
vite: {
build: {
// For Debug
sourcemap: true,
outDir: 'dist/electron/main',
},
// Will start Electron via VSCode Debug
plugins: [process.env.VSCODE_DEBUG ? onstart() : null],
},
},
preload: {
input: {
// You can configure multiple preload scripts here
index: path.join(__dirname, 'electron/preload/index.ts'),
},
vite: {
build: {
// For Debug
sourcemap: 'inline',
outDir: 'dist/electron/preload',
}
},
},
// Enables use of Node.js API in the Electron-Renderer
// https://github.com/electron-vite/vite-plugin-electron/tree/main/packages/electron-renderer#electron-renderervite-serve
renderer: {},
}),
],
server: process.env.VSCODE_DEBUG ? {
host: pkg.debug.env.VITE_DEV_SERVER_HOSTNAME,
port: pkg.debug.env.VITE_DEV_SERVER_PORT,
} : undefined,
})
Source Code:
https://github.com/liansnail/electron-demo
Build Tool: Vite
OS: mac arm64
node version: 16.14.2
Please let me know what I'm missing. I used Vite for
Edit: I turned off asar option but it still doesn't work.
"scripts": {
"dev": "vite",
"build": "tsc && vite build && electron-builder build --config.asar=false"
},

Jest encountered an unexpected token when use the `amchart5` imports

I am getting this error by doing jest test with amchart5 integration.
Details:
C:\Users\BASHIMX5\Projects\Bitbucket\hf-ui\node_modules\#amcharts\amcharts5\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { Root } from "./.internal/core/Root";
^^^^^^
SyntaxError: Unexpected token 'export'
2 |
3 | import { ImplantReportComponent } from './implant-report.component';
> 4 | import * as am5 from '#amcharts/amcharts5';
| ^
5 | import * as am5xy from '#amcharts/amcharts5/xy';
6 | import am5themes_Animated from '#amcharts/amcharts5/themes/Animated';
7 |
at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/app/pages/patient-account-management/component/implant-report/implant-report.component.spec.ts:4:1)
jest.preset:
const nxPreset = require('#nrwl/jest/preset').default;
module.exports = {
...nxPreset,
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
transform: {
'^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular'
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)', "[/\\\\]node_modules[/\\\\](?!(#amcharts)\\/).+\\.js$", "^.+\\.module\\.(css|sass|scss)$"],
resolver: '#nrwl/jest/plugins/resolver',
coverageReporters: ['text', 'text-summary', "html", "cobertura"],
moduleFileExtensions: ['ts', 'js', 'html'],
globals: {
crypto: require('crypto'),
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
},
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
"reporters": ["default", "jest-junit"]
};
mock:
node_modules/
__mocks__/
├─ #amcharts/
│ ├─ amcharts5/
│ │ ├─ themes/
│ │ │ ├─ Animated.js
│ │ ├─ index.js
│ │ ├─ xy.js
But getting the above error. any help? I spend moreover 24 hr to fix. but no luck. I am running nx worksapce.
I was able to get past this by removing the es6 module regex in the transformIgnorePatterns settings. Also if you have other libraries/apps consuming this library, they also need to have the same regex settings in their transformIgnorePatterns.
const nxPreset = require('#nrwl/jest/preset').default;
module.exports = {
...nxPreset,
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
transform: {
'^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular'
},
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\](?!(#amcharts)\\/).+\\.js$', '^.+\\.module\\.(css|sass|scss)$'],
resolver: '#nrwl/jest/plugins/resolver',
coverageReporters: ['text', 'text-summary', "html", "cobertura"],
moduleFileExtensions: ['ts', 'js', 'html'],
globals: {
crypto: require('crypto'),
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
},
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
"reporters": ["default", "jest-junit"]
};

Webpack 4 - Module not found: Can't resolve node_modules

I am trying to bundle my nodejs express app with Webpack, I keep on getting the same error, will greatly appreciate help
node version 8.9.1
webpack version 4.41.2
Operating System Windows 10
My project structure
.
├── node_modules
├── package.json
├── README.md
├── src
│ ├── components
│ ├── index.js
|__ webpack-config.js
|
My Webpack config is following
var webpack = require('webpack');
import path from "path";
import nodeExternals from "webpack-node-externals";
module.exports = {
entry: {app:"./src/index.js"},
target: "node",
output: {
path: path.join(__dirname, 'webpack-build'),
filename: "bundle.js"
},
module:{
rules:[{
test: /\.(js)$/,
exclude: /(node_modules)/,
// flags to apply these rules, even if they are overridden (advanced option)
loader: "babel-loader",
// the loader which should be applied, it'll be resolved relative to the context
options: {
presets: ["es2015"]
},
}]
},
externals: [nodeExternals()]
};
Things I Have Tried
add webpack-node-externals to Externals property
Tried adding
resolve: {
root: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')],
extensions: ['', '.js']
};
ERROR I GET

Understanding r.js, almond, and relative paths

I see this answer but AFAICT it's not working for me. Maybe I'm doing something stupid.
I'm using almond and grunt-contrib-requirejs. I've tried a bunch of stuff
Here's my layout
.
├── Gruntfile.js
├── 3rdparty
│ ├── require.js
├── src
│ ├── lib.js
│ └── main.js
└── node_modules
   └── almond
      └── almond.js
And here's my grunt-contrib-requirejs config
requirejs: {
full: {
options: {
baseUrl: "./",
name: "node_modules/almond/almond.js",
include: [ "src/main.js" ],
out: "dist/app.js",
optimize: "none",
},
},
},
main.js looks like this
requirejs(['./lib',], function(lib) {
lib.hello();
});
lib.js looks like this
define([], function() {
return {
hello: function() {
console.log("hello from lib");
},
};
});
If run a page that uses require.js as in
<script src="3rdparty/require.js" data-main="src/main.js"></script>
It runs great. You can see it live it here. Check the console and you'll see it prints hello from lib
So I run grunt. Then I run a page that uses dist/app.js and I get the error
Uncaught Error: undefined missing lib
Here's a live page.
Checking the generated dist/app.js I see lib has been turned into this
define('src/lib',[], function() {
...
});
And main is including it like this
requirejs(['./lib'], function(lib) {
...
});
In other words, the id that r.js generated src/lib doesn't match the id that main is referencing ./lib.
This seems like a very straight forward example for r.js. Like practically "hello world".
What am I doing wrong?
One thing I've tried is changing the baseUrl to ./src
requirejs: {
full: {
options: {
baseUrl: "./src",
name: "node_modules/almond/almond.js",
include: [ "src/main.js" ],
out: "dist/app.js",
optimize: "none",
},
},
},
But now I get
{ [Error: Error: ENOENT: no such file or directory, open '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js'
at Error (native)
]
originalError:
{ [Error: ENOENT: no such file or directory, open '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js',
fileName: '/Users/gregg/temp/grunt-contrib-requirejs-example/src/node_modules/almond/almond.js' } }
So I try fixing the almond path
requirejs: {
full: {
options: {
baseUrl: "./src",
name: "../node_modules/almond/almond.js",
include: "main",
out: "dist/app.js",
optimize: "none",
},
},
},
But that fails as well
{ [Error: Error: ERROR: module path does not exist: ../node_modules/almond/almond.js for module named: ../node_modules/almond/almond.js. Path is relative to: /Users/gregg/temp/grunt-contrib-requirejs-example
at /Users/gregg/temp/grunt-contrib-requirejs-example/node_modules/requirejs/bin/r.js:30214:35
]
originalError: [Error: ERROR: module path does not exist: ../node_modules/almond/almond.js for module named: ../node_modules/almond/almond.js. Path is relative to: /Users/gregg/temp/grunt-contrib-requirejs-example] }
What am I not getting?
The entire thing is checked into github here if you'd like to work with it.
So here's the answer.
r.js prefers module names not paths
requirejs: {
full: {
options: {
baseUrl: "./src",
paths: {
almond: "../node_modules/almond/almond",
}
name: "almond",
include: [ "main.js" ],
out: "dist/app.js",
optimize: "none",
},
},
},

Resources