Vitejs. Running a script for a specific task - javascript

I'm using Vite. I installed the npm plugin called 'vite-plugin-zip-file' in order to archive the dist folder. How can I run a separate from 'build' script in package.json specifically for this task?
vite.config.js below
import { defineConfig } from 'vite';
import { resolve } from 'path';
import { viteZip } from 'vite-plugin-zip-file';
export default defineConfig({
build: {
outDir: 'build',
},
plugins: [
viteZip({
folderPath: resolve(__dirname, 'build'),
outPath: resolve(__dirname),
zipName: 'Test.zip',
}),
],
});
package.json 'scripts' (I don't know what to write in 'zip' here)
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
"zip": ?
},
I tried adding the environmental variable, but I don't know exactly how to do it. So, there's probably another better way.

Related

Vite: Building a SASS file as it is written

I am building a library using Vite/Vue3/Quasar and I would like to export a quasar-variables.sass file as it is written without it being compiled or anything. Just straight SASS file that I can import to my other projects.
Is this possible with Vite?
Here is my vite.config.js:
import { resolve } from 'path';
import { defineConfig } from 'vite';
import { quasar, transformAssetUrls } from '#quasar/vite-plugin';
import eslintPlugin from 'vite-plugin-eslint';
import vue from '#vitejs/plugin-vue';
// https://vitejs.dev/config/
export default defineConfig({
build: {
lib: {
entry: resolve(__dirname, 'src/index.js'),
name: 'AvvinueClowder',
fileName: (format) => `avvinue-clowder.${format}.js`,
},
rollupOptions: {
external: ['vue'],
output: {
globals: {
vue: 'Vue',
},
},
},
},
plugins: [
vue({
template: { transformAssetUrls },
}),
eslintPlugin(),
quasar({
sassVariables: 'src/style/_quasar-variables.sass',
}),
],
resolve: {
alias: {
'#': resolve(__dirname, './src'),
},
},
});
And part of my package.json:
"version": "2.0.9",
"files": [
"dist"
],
"main": "./dist/avvinue-clowder.umd.js",
"module": "./dist/avvinue-clowder.es.js",
"exports": {
".": {
"import": "./dist/avvinue-clowder.es.js",
"require": "./dist/avvinue-clowder.umd.js"
}
},
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
And this is what gets spit out in the dist folder:
Right now everything gets converted to simple CSS and the variables seem to get lost, which is forcing me to declare multiple variable files in multiple repositories, instead of just importing it from my NPM library I'm creating.
Thank you!
For Vite specifically, its easier if you just create a /public folder in your root and add files/assets that shouldn't be altered by the build script.
You can use the rollup copy plugin to copy your file into dist folder
import copy from 'rollup-plugin-copy'
plugins: [
copy({
targets: [
{ src: 'src/style/_quasar-variables.sass', dest: 'dist/style' }
]
})
]
Another way, you can just add your file to npm by excluding it from .npmignore file
/src <- This line prevents uploading the whole src folder to npm
!src/style/_quasar-variables.sass <- This will add your file to npm package

vite failed to load config from vite.config.js,

I created a new vue app by doing these (according to vue docs)
npm init vue#latest
npm install
Then I try to run npm run dev.Then this happened.
My environments are these
OS => Ubuntu
Node version => 18.7.0
npm version => 8.15.0
My package.json
{
"name": "vue-project",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview --port 4173"
},
"dependencies": {
"vue": "^3.2.37"
},
"devDependencies": {
"#vitejs/plugin-vue": "^3.0.1",
"vite": "^3.0.4"
}
}
My vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
I have been searching for a while now but no avail.Thanks in advance.
Finally I found the solution.
The problem was because of the package.json file conflict.
Vite is using the wrong package.json file located in the Project's parent directory instead of project's own package.json file.Like this -
~/package.json ( wrong file )
~/Projects/VueProject/package.json ( correct file )
So delete the wrong file and the problem will be fixed.
Thanks to this github issue answer package.json:1:0: error: Unexpected end of file

Next.js create a polyfill.js file in dist folder

I try to implement the Trading view library's next.js example.
In _document.js file I have to import
<script src="/static/datafeeds/udf/dist/polyfills.js" />
<script src="/static/datafeeds/udf/dist/bundle.js" />
But when I go to datafeeds/udf.dist folder only I can see is the bundle.js file.
And inside the udf folder I have this package.json file
{
"private": true,
"dependencies": {
"tslib": "2.1.0"
},
"devDependencies": {
"#rollup/plugin-node-resolve": "~9.0.0",
"rollup": "~2.28.2",
"rollup-plugin-terser": "~7.0.2",
"typescript": "4.2.3"
},
"scripts": {
"compile": "tsc",
"bundle-js": "rollup -c rollup.config.js",
"build": "npm run compile && npm run bundle-js"
}
}
and rollup.config.js
/* globals process */
import { terser } from 'rollup-plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
const environment = process.env.ENV || 'development';
const isDevelopmentEnv = (environment === 'development');
export default [
{
input: 'lib/udf-compatible-datafeed.js',
output: {
name: 'Datafeeds',
format: 'umd',
file: 'dist/bundle.js',
},
plugins: [
nodeResolve(),
!isDevelopmentEnv && terser({
ecma: 2017,
safari10: true,
output: { inline_script: true },
}),
],
},
];
When I run compile,bundle-js, and build scripts that only create the bundle.js file only. How can I create a polyfills.js file inside the dist folder? I hope this can be done with rollup pakcage.

Cannot resolve module in sibling directory

Good day all!
I am trying to setup a javascript workspace including the posibility to run test script using npm, webpack (and mocha for tests).
So my project structure looks someting like (npm generated files are omitted):
root
|- src
| |- main.js
| |- MyClass.js
|- test
| |- test.js
|- package.json
|- webpack.config.js
The main.js script is building and debugging fine. But the test script is giving me problems.
In short, I import classes from the project (from the src directory) for testing. But it cannot resolve it (eventhough intellisense of vscode is having no issues at all). So if my test-script looked something like:
import { MyClass } from 'MyClass'
/* testing stuff */
Intellisense is perfectly capable of resolving the location (as configured in the jsconfig.json), but eventhough I set the src directory as include-rule or as alias, webpack is not able to resolve it and tries to search in the /test directory instead (and in recursive order all its parent-directories, failing in the same manner).
So the question is how to let webpack resolve for 'nephew' directories?
(If there is an easier way to use mocha than with the current combined scripts, it would suffice in this case as well. So feedback on that is also welcome, but I defenitly would love to find the answer to the original question)
Here is the webpack.config.js content
const path = require('path');
{
name: "myProject_test",
mode: "development",
entry: path.resolve(__dirname, "./test/test.js"),
devtool: 'source-map' : '',
output:
{
clean: { dry: true },
path: path.resolve(__dirname, root, source.outputDir),
filename: "[id]/[name].js",
},
module:
{
rules:
[
{
test: /.jsx?$/,
include: [path.resolve(__dirname, "./test"), path.resolve(__dirname, "./src")],
exclude: [path.resolve(__dirname, "./dist"), path.resolve(__dirname, "./test/test-dist"), path.resolve(__dirname, "./node_modules")],
loader: 'loader-type',
options: { /* All loader types follow this pattern; so the rest is omited for brevety, but basically this includes all the loaders required for correct compiling */ }
}
],
},
resolve:
{
alias:
{
"*": [path.resolve(__dirname, "./src/*"), path.resolve(__dirname, "./test/*")],
},
extensions: ['.json', '.js', '.jsx', '.scss', '.sass', '.html', '.htm']
},
devServer:
{
contentBase: [path.resolve(__dirname, "./test"), path.resolve(__dirname, "./test/test-dist")],
/* Other server properties to make this work with server utility */
}
}
And here the package.json file content
{
"name": "MyProject",
"version": "0.0.1",
"description": "some description",
"dependencies": {},
"scripts": {
"test": "webpack && mocha test/test-dist --require source-map-support/register --reporter spec --check-leaks --recursive && rm -rf test/test-dist",
"debug": "webpack serve",
"start": "webpack --watch",
"build": "webpack"
},
"devDependencies": {
"#babel/core": ">=7.x",
"#babel/preset-env": ">=7.x",
"babel-loader": ">=8.x",
"cross-env": ">=7.x",
"css-loader": ">=6.x",
"html-loader": ">=2.x",
"resolve-url-loader": ">=4.x",
"style-loader": ">=3.x",
"sass-loader": ">=12.x",
"sass": ">=1.x",
"mini-css-extract-plugin": ">=2.x",
"extract-loader": ">=5.x",
"webpack": ">=5.x",
"webpack-cli": ">=4.x",
"webpack-dev-server": ">=3.x",
"worker-loader": ">=3.x",
"source-map-support": ">=0.x",
"mocha": ">=8.x",
"should": ">=13.x"
}
}

Jest test 'unexpected token export'

I'm trying to get my jest tests to run. I am getting the error SyntaxError: Unexpected token export at the line export default configureStore..specifically on the word 'export'. To me this suggests redux-mock-store is not being transpiled by Babel, so how can I force this with Jest? I'm using jest-webpack.
ContractsActions.test.js
import * as contractsActions from './contractsActions';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
const store = mockStore({})
return store.dispatch(contractsActions.fetchAllContracts()).then(() => {
//Do something
})
});
package.json
...
"scripts": {
"test": "jest-webpack",
...
"jest": {
"transformIgnorePatterns": [
"!node_modules/"
]
}
...
webpack.config.js
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['es2015', 'react', 'stage-2']
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
}
},
I ended up fixing this problem by creating a separate .babelrc file, instead of trying to set the babel configuration settings in package.json. I'm sure there are other steps I tried that may have contributed but this seemed to be the one that fixed it.
.babelrc
{
"presets": [["es2015", {"modules": false}]],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Take a look at the package.json from that package:
https://github.com/arnaudbenard/redux-mock-store/blob/master/package.json
You can see it offers different entry points:
"main": "dist/index-cjs.js",
"module": "dist/index-es.js",
"js:next": "dist/index-es.js",
"browser": "dist/index.min.js",
Check if your node_modules/redux-mock-store has a dist folder. If not, start the build that suits your requirements (also listed in package.json):
"build:cjs": "babel src --out-file dist/index-cjs.js",
"build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f umd -c -i src/index.js -o dist/index-umd.js",
"build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -f umd -c -i src/index.js -o dist/index-umd.min.js",
"build:es": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f es -c -i src/index.js -o dist/index-es.js",
"build": "npm run build:umd && npm run build:umd:min && npm run build:es && npm run build:cjs",
I don't know which of those versions buildable would be the right one for you, but I assume one of them will be. At worst, start npm i && npm run build:cjs in node_modules/redux-mock-store and resort to CommonJS require syntax:
const configureMockStore = require('redux-mock-store/dist/index-cjs.js');
Really hope this solves your problem, at least these are the steps I would try.

Categories

Resources