Webpack/Vue vue__WEBPACK_IMPORTED_MODULE... is not defined - vue.js
I would like to make a web app which works with VueJS, the scripts files will be packed all in one with Webpack.
I've installed Vue and Webpack with Npm.
Here is the structure of my app folder :
dist
- main.js
- output.css
node_modules
- "contain the dependencies installed with NPM, including Vue"
package-lock.json
package.json
src
- app.js
- App.vue
- index.html
- input.css
tailwind.config.js
template.html
webpack.config.js
Here's my dependencies' in the "package.json" file :
"devDependencies": {
"tailwindcss": "^3.0.23",
"webpack": "^5.69.1",
"webpack-cli": "^4.9.2"
},
"dependencies": {
"#heroicons/vue": "^1.0.5",
"vue": "^3.2.31"
}
Here's the content of my "webpack.config.js"
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
};
Here's the content of my "app.js"
import Vue from 'vue'
console.log(Vue); // => return "undefined"
MY PROBLEM :
Vue is not loaded, and I don't know why.
I've the following error in the log of the main.js building :
npx webpack --config webpack.config.js --mode=development --watch
asset main.js 521 KiB [compared for emit] (name: main)
runtime modules 891 bytes 4 modules
cacheable modules 429 KiB
modules by path ./node_modules/#vue/ 428 KiB
./node_modules/#vue/runtime-dom/dist/runtime-dom.esm-bundler.js 59.9 KiB [built] [code generated]
./node_modules/#vue/runtime-core/dist/runtime-core.esm-bundler.js 304 KiB [built] [code generated]
./node_modules/#vue/reactivity/dist/reactivity.esm-bundler.js 40.3 KiB [built] [code generated]
./node_modules/#vue/shared/dist/shared.esm-bundler.js 23.5 KiB [built] [code generated]
./src/app.js 184 bytes [built] [code generated]
./node_modules/vue/dist/vue.runtime.esm-bundler.js 611 bytes [built] [code generated]
WARNING in ./src/app.js 10:12-15
export 'default' (imported as 'Vue') was not found in 'vue' (possible exports: BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId)
Does somebody have a solution or a way to follow?
As the error says, there is no 'default' export in 'vue' package. That is because the global Vue API initialization in Vue 3 has been changed from:
import Vue from 'vue'
to
import { createApp } from 'vue'
const app = createApp({})
In other words, the global API is not exported by default by the 'vue' package, but is created by the 'createApp' function.
Related
Trying to add bootstrap into my VUE CLI and it's not working
I am trying to add bootstrap into my Vue CLI project and I don't know if it works. I am following the get started link by Bootstrap https://bootstrap-vue.org/docs and I always get stuck.. First I run the: "yarn add vue bootstrap bootstrap-vue" command in the directory where my project is stored. This part works fine, but next it's asking me to import these files into the main.js file: import Vue from 'vue' import { BootstrapVue, IconsPlugin } from 'bootstrap-vue' // Import Bootstrap and BootstrapVue CSS files (order is important) import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' // Make BootstrapVue available throughout your project Vue.use(BootstrapVue) // Optionally install the BootstrapVue icon components plugin Vue.use(IconsPlugin) So this is what I have now in the main.js file: import { createApp } from 'vue' import App from './App.vue' import Vue from 'vue' import { BootstrapVue, IconsPlugin } from 'bootstrap-vue' // Import Bootstrap and BootstrapVue CSS files (order is important) import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' // Make BootstrapVue available throughout your project Vue.use(BootstrapVue) // Optionally install the BootstrapVue icon components plugin Vue.use(IconsPlugin) createApp(App).mount('#app') And this is the error/warning I receive when running the app: [BABEL] Note: The code generator has deoptimised the styling of /Users/rubencapota/project-vue/node_modules/bootstrap-vue/esm/icons/icons.js as it exceeds the m WARNING Compiled with 2 warnings 18:52:41 warning in ./node_modules/bootstrap-vue/esm/vue.js export 'default' (reexported as 'Vue') was not found in 'vue' (possible exports: BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId) warning in ./src/main.js export 'default' (imported as 'Vue') was not found in 'vue' (possible exports: BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId) App running at: - Local: http://localhost:8080/ - Network: http://192.168.0.209:8080/ [BABEL] Note: The code generator has deoptimised the styling of /Users/rubencapota/project-vue/node_modules/bootstrap-vue/esm/icons/icons.js as it exceeds the m WARNING Compiled with 2 warnings 18:52:41 warning in ./node_modules/bootstrap-vue/esm/vue.js export 'default' (reexported as 'Vue') was not found in 'vue' (possible exports: BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effe When I run the application I just see a blank page in the browser and not the one that Vue creates by default. Sorry for this stupid question and thanks in advance for your help.
Adding a plugin to vite
I am trying out Vite and using it to develop a Vue app with Prismic Cms. In reading Prismic Doc's I see have to install dependencies npm install #prismicio/vue #prismicio/client prismic-dom Doc's then say you have to register it: To use #prismicio/vue, you must register it in your app entry point, which is most likely ~/src/main.js. The access token and API options are only necessary if your repo is set to private. // `~/src/main.js` import Vue from 'vue' import App from './App' import PrismicVue from '#prismicio/vue' import linkResolver from './link-resolver' // Update this path if necessary const accessToken = '' // Leave empty if your repo is public const endpoint = 'https://your-repo-name.cdn.prismic.io/api/v2' // Use your repo name // Register plugin Vue.use(PrismicVue, { endpoint, apiOptions: { accessToken }, linkResolver }) In reading Vite doc's I see you add plugins via the vite.config.js file instead of using Vue.use() in main.js. So I created one as follows: import { defineConfig } from "vite"; import Vue from "#vitejs/plugin-vue"; import PrismicVue from "#prismicio/vue"; import linkResolver from "./link-resolver"; // Update this path if necessary const accessToken = ""; // Leave empty if your repo is public const endpoint = "https://*******-****.cdn.prismic.io/api/v2"; // Use your repo name // https://vitejs.dev/config/ export default defineConfig({ plugins: [ Vue(), PrismicVue({ endpoint, apiOptions: { accessToken }, linkResolver, }), ], }); However I get error as follows: failed to load config from C:\Users\akill\Github\shs\vite.config.js error when starting dev server: TypeError: (0 , import_vue.default) is not a function at Object.<anonymous> (C:\Users\akill\Github\shs\vite.config.js:53:28) at Module._compile (internal/modules/cjs/loader.js:1137:30) at Object.require.extensions.<computed> [as .js] (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:76005:20) at Module.load (internal/modules/cjs/loader.js:985:32) at Function.Module._load (internal/modules/cjs/loader.js:878:14) at Module.require (internal/modules/cjs/loader.js:1025:19) at require (internal/modules/cjs/helpers.js:72:18) at loadConfigFromBundledFile (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:76013:17) at loadConfigFromFile (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:75932:32) at processTicksAndRejections (internal/process/task_queues.js:97:5) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! shs#0.0.0 dev: `vite --open` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the shs#0.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. I also notice VS Code is giving me a hint # import of PrismicVue line of Could not find a declaration file for module '#prismicio/vue'. 'c:/Users/akill/Github/shs/node_modules/#prismicio/vue/dist/prismic-vue.common.js' implicitly has an 'any' type. I have isolated it to the line "PrismicVue({endpoint,apiOptions: { accessToken }, Etc....})," causing the error. Can someone explain what is the proper way to import this plugin in Vite? Thanks in advance.
vite.config.js's plugins property is intended for Vite plugins, which are for Vite itself (e.g., adding a custom transform for specific file types). That config is not for Vue plugins, which can only be installed in a Vue 3 app with app.use(). To setup Prismic with Vue 3: Install the following dependencies. The alpha versions of #prismicio/vue and #prismicio/client (3.x and 6.x, respectively) are needed for Vue 3 support. npm i -S #prismicio/vue#alpha #prismicio/client#alpha prismic-dom Create a link resolver that returns a route path based on a given Prismic document type. The resolved route path should already be registered in router.js: const resolver = doc => { if (doc.isBroken) { return '/not-found' } if (doc.type === 'blog_home') { return '/blog' } else if (doc.type === 'post') { return '/blog/' + doc.uid } return '/not-found' } export default resolver In src/main.js, use createPrismic() from #prismic/vue to create the Vue plugin, and pass that along with the link resolver to app.use(): import { createApp } from 'vue' import { createPrismic } from '#prismicio/vue' import linkResolver from './prismic/link-resolver' import App from './App.vue' import router from './router' createApp(App) .use(router) .use(createPrismic({ endpoint: 'https://blog-demo2.prismic.io/api/v2', linkResolver, })) .mount('#app') demo
You probably have a mess in your setup / package.json as there is nothing special to do - I bet that you are missing vite-plugin-vue2 and vue-template-compiler. To get it working, try to create a new project with the following : vite.config.js: const { createVuePlugin } = require('vite-plugin-vue2'); module.exports = { plugins: [ createVuePlugin() ] }; main.js: import Vue from 'vue'; import App from './App.vue'; import PrismicVue from "#prismicio/vue"; const accessToken = ""; // Leave empty if your repo is public const endpoint = "https://*******-****.cdn.prismic.io/api/v2"; // Use your repo name Vue.use(PrismicVue, { endpoint: endpoint }); new Vue({ render: (h) => h(App), }).$mount('#app'); App.vue: <template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png" /> </div> </template> <style> #app { text-align: center; } </style> then package.json: { "name": "vue2-prismic", "version": "0.0.0", "scripts": { "dev": "vite", "build": "vite build", "serve": "vite preview" }, "dependencies": { "#prismicio/client": "^5.1.0", "#prismicio/vue": "^2.0.11", "prismic-dom": "^2.2.6", "vite-plugin-vue2": "^1.4.0", "vue": "^2.6.12", "vue-template-compiler": "^2.6.14" }, "devDependencies": { "vite": "^2.0.5" } }
Web3js fails to import in Vue3 composition api project
I've created a brand new project with npm init vite bar -- --template vue. I've done an npm install web3 and I can see my package-lock.json includes this package. My node_modules directory also includes the web3 modules. So then I added this line to main.js: import { createApp } from 'vue' import App from './App.vue' import Web3 from 'web3' <-- This line createApp(App).mount('#app') And I get the following error: I don't understand what is going on here. I'm fairly new to using npm so I'm not super sure what to Google. The errors are coming from node_modules/web3/lib/index.js, node_modules/web3-core/lib/index.js, node_modules/web3-core-requestmanager/lib/index.js, and finally node_modules/util/util.js. I suspect it has to do with one of these: I'm using Vue 3 I'm using Vue 3 Composition API I'm using Vue 3 Composition API SFC <script setup> tag (but I imported it in main.js so I don't think it is this one) web3js is in Typescript and my Vue3 project is not configured for Typescript But as I am fairly new to JavaScript and Vue and Web3 I am not sure how to focus my Googling on this error. My background is Python, Go, Terraform. Basically the back end of the back end. Front end JavaScript is new to me. How do I go about resolving this issue?
Option 1: Polyfill Node globals/modules Polyfilling the Node globals and modules enables the web3 import to run in the browser: Install the ESBuild plugins that polyfill Node globals/modules: npm i -D #esbuild-plugins/node-globals-polyfill npm i -D #esbuild-plugins/node-modules-polyfill Configure optimizeDeps.esbuildOptions to use these ESBuild plugins. Configure define to replace global with globalThis (the browser equivalent). import { defineConfig } from 'vite' import GlobalsPolyfills from '#esbuild-plugins/node-globals-polyfill' import NodeModulesPolyfills from '#esbuild-plugins/node-modules-polyfill' export default defineConfig({ ⋮ optimizeDeps: { esbuildOptions: { 2️⃣ plugins: [ NodeModulesPolyfills(), GlobalsPolyfills({ process: true, buffer: true, }), ], 3️⃣ define: { global: 'globalThis', }, }, }, }) demo 1 Note: The polyfills add considerable size to the build output. Option 2: Use pre-bundled script web3 distributes a bundled script at web3/dist/web3.min.js, which can run in the browser without any configuration (listed as "pure js"). You could configure a resolve.alias to pull in that file: import { defineConfig } from 'vite' export default defineConfig({ ⋮ resolve: { alias: { web3: 'web3/dist/web3.min.js', }, // or alias: [ { find: 'web3', replacement: 'web3/dist/web3.min.js', }, ], }, }) demo 2 Note: This option produces 469.4 KiB smaller output than Option 1.
You can avoid the Uncaught ReferenceError: process is not defined error by adding this in your vite config export default defineConfig({ // ... define: { 'process.env': process.env } })
I found the best solution. The problem is because you lose window.process variable, and process exists only on node, not the browser. So you should inject it to browser when the app loads. Add this line to your app: window.process = { ...window.process, };
import vue-awesome icons error while jest testing with nuxt on node 13.9.0
I have followed the instructions on https://github.com/Justineo/vue-awesome in my jest.config.js I add the following transformIgnorePatterns: [ '/node_modules(?![\\\\/]vue-awesome[\\\\/])/' ] my nuxt.config.js build: { transpile: [/^vue-awesome/] // enable font-awesome integration. }, The icons work just fine when I'm running the dev box, but I get the following when I run yarn test: [path/to/project]/node_modules/vue-awesome/icons/building.js:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue' ^^^^^^ SyntaxError: Cannot use import statement outside a module explicitly, the issue seems to be something to do with how babel reads (or overlooks) the imports above the Icon component import. So, for example, given the building.js in the error log above, here is how the import looks in the vuejs file: <script> import 'vue-awesome/icons/building' import Icon from 'vue-awesome/components/Icon' export default { componentes: { 'v-icon': Icon } ... } </script>
It looks like I have to explicitly mock the component and its imports at the top of the file (below the imports) the following works for my test. import { shallowMount, createLocalVue } from '#vue/test-utils' import Vuex from 'vuex' import { AxiosSpy, MockNuxt } from 'jest-nuxt-helper' import index from '#/pages/courses/index' // MOCKS: jest.mock('vue-awesome/icons/building', () => '') jest.mock('vue-awesome/components/Icon', () => '<div></div>') ...
Loading vuetify in a package that i use in a vuetify project
What is the correct way of loading vuetify into a package that i use in a vuetify project? When serving projects it all seems to work fine but when i build the project i've got some issues with the css/sass things i've tried: With vuetify loader: the css is loaded twice so i can't overwrite sass variables Without vuetify loader: the package doesn't have the vuetify css, so it looks horrible Without vuetify loader with vuetify.min.css: the css is loaded twice so i can't overwrite sass variables, and the loaded css is all the css so it's huge My package is called vuetify-resource, and this is the source code of the index.js (without the vuetify loader) At this point everything works on npm run serve But when i build the package doesn't have "access" to the vuetify css. import Vue from 'vue'; import Vuetify from 'vuetify'; import VuetifyResourceComponent from './VuetifyResource.vue'; Vue.use(Vuetify); const VuetifyResource = { install(Vue, options) { Vue.component('vuetify-resource', VuetifyResourceComponent); }, }; export default VuetifyResource;
To solve my issue i had to do a couple of things. Make peer dependencies of vuetify and vue add vuetify to the webpack externals, so when someone uses the package, the package uses that projects vuetify not longer import vue and vuetify in the index.js it's not needed, the project that uses the package imports that import the specific components that you use in every .vue file for example: Vue.config.js module.exports = { configureWebpack: { externals: {'vuetify/lib': 'vuetify/lib'}, }, }; index.js import VuetifyResourceComponent from './VuetifyResource.vue'; const VuetifyResource = { install(Vue, options) { Vue.component('vuetify-resource', VuetifyResourceComponent); }, }; export default VuetifyResource; part of the component.vue import { VDataTable } from 'vuetify/lib'; export default { name: 'vuetify-resource', components: { VDataTable },
Step 4 in Ricardo's answer is not needed if you use vuetify-loader, it will do the job for you. And I would modify step 2 to also exclude Vuetify's styles/css from your bundle. If you don't exclude them you can run into styling issues when the Vuetify version differ between your library and your application. Use a regular expression in vue.config.js like this: configureWebpack: { externals: /^vuetify\// }. That way, only your own styles are included in the library bundle.