Vite Js --> dev mode works, but build doesn't. (importing library causes error) - javascript

I tried to move from vue-cli to vite but observed some obstacles.
I want to include several npm packages into my vue 3 project.
I tried to understand the issue, and basically the error came when I imported
https://www.npmjs.com/package/rdf-parse
If I run npm run dev everything works as expected, but when I run npm run build and serve the dist folder with http-server the error:
Uncaught TypeError: Object.defineProperty called on non-object at Function.defineProperty
occurs.
The code worked with vue-cli and in vite-dev mode so I expect I missed somethin crucial in the vite.config.js
But I didnt find anything in the docu that helped me out and also no thread here on stackoverflow or elsewhere.
I created a repo with a minimal example here: https://github.com/stackoverflowuser/vite-issue
It is the npm vue3 template (npm init vue#3) and only the library rdf-parse is added.
// vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': fileURLToPath(new URL('./src', import.meta.url)),
}
},
build: {
target: "es2020"
},
optimizeDeps: {
esbuildOptions: {
// Limit target browsers due to issue: Big integer literals are not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari13" + 2 overrides)'
target: "es2020",
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeModulesPolyfillPlugin()
]
}
},
})
In hope someone can give me a hint.

Related

Vite production build fails (React)

I have a web app created with create-react-app that I am trying to migrate to vite, but it is not working when I build with vite build --minify false.
Everything works well on vite dev version.
Vite 2.9.9,
react: 16.13.1
vite.config.js
import { defineConfig, loadEnv } from 'vite'
import svgr from 'vite-plugin-svgr'
import process from 'process'
import react from '#vitejs/plugin-react'
export default defineConfig(({ command, mode }) => {
// Load env file based on `mode` in the current working directory
const env = loadEnv(mode, process.cwd())
return {
plugins: [
react(),
svgr({
exportAsDefault: false,
// A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should include. By default all svg files will be included.
include: '**/*.svg',
}),
],
build: {
commonjsOptions: {
strictRequires: true,
// transformMixedEsModules: true,
}
}
}
})
Error:
require is not defined on js-cookie (coming from an okta-auth-js dependency).
Research tells me that require should not be used in the browser. So I tried the following option.
I have tried to add in transformMixedEsModules: true to the build options, but that changes the error to:
index.6cd5b200.js:108281 Uncaught TypeError: _typeof$3 is not a function
at _interopRequireWildcard$T (index.6cd5b200.js:108281:23)
at index.6cd5b200.js:108267:1
Am I missing a plugin or something?

Jest fails when rendering React component with 'No element indexed by'

I am attempting to get Jest working for my React Native project and have run into a variety of problems, the most confusing of which is the following:
When I run any test that renders a component, it spits out the error No element indexed by 7.
Here is the full stack trace:
FAIL __tests__/App-test.tsx
● Test suite failed to run
No element indexed by 7
at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
at mapSourcePosition (node_modules/source-map-support/source-map-support.js:244:42)
at wrapCallSite (node_modules/source-map-support/source-map-support.js:397:20)
at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:446:39)
at Function.write (node_modules/#jest/console/build/BufferedConsole.js:101:7)
at console._log (node_modules/#jest/console/build/BufferedConsole.js:117:21)
at console.error (node_modules/#jest/console/build/BufferedConsole.js:161:10)
This same error occurs with any component I attempt to render.
Regarding this issue which purports to solve a similar problem, I have tried installing babel (npm install --save-dev babel-jest #babel/core #babel/preset-env) and setting "coverageProvider" in the jest config to "v8". With or without the v8 preset I am still getting the same errors. It's definitely possible that I configured something else wrong. Here are some code snippets which may be of use:
App-test.tsx
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
package.json
// ...
"jest": {
"preset": "react-native",
"coverageProvider": "babel",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|#react-native|react-native-video|react-native-reanimated|#miblanchard/react-native-slider|react-native-gesture-handler)/)"
],
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
['#babel/preset-typescript', {allowDeclareFields: true}],
],
plugins: [
"react-native-reanimated/plugin",
],
};
As an additional note, I have tried adding #babel/preset-env to the list of babel presets, but this only resulted in a different error related to a separate package added to the transformIgnorePatterns list. Adding source-map-support to said list also solves nothing.
Edited to note that these tests fail regardless of whether or not the --coverage argument is applied
In the end, I solved my error by uninstalling node_modules, re-running npm install --save-dev babel-jest #babel/core #babel/preset-env and adding
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js",
// ...
]
to my package.json

Svelte app shows blank page on first start

This my first time running a Svelte app and I have this issue where the app doesn't seem to know where build/build.css and build/build.js are.
I got the same issue when I tried Svelte with Tailwind.
This is my config when I created the project:
import svelte from 'rollup-plugin-svelte';
import commonjs from '#rollup/plugin-commonjs';
import resolve from '#rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css' }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
This is the ouput after running npm start:
Here is my folder structure:
What went wrong?
This looks very much like the official Svelte template. In this case, the command to build, watch, & serve is npm run dev.
npm start just runs the web server and serve existing files. You'd use it, for example to test your prod build after npm run build.

Unable to load a react module as node module

I have a react component in the path
src/components/test
import React from 'react';
import ReactDom from 'react-dom';
class TestComp extends React.Component {}
export default TestComp;
I am exposing the component in index.js from path
src/index.js
import TestComp from './components/test';
export {
TestComp
};
I have added main in package.json as "main": "src/index.js"
I have published a npm package test-comp of above application and using same in another application.
main.js
import {TestComp} from 'test-comp';
I am using grunt-browserify in this application with following options set.
options: {
"transform": [
[
"babelify",
{
"presets": [
"es2015",
"react",
"stage-0"
]
}
]
],
browserifyOptions: {
debug: true,
extensions: ['.js', '.jsx'],
entries: ['main.js']
}
}
When I run grunt browserify getting following error.
>> import TestComp from './components/test';
>> ^
>> ParseError: 'import' and 'export' may appear only with 'sourceType: module'
Warning: Error running grunt-browserify. Use --force to continue.
It probably not understanding the path mentioned in node module or rejecting to understand the same which linting. I even have tried adding following in .eslintrc but no luck
{
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"env": {
"browser": true,
"es6": true
},
"ecmaFeatures": {
"modules": true
}
}
I tried most of SO answers related to this error. But still stuck in same place.
EDIT
I am able to browserify first module directly with almost similar configuration. Getting this error when first module is loaded as node dependancy in other application as explained above.
So you wrote the module test-comp in ES6, using import and export, and the main entry of the package.json in test-comp refers to src/index.js.
The answer is that browserify transforms don't apply to every module you require. They only apply to the immediate project: not the project's dependencies.
If you want to require a module that uses ES6 syntax in browserify, you'll either need to
Add a prepublish script to test-comp that transpiles it to ES5, and change the main entry of test-comp to refer to that ES5 version, not the ES6 version
Add babelify as a dependency of test-comp and add babelify as a browserify transform in the package's 'browserify' entry, as documented in babelify.

"No ESLint configuration found" error

Recently, we've upgraded to ESLint 3.0.0 and started to receive the following message running the grunt eslint task:
> $ grunt eslint
Running "eslint:files" (eslint) task
Warning: No ESLint configuration found. Use --force to continue.
Here is the grunt-eslint configuration:
var lintTargets = [
"<%= app.src %>/**/*/!(*test|swfobject)+(.js)",
"test/e2e/**/*/*.js",
"!test/e2e/db/models/*.js"
];
module.exports.tasks = {
eslint: {
files: {
options: {
config: 'eslint.json',
fix: true,
rulesdir: ['eslint_rules']
},
src: lintTargets
}
}
};
What should we do to fix the error?
The error you are facing is because your configuration is not present.
To configure the eslint type
eslint --init
then configure as your requirement.
then execute the project again.
I've had the same error. It seems to need configuration.
Go to your project root & run in terminal
./node_modules/.bin/eslint --init
Try to swap config with configFile. Then :
Create eslint.json file and
Point the right location of it (relative to Gruntfile.js file)
Place some configuration in that file (eslint.json), i.e.:
.
{
"rules": {
"eqeqeq": "off",
"curly": "warn",
"quotes": ["warn", "double"]
}
}
for more examples, go here.
I hade the same problem with Gulp and running "gulp-eslint": "^3.0.1" version.
I had to rename config: to configFile in Gulp task
.pipe(lint({configFile: 'eslint.json'}))
For those having the same problem, this is how we've fixed it.
Following the Requiring Configuration to Run migration procedure, we had to rename eslint.json to .eslintrc.json which is one of the default ESLint config file names now.
We've also removed the config grunt-eslint option.
Create a new file on the root directory called .eslintrc.json file:
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": "error"
}
}
Just follow the steps
1.create eslint config file name eslintrc.json
2.place the code as given below
gulp.src(jsFiles)
// eslint() attaches the lint output to the "eslint" property
// of the file object so it can be used by other modules.
.pipe(eslint({configFile: 'eslintrc.json'}))
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failAfterError last.
.pipe(eslint.failAfterError());
Webpack
I had eslint.rc file in my root project directory but event though
I was getting error.
Solution was to add exclude property to "eslint-loader" rule config:
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
// eslint options (if necessary)
}
},
],
},
// ...
}
We faced this problem today and realized, that the issue was not caused inside the project that we were working on, but inside a package that we had a link on using the command:
yarn link
Which is a feature often useful to test out new features or when trying to debug an issue in a package that manifests itself in another project.
We solved it by either removing the link, or in case of ember.js disabling the developer mode of our addon package.
index.js
module.exports = {
isDevelopingAddon: function() {
return false;
},
...
}
gulp.task('eslint',function(){
return gulp.src(['src/*.js'])
.pipe(eslint())
.pipe(eslint.format())
});
`touch .eslintrc` instead of .eslint
these two steps may help you!
Run the command ember init.
When it asks for overwriting the existing file(s). Type n to skipping overwriting the file.
Now it will automatically create required files like .eslintrc, etc.
For me the same issue occurred when i copied my folder except dist, dist_production and node_modules folder to another system and tried running ember build.

Categories