Getting an error
[vite] Internal server error: Cannot read property 'length' of undefined
This is happening while trying to run my vue project using vite.
Below is the error stack:
Build failed with 1 error: node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59574:34: ERROR: [plugin: vite:dep-scan] Cannot read property 'length' of undefined 2:44:29 PM [vite] Internal server error: Cannot read property 'length' of undefined at matches (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59574:35) at /Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59633:58 at Array.find () at Context.resolveId (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:59633:42) at Object.resolveId (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:36609:55) at processTicksAndRejections (internal/process/task_queues.js:95:5) at async ModuleGraph.resolveUrl (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:56244:26) at async ModuleGraph.getModuleByUrl (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:56124:23) at async doTransform (/Users/pandocorp/Desktop/pando/codes/pando-app/frontend/shipper/node_modules/vite/dist/node/chunks/dep-27bc1ab8.js:55582:20)
My vite.config.js
import { defineConfig } from 'vite';
import { createVuePlugin } from 'vite-plugin-vue2';
const config = require('./config');
const path = require('path');
export default defineConfig({
plugins: [createVuePlugin()],
server: {
port: 8080,
},
resolve: {
alias: [
{
'#': path.resolve(__dirname, './src'),
},
{
'#common': path.resolve(__dirname, '../common-v2'),
},
// {
// find: path.resolve(__dirname, '../static'),
// replacement: config.dev.assetsSubDirectory,
// ignore: ['.'],
// },
// {
// find: path.resolve(__dirname, '../firebase-messaging-sw.js'),
// replacement: 'firebase-messaging-sw.js',
// ignore: ['.'],
// },
],
},
build: {
chunkSizeWarningLimit: 600,
cssCodeSplit: false,
},
});
When I encountered this error, adding the following to vite.config.js seemed to resolve it.
resolve: {
alias: [
{
find: /^~(.*)$/,
replacement: 'node_modules/$1',
},
],
},
I had the same issue with a brand new Vite project. I don't know if this is your case, but I created this new project under a directory of another project like so:
/some/path/my-project <- "parent project"
/some/path/my-project/... <- other project files
/some/path/my-project/node_modules
/some/path/my-project/... <- other project files
/some/path/my-project/brand-new-vite-project <--- THIS ONE!
This nesting seems to generate the issue, because I moved the brand new project elsewhere and everything worked as expected.
Same problem encountered while getting throug Amplify "getting started" (which requires a new alias)
The solution for me was to rewrite the config as follows
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
"./runtimeConfig": "./runtimeConfig.browser",
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
],
},
});
Related
I am trying to use the npm package "Typeorm" in my Electron + Vue project, but when I run it I have this error:
Module parse failed: Unexpected character '' (2:0)
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
| import { EntitySchema } from "typeorm"
>
| export default new EntitySchema({
| name: "Post", // Will use table name `post` as default behaviour.
But I don't even have a webpack.config.js in my project. Not even inside files from frameworks that i'm using. So I can't follow the tips of this https://webpack.js.org/concepts#loaders.
The file that contains this import:
Category.js
import { EntitySchema } from "typeorm"
export default new EntitySchema({
name: "Category", // Will use table name `category` as default behaviour.
tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
columns: {
id: {
primary: true,
type: "int",
generated: true,
},
name: {
type: "varchar",
},
},
})
This is my Babel.config:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
To try to make it work, in my vue.config.js I added this "transpileDependecies", as suggested in #vue/cli-plugin-babel/preset . But it stills the same error.
vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: [
'typeorm'
],
configureWebpack: {
devtool: 'source-map',
},
pluginOptions: {
vuetify: {
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vuetify-loader
}
}
})
Other similar questions did not help..
I migrated from webpack to vite successfully in a vue2 project and now I am upgrading from vue2 to vue3.
I made it until step 4 in this guide: https://v3-migration.vuejs.org/migration-build.html#installation, and now the build process gives me this error.
ERROR: [plugin: vite:dep-scan] Cannot read properties of undefined (reading 'length')
It looks like the vite compat builder is not able to find the file /src/main.js, because if I rename or even delete the file, the error remains the same.
Did I miss something?
✘ [ERROR] [plugin vite:dep-scan] Cannot read properties of undefined (reading 'length')
node_modules/vite/dist/node/chunks/dep-59dc6e00.js:60384:34:
60384 │ if (importee.length < pattern.length) {
╵ ^
at matches (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:60384:35)
at /home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:60443:58
at Array.find (<anonymous>)
at Context.resolveId (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:60443:42)
at Object.resolveId (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38837:55)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async resolve (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:39049:26)
at async /home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:39257:34
at async callback (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:929:28)
at async handleRequest (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:709:30)
This error came from the "onResolve" callback registered here:
node_modules/vite/dist/node/chunks/dep-59dc6e00.js:39253:18:
39253 │ build.onResolve({
╵ ~~~~~~~~~
at setup (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:39253:19)
at handlePlugins (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:851:23)
at Object.buildOrServe (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:1145:7)
at /home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:2087:17
at new Promise (<anonymous>)
at Object.build (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:2086:14)
at Object.build (/home/user/projects/ipfs-search/dweb-search-frontend/node_modules/esbuild/lib/main.js:1935:51)
at /home/user/projects/ipfs-search/dweb-search-frontend/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38997:54
at Array.map (<anonymous>)
The plugin "vite:dep-scan" was triggered by this import
html:/home/user/projects/ipfs-search/dweb-search-frontend/index.html:1:7:
1 │ import "/src/main.js"
╵ ~~~~~~~~~~~~~~
Build failed with 1 error:
node_modules/vite/dist/node/chunks/dep-59dc6e00.js:60384:34: ERROR: [plugin: vite:dep-scan] Cannot read properties of undefined (reading 'length')
vite.config.js:
import { defineConfig } from 'vite';
import path from 'path';
import createVuePlugin from '#vitejs/plugin-vue';
export default defineConfig({
plugins: [
createVuePlugin({
template: {
compilerOptions: {
compatConfig: {
MODE: 2,
},
},
},
}),
],
server: {
port: 8080,
},
resolve: {
alias: [
{
vue: '#vue/compat',
},
{
find: '#',
replacement: path.resolve(__dirname, 'src'),
},
],
},
});
Well I found an answer; the alias in vite.config.js:
{
vue: '#vue/compat',
},
seemed to cause the error.
Note that this snippet was copied directly from the official vue.js vue3 migration guide. After I removed it, the error disappeared, and more comprehensible errors came, as the ones I expected.
Inspired by Frido Emans answer, I found the issue was using a list into alias. I ended up replacing
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [
{
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
{
find: "./runtimeConfig",
replacement: "./runtimeConfig.browser",
},
]
},
});
by (notice the alias list is gone)
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"./runtimeConfig": "./runtimeConfig.browser",
"#": fileURLToPath(new URL("./src", import.meta.url))
}
},
});
We are maintaining an internal library which is exporting ESM modules using Rollup. We have just recently switched to using CSS modules, which we have set with rollup-plugin-postcss. We want to inject these styles into the head rather than have an external file.
Our built bundle generates the ESM file with:
import styleInject from '../node_modules/style-inject/dist/style-inject.es.js';
Our consuming library then fails with
Uncaught Error: Cannot find module '../node_modules/style-inject/dist/style-inject.es.js'
I would expect the ESM export to import styleInject from 'style-inject' and style-inject to be included in the package-lock.json as a dependency. What is the correct way of using CSS Modules and injecting into the head for the consumer of a library?
rollup.config.js
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import babel from '#rollup/plugin-babel';
import json from '#rollup/plugin-json';
import postcss from 'rollup-plugin-postcss';
import pkg from './package.json';
import fg from 'fast-glob';
import path from 'path';
export default [
{
input: 'src/index.js',
external: external(),
output: [
{
name: '#my/packageName',
file: pkg.module,
format: 'es',
sourcemap: true,
},
],
plugins: [
{
name: 'watch-external',
async buildStart() {
const files = await fg(['src/index.d.ts', 'playground/**/*']);
for (let file of files) {
this.addWatchFile(path.resolve(file));
}
},
},
json(),
postcss({
modules: true,
}),
babel({
exclude: /node_modules/,
babelHelpers: 'runtime',
babelrc: false,
presets: [
[
'#babel/preset-env',
{
modules: false,
useBuiltIns: 'entry',
corejs: 3,
targets: {
ie: 11,
},
},
],
'#babel/preset-react',
],
plugins: [
'#babel/plugin-transform-runtime',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-proposal-export-namespace-from',
],
}),
commonjs(),
],
},
];
function external() {
const { dependencies = {}, peerDependencies = {} } = pkg;
const externals = [
...Object.keys(dependencies),
...Object.keys(peerDependencies),
];
return id =>
// match 'lodash' and 'lodash/fp/isEqual' for example
externals.some(dep => id === dep || id.startsWith(`${dep}/`));
}
There is a bug in the library where the import is relative rather than being the module name.
There is an open pr, but the library looks like it is no longer being maintained. There are two recommended solutions in the comments:
String replace the built output
Add a custom rollup plugin to do this
This is not a bug at all. It works properly because stylesInject is just a function from 'styles-inject' package, so we can allow it to be bundled. But it is not bundled because most likely you have this setting in your rollup.config.js:
external: [
/node_modules/
]
So, replace it with a code bellow and it will work:
external: (id) => {
if (/style-inject/.test(id)) return false;
if (/node_modules/.test(id)) return true;
return false;
},
also, you can write a regexp for it instead
You need to do 2 things:
Add style-inject dependency in package.json
"dependencies": {
"style-inject": "^0.3.0"
},
Add following plugin to rollup.config.js
const plugins = [
...
{
/**
* - https://github.com/egoist/rollup-plugin-postcss/issues/381#issuecomment-880771065
* - https://lightrun.com/answers/egoist-rollup-plugin-postcss-esm-library-generated-with-rollup-plugin-postcss-throws-cannot-find-module-node_modulesstyle-in
*/
name: 'Custom Rollup Plugin`',
generateBundle: (options, bundle) => {
Object.entries(bundle).forEach((entry) => {
// early return if the file we're currently looking at doesn't need to be acted upon by this plugin
if (!entry[0].match(/.*(.scss.js)$/)) {
return;
}
// this line only runs for .scss.js files, which were generated by the postcss plugin.
// depending on the use-case, the relative path to style-inject might need to change
bundle[entry[0]].code = entry[1].code.replace(
/\.\.?\/[^\n"?:*<>|]+\/style-inject\/dist\/style-inject.es.js/g,
'style-inject',
);
});
},
}
];
References:
https://github.com/egoist/rollup-plugin-postcss/issues/381#issuecomment-880771065
https://lightrun.com/answers/egoist-rollup-plugin-postcss-esm-library-generated-with-rollup-plugin-postcss-throws-cannot-find-module-node_modulesstyle-in
Storybook currently calls react-scripts. However, I've got some parts of the CRA config overriden with craco. It means my application is invoked with craco ..., rather than react-scripts ....
Is there a clean solution to have Storybook call craco instead?
The solution I came up with is this :
.storybook/main.js :
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.js'],
addons: [
'#storybook/preset-create-react-app',
'#storybook/addon-actions',
'#storybook/addon-links',
'#storybook/addon-viewport/register',
'#storybook/addon-knobs/register',
],
webpackFinal(config, { configType }) {
return {
...config,
resolve: {
alias: {
...config.resolve.alias,
'~': path.resolve(__dirname, '../src/'),
},
},
};
},
};
I was only using the alias feature in my craco file, so here I override webpack config from storybook and only add the alias parameter. For your case, you'll need to add your own config.
The #FR073N solution is good, but since the lasts versions, this throw an error.
One line was missing to fully override correctly the webpack config.
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.js'],
addons: [
'#storybook/preset-create-react-app',
'#storybook/addon-actions',
'#storybook/addon-links',
'#storybook/addon-viewport/register',
'#storybook/addon-knobs/register',
],
webpackFinal(config, { configType }) {
return {
...config,
resolve: {
...config.resolve, // <= HERE
alias: {
...config.resolve.alias,
'~': path.resolve(__dirname, '../src/'),
},
},
};
},
};
I've successfully used storybook-preset-craco with #storybook#6.3.5 and react-scripts#4.0.3 and #craco/craco#6.2.0 in a new CRA TypeScript project.
I am trying to run nuxt locally with https to test some geolocation stuff.
(https://nuxtjs.org/, https://nuxtjs.org/api/nuxt)
I was following this tutorial:
https://www.mattshull.com/blog/https-on-localhost
And then I found this:
https://github.com/nuxt/nuxt.js/issues/146
Both links seem to describe pretty nicely how to run nuxt with server.js programmatically.
The thing is that in my nuxt.config.js I seem to have some problems.
I get the following error when runnung yarn dev:
/Users/USER/Documents/github/mynuxtrepo/nuxt.config.js:2
import { module } from 'npmmodule'
> SyntaxError: Unexpected token {
In my nuxt config I import a custom helper to generate localized routes. Not really important what it does but obviously it can't handle the import syntax.
I assume that the node version does not understand.
So how can I get it to run? Do I have to require everything instead of importing?
Or is my assumption wrong and the cause lies somewhere totally different?
Thank you for your help
Cheers.
------
Edit 1:
My nuxt config looks like this:
// eslint-disable-next-line prettier/prettier
import { generateLocalizedRoutes, generateRoutesFromData } from 'vuecid-helpers'
import config from './config'
// TODO: Add your post types
const postTypes = [{ type: 'pages' }, { type: 'posts', paginated: true }]
// TODO: Add your site title
const siteTitle = 'Title'
const shortTitle = 'short title'
const siteDescription = 'Page demonstrated with a wonderful example'
const themeColor = '#ffffff'
// TODO: Replace favicon source file in /static/icon.png (512px x 512px)
// eslint-disable-next-line prettier/prettier
const iconSizes = [32, 57, 60, 72, 76, 144, 120, 144, 152, 167, 180, 192, 512]
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: 'Loading…',
htmlAttrs: {
lang: config.env.DEFAULTLANG,
dir: 'ltr' // define directionality of text globally
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
// TODO: Check this info
{ name: 'author', content: 'Author' },
{ name: 'theme-color', content: themeColor },
// TODO: Add or remove google-site-verification
{
name: 'google-site-verification',
content: '...W1GdU'
}
],
link: []
},
/*
** env: lets you create environment variables that will be shared for the client and server-side.
*/
env: config.env,
/*
** Customize the progress-bar color
** TODO: Set your desired loading bar color
*/
loading: { color: '#0000ff' },
/*
** CSS
*/
css: ['#/assets/css/main.scss'],
/*
** Plugins
*/
plugins: [
{ src: '~/plugins/global.js' },
{ src: '~/plugins/throwNuxtError.js' },
{ src: '~/plugins/axios' },
{ src: '~/plugins/whatinput.js', ssr: false },
{ src: '~/plugins/i18n.js', injectAs: 'i18n' },
{ src: '~/plugins/vuex-router-sync' },
{ src: '~/plugins/vue-bows' },
{ src: '~/plugins/vue-breakpoint-component', ssr: false }
],
/*
** Modules
*/
modules: [
'#nuxtjs/axios',
'#nuxtjs/sitemap',
[
'#nuxtjs/pwa',
{
icon: {
sizes: iconSizes
},
// Override certain meta tags
meta: {
viewport: 'width=device-width, initial-scale=1',
favicon: true // Generates only apple-touch-icon
},
manifest: {
name: siteTitle,
lang: config.env.DEFAULTLANG,
dir: 'ltr',
short_name: shortTitle,
theme_color: themeColor,
start_url: '/',
display: 'standalone',
background_color: '#fff',
description: siteDescription
}
}
]
],
/*
** Workbox config
*/
workbox: {
config: {
debug: false,
cacheId: siteTitle
}
},
/*
** Axios config
*/
axios: {
baseURL: '/'
},
/*
** Generate
*/
generate: {
subFolders: true,
routes: [
...generateRoutesFromData({
langs: config.env.LANGS,
postTypes: postTypes,
dataPath: '../../../../../static/data',
bundle: 'basic',
homeSlug: config.env.HOMESLUG,
errorPrefix: config.env.ERROR_PREFIX
})
]
},
/*
** Build configuration
*/
build: {
extend(config, { isDev, isClient }) {
/*
** Run ESLINT on save
*/
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
/*
** Router
*/
router: {
linkActiveClass: 'is-active',
linkExactActiveClass: 'is-active-exact',
middleware: ['i18n'],
extendRoutes(routes) {
// extends basic routes (based on your files/folders in pages directory) with i18n locales (from our config.js)
const newRoutes = generateLocalizedRoutes({
baseRoutes: routes,
defaultLang: config.env.DEFAULTLANG,
langs: config.env.LANGS,
routesAliases: config.routesAliases
})
// Clear array
routes.splice(0, routes.length)
// Push newly created routes
routes.push(...newRoutes)
}
},
/*
** Sitemap Configuration
*/
sitemap: {
path: '/sitemap.xml',
hostname: config.env.FRONTENDURLPRODUCTION,
cacheTime: 1000 * 60 * 15,
generate: true,
routes: [
...generateRoutesFromData({
langs: config.env.LANGS,
postTypes: postTypes,
dataPath: '../../../../../static/data',
bundle: 'basic',
homeSlug: config.env.HOMESLUG,
errorPrefix: config.env.ERROR_PREFIX
})
]
}
}
You can see that the generateLocalizedRoutes and the generateRoutesFromData methods are used to generate localized routes and is also taking post json files to generate routes from data (:slug).
--------- Edit 2:
I got it to run eventually.
I had to require all parts within the nuxt.config.js instead of importing them. I also resolved issues with the certificates. So I thought it was all cool 🚀.
BUT!!! 🚧:
Then I found out that I had my config file used within my post template.
So I thought I would also require the file within my template:
Like const config = require('~/config').
But then I would get this error:
[nuxt] Error while initializing app TypeError: ""exports" is read-only"
After some research, I found that is probably a thing when using common.js require and module.exports together with ES6 import/export within my project. (Probably linked to: https://github.com/FranckFreiburger/vue-pdf/issues/1).
So how could I still use my config.js when running nuxt programmatically (with require) and then also within my app?
I am glad to hear any ideas on this...
Cheers
Well, just to close this:
My problem resulted from running nuxt as a node app, which does not understand ES6 import statements, which appeared in my nuxt config.
So I had to rewrite things to work with commons.js (require).
This works for now.
(I also tried to run babel-node when starting the server.js, but had no success. Does not mean this did not work, I just wasn't keen on trying harder).
Thanks for the comments.
cheers