I’m developing app using JS and Vue.js and get error on line:
import Vue from 'vue'
I’m getting this:
Uncaught SyntaxError: The requested module
‘/node_modules/.vite/vue.js?v=6dba2ea6’ does not provide an export
named ‘default’
I googled that might be caused by old Vue version, in my package.json vue version is 3.2.6, but
npm view vue version
returns 2.6.14, I tried to upgrade it with Vue CLI
vue upgrade
but npm command still return 2.6.14
I hope you could help me, what did I wrong or it is not even versions problem? Thanks!
asked Dec 24, 2021 at 18:19
The reason it didn’t work is that Vue provides a named export, whereas you are trying to import it as though it had a default
export.
To make a named import (which you must do with named exports), you need to wrap the name of the export you want to import in curly braces, so {}
around Vue
like this:
import { Vue } from 'vue';
// ^^^ name of export
It will work
The thing you want to do is import vue but it doesnot have a default export function or either the default thing to export is not set in vue module. So you have to select function named vue by adding curly braces.
If it had a default
export function, then your code would have worked and in that case you could write anything in place of vue
like below:
import anyname from 'vue'
anyname
is name whatever you want.
connexo
52.6k14 gold badges85 silver badges121 bronze badges
answered Dec 24, 2021 at 22:09
jassjass
815 bronze badges
1
Another solution is to use the createApp()
function like this:
import { createApp } from 'vue';
createApp(App).mount('#app')
I’m not experienced in Vue JS, but it looks like they no longer export a single object. Ranger a collection of things.
answered Aug 7, 2022 at 9:27
StheSthe
2,5562 gold badges30 silver badges47 bronze badges
Usually as of Vue 2, in the src/main.js file, we’re bootstrapping the app by calling a new Vue as a constructor for creating an application instance.
import Vue from "vue";
import App from "./App.vue";
import router from './router'
const app = new Vue({
router,
render: h => h(App)
});
For Vue 3 the initialization code syntax has changed and is much cleaner and compact
import { createApp } from "vue";
createApp(App).use(store).mount('#app')
answered Sep 29, 2022 at 4:46
This worked for me:-
import * as Vue from 'vue';
and similarly for different packages:-
import * as Vuex from 'vuex';
import * as VueRouter from 'vue-router';
As of time of writing:-
"devDependencies": {
...
"vue": "^3.2.45",
answered Jan 9 at 9:28
cookiecookie
2,3647 gold badges27 silver badges49 bronze badges
To solve the error ‘does not provide an export name default’ in JavaScript, use the default keyword to make it the default export and the import. For example, the SyntaxError occurs when we try to import a function or value from the file using default import, but the file does not contain a default export.
Let’s see a scenario where we get SyntaxError.
Create a JavaScript file where we declare a function sum, and we are importing it into another JS file.
file1.js
export function sum(a, b){
return a+b;
}
This is using named export. Now, write the below file that imports the function from file1.js.
file2.js
import sum from "./file1.js";
let x = sum(15, 40);
console.log(x);
If you run the file2.js file using the node app file, you will get the following error.
This code will generate a ‘does not provide an export name default’ error because, in file1, we used named export, and in file2, we are importing the function using default export.
SyntaxError: The requested module './file1.js' does not provide an export named 'default'
To solve SyntaxError: does not provide an export named ‘default’; use the default keyword to make it the default export and the import. Then import a function without wrapping the corresponding import in curly braces. We can only have a single export default in a JavaScript file.
file1.js
export default function sum(a, b){
return a+b;
}
This is using named export. Now below file imports the function from file1.js.
file2.js
import sum from "./file1.js";
let x = sum(15, 40);
console.log(x);
Output
Note: we never work with curly braces when working with default exports. We import a named export inside curly braces.
file2. js
import { sum } from './sqcube.js';
let x = sum(15, 40);
console.log(x);
If you run the above file, you will get the following error.
SyntaxError: The requested module './file1.js' does not provide an export named 'sum'
Ensure not to use curly braces when you want to import default exports and use curly braces when you want to import named exports.
That’s it for this tutorial.
Related posts
How to Solve cannot find module and its corresponding type declarations
How to Solve cannot read property of null
How to Solve SyntaxError: Unexpected end of input
How to Solve Uncaught ReferenceError: required is not defined
How to solve reference error: window is not defined
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. Krunal has experience with various programming languages and technologies, including PHP, Python, and expert in JavaScript. He is comfortable working in front-end and back-end development.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent.
What steps will reproduce the bug?
git clone https://github.com/dandv/lib-does-not-provide-export-foo
cd lib-does-not-provide-export-foo/use-lib
node use-it.js # node v13.9.0
What is the expected behavior?
The script should run and output foo
.
What do you see instead?
import { foo } from '../lib/index.js';
^^^
SyntaxError: The requested module '../lib/index.js' does not provide an export named 'foo'
Additional information
Within the context of a large project, this was a pretty odd mystery, when lib/index.js
clearly exports foo
. Feel free to have some fun figuring out it (not hard with the minimal repro repo, but imagine the confused looks in a real-world scenario). Solution below.
.
.
.
.
.
.
.
.
.
.
Solution
lib/package.json lacks "type": "module"
.
Proposal
A clearer error would indicate that the imported file is not a module at all. As it is, the error suggested that other symbols were exported fine, so I kept double checking for typos and what not. This happened during a conversion to TypeScript that involved adding one export. The error made me think the problem was that export; it was not — it was that I forgot to add "type": "module"
to package.json
.
The full title of the bug would be «Misleading error that module does not provide export when «module» is not in fact a module», but that would have been a spoiler.
strarsis reacted with heart emoji
format
be assigned as commonjs
format = getPackageType(parsed.href) === TYPE_MODULE ? | |
‘module’ : ‘commonjs’; |
and loaderInstance
is the commonjs
loader
if (format === ‘dynamic’) { | |
if (typeof this._dynamicInstantiate !== ‘function’) | |
throw new ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK(); | |
loaderInstance = async (url) => { | |
debug(`Translating dynamic ${url}`); | |
const { exports, execute } = await this._dynamicInstantiate(url); | |
return createDynamicModule([], exports, url, (reflect) => { | |
debug(`Loading dynamic ${url}`); | |
execute(reflect.exports); | |
}).module; | |
}; | |
} else { | |
if (!translators.has(format)) | |
throw new ERR_UNKNOWN_MODULE_FORMAT(format); | |
loaderInstance = translators.get(format); | |
} |
translators.set(‘commonjs’, function commonjsStrategy(url, isMain) { | |
debug(`Translating CJSModule ${url}`); | |
const pathname = internalURLModule.fileURLToPath(new URL(url)); | |
const cached = this.cjsCache.get(url); | |
if (cached) { | |
this.cjsCache.delete(url); | |
return cached; | |
} | |
const module = CJSModule._cache[ | |
isWindows ? StringPrototypeReplace(pathname, winSepRegEx, ‘\’) : pathname | |
]; | |
if (module && module.loaded) { | |
const exports = module.exports; | |
return new ModuleWrap(url, undefined, [‘default’], function() { | |
this.setExport(‘default’, exports); | |
}); | |
} | |
return new ModuleWrap(url, undefined, [‘default’], function() { | |
debug(`Loading CJSModule ${url}`); | |
// We don’t care about the return val of _load here because Module#load | |
// will handle it for us by checking the loader registry and filling the | |
// exports like above | |
CJSModule._load(pathname, undefined, isMain); | |
}); | |
}); |
ESMLoader
directly use v8
esm import, I think we currently haven’t checker if a source is esm or cjs
MylesBorins
added
the
esm
Issues and PRs related to the ECMAScript Modules implementation.
label
Mar 9, 2020
There seems to be a bug here in the loader itself. This module should not be loaded as ESM, but rather as CJS. Was able to make the repro even smaller
index.mjs
import { foo } from './index.cjs'; console.log(foo());
index.cjs
export function foo() { return 'foo'; }
Even though this has ESM syntax in it it should fail to even import as you are attempting to do a named exports of the CJS module. pinging @jkrems and @guybedford to take a look
I don’t think it’s a bug, because you not mark the file as the esm
module. and it’s just an incorrect error message. and can we add support that esm loader can check the js
file as mjs
file and log the message like Load js as commonjs error
Even though this has ESM syntax in it it should fail to even import as you are attempting to do a named exports of the CJS module.
Maybe I’m missing something but this looks to error correctly because of the lack of an export named foo
, at least according to the issue description:
SyntaxError: The requested module '../lib/index.js' does not provide an export named 'foo'
Even though this has ESM syntax in it it should fail to even import as you are attempting to do a named exports of the CJS module.
Maybe I’m missing something but this looks to error correctly because of the lack of an export named
foo
, at least according to the issue description:SyntaxError: The requested module '../lib/index.js' does not provide an export named 'foo'
why correctly?
when
import { foo } from '../lib/index.js';
import {foo} from '../lib/index.js'; ^^^ SyntaxError: The requested module '../lib/index.js' does not provide an export named 'foo'
but, when
import foo from '../lib/index.js'; `` ```bash export function foo() { ^^^^^^ SyntaxError: Unexpected token 'export'
this is two kinds of different error types, and the first error message will misleading users.
another example
// change https://github.com/dandv/lib-does-not-provide-export-foo/blob/master/lib/index.js exports.foo = 123
the error message still occur
import { foo } from '../lib/index.js'; ^^^ SyntaxError: The requested module '../lib/index.js' does not provide an export named 'foo'
but I change use-lib/index.js
to
import md from '../lib/index.js'; console.log(md);
thing go weird
(node:24052) ExperimentalWarning: The ESM module loader is experimental. { foo: 123 }
I’m not saying it’s not confusing right now. The issue is just: This happens before we even try to run the code and that’s when a CommonJS syntax errors would happen. It may be possible to somehow detect this specific error and try to gather some more context but it would be tricky.
To go into what you were seeing in your last comment: Exports in ES modules are very different from the «exports» object in CommonJS, confusingly. Each module export is a variable/identifier. The following CommonJS code doesn’t create a new variable, it only sets a property on one:
So afterwards the CommonJS still only has a single export — the module.exports
object. That’s all a CommonJS file exports, from an ES module perspective. Your later code could be rewritten as:
import { default as md } from '../lib/index.js'; console.log(md);
So your importing the default
export (the module.exports
object) from ../lib/index.js
which is an object that has a property foo
, as set above.
I’m not saying it’s not confusing right now. The issue is just: This happens before we even try to run the code and that’s when a CommonJS syntax errors would happen. It may be possible to somehow detect this specific error and try to gather some more context but it would be tricky.
To go into what you were seeing in your last comment: Exports in ES modules are very different from the «exports» object in CommonJS, confusingly. Each module export is a variable/identifier. The following CommonJS code doesn’t create a new variable, it only sets a property on one:
So afterwards the CommonJS still only has a single export — the
module.exports
object. That’s all a CommonJS file exports, from an ES module perspective. Your later code could be rewritten as:import { default as md } from '../lib/index.js'; console.log(md);So your importing the
default
export (themodule.exports
object) from../lib/index.js
which is an object that has a propertyfoo
, as set above.
Yeah, I get you
guybedford
added
the
doc
Issues and PRs related to the documentations.
label
Mar 12, 2020
Marking as a documentation issue since this is a common error that should be well documented. //cc @GeoffreyBooth
I think this needs more than just documentation. If you directly run node lib/index.js
, you’ll see a really nice little warning:
$ node index.js
(node:83643) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/private/tmp/tp/lib-does-not-provide-export-foo/lib/index.js:1
export function foo() {
^^^^^^
SyntaxError: Unexpected token 'export'
I would have wanted this case to show a better SyntaxError, and maybe a warning, something like:
(node:83643) Warning: '../lib/index.js' is a CommonJS module,
but ES modules can't import named exports from CommonJS modules
SyntaxError: The requested module '../lib/index.js' does not provide an export named 'foo'
I’ll note that the error is marginally better if you try to import the default export without braces, like this:
import foo from '../lib/index.js'
export function foo() {
^^^^^^
SyntaxError: Unexpected token 'export'
I just realized that the scope of this is bigger than «ESM misinterpreted as CJS.» This error applies even when the imported script is legit CJS with named exports.
dependency.cjs
module.exports.name = "foo";
dependent.mjs
import {name} from './dependency.cjs'; console.log({name});
You get this: SyntaxError: The requested module './dependency.cjs' does not provide an export named 'name'
which is only «true» because ES modules aren’t allowed to import CJS named exports.
The SyntaxError in this case should be much clearer:
SyntaxError: The requested module './dependency.cjs' is a CommonJS module, which can only provide a default export, not named exports, to an ES module script.
I just realized that the scope of this is bigger than «ESM misinterpreted as CJS.» This error applies even when the imported script is legit CJS with named exports.
dependency.cjs
module.exports.name = "foo";dependent.mjs
import {name} from './dependency.cjs'; console.log({name});You get this:
SyntaxError: The requested module './dependency.cjs' does not provide an export named 'name'
which is only «true» because ES modules aren’t allowed to import CJS named exports.The SyntaxError in this case should be much clearer:
SyntaxError: The requested module './dependency.cjs' is a CommonJS module, which can only provide a default export, not named exports, to an ES module script.
How do you re-write this so it works?
This error was considerably enhanced in Node 14.8 I believe. Now the error message says:
SyntaxError: The requested module './dependency.cjs' is expected to be of type
CommonJS, which does not support named exports. CommonJS modules can be
imported by importing the default export.
For example:
import pkg from './dependency.cjs';
const {name} = pkg;
And, indeed, that’s what you’d do to fix dependent.mjs
.
import pkg from './dependency.cjs';
const {name} = pkg;
console.log({name});
@dandv @dfabulich @kathy-ems Node.js 14.13.0 added support for named CJS exports, see #35249 and this change has also been backported to Node.js v12.20.0.
Can you confirm that
import { foo } from '../lib/index.js';
now also works for you if index.js
is a CJS file?
delhanty
pushed a commit
to delhanty/kit
that referenced
this issue
May 17, 2021
How Do I Solve This I’m New to Node JS?
How Do I Solve This I’m New to Node JS?
Use the suggested code from the error message.
Closing as I think this has been addressed.
What do we do when it’s a dependency that’s doing the import
‘ing?
I’m receiving this error and don’t have control over the dependency’s code. Any suggestions?
Have you tried reporting this as a bug to the dependency which is causing the issue?
What do we do when it’s a dependency that’s doing the
import
‘ing?I’m receiving this error and don’t have control over the dependency’s code. Any suggestions?
Yeah you have to provide a fix in the repo. I’m facing this currently and it’s a bit frustrating.
“The requested module does not provide an export named” in JavaScript is a common error related to import and export modules. The below explanations can help you know more about this error of causes and solutions.
Basically, this error happens because you have declared the export default function in a module but when you import and use them, you declare them as a named module, or vice versa. For example, you have an export default function in a file, for example: index.js.
// Declare export default function export default function hello() { console.log("LearnShareIT") }
And then in the HTML file, you import them and use them as a named function:
<html> <body> <h1>LearnShareIT</h1> <script type = "module"> // Import the function as a named function (with brackets) import {hello} from './index.js'; console.log(hello()); </script> </body> </html>
Output:
The ES6 does not allow programmers to mix up default and named exports and imports concurrently. If this is exactly the cause of your problem then we suggest you the following solution.
How to solve the error “The requested module does not provide an export named” in JavaScript?
Using default imports and export
As we have explained, you must maintain the imports and exports in your project. You should use curly braces only when importing named exports but not default exports. For instance:
In the file index.js:
// Declare export default function export default function hello() { console.log("LearnShareIT") }
<html> <body> <h1>LearnShareIT</h1> <script type = "module"> // Import the function as a default function (without brackets) import hello from './index.js'; console.log(hello()); </script> </body> </html>
Output
LearnShareIT
The above example used the default function to import and export in the program. As can be seen, when we import it in the HTML Document, we neglect the brackets around the ‘hello’ which is the name of the function which we want to export. If you want to import and export a named function instead of default function, please take a look at the following solution.
Using named imports and export
Another way to fix this problem is to export a named function in your module file. And then import them with the brackets as a named module when you need to use that function.
// Declare export named function export function hello() { console.log("LearnShareIT") }
<html> <body> <h1>LearnShareIT</h1> <script type = "module"> // Import the function as a named function (with brackets) import {hello} from './index.js'; console.log(hello()); </script> </body> </html>
Output
LearnShareIT
As can be seen clearly, using named export also produces the same results as in the first solution. So make sure to check if you don’t mix up those solutions together because that is the reason for the error.
Summary
In this article, we have helped you to deal with the JavaScript error “The requested module does not provide an export named” in JavaScript. By declaring ES6 imports and exports in the same type, you can easily avoid this error.
Maybe you are interested:
- “TypeError: toISOString is not a function” in JavaScript
- TypeError: createPopper is not a function in Bootstrap
- TypeError: getContext is not a function in JavaScript
I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.
Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R
0 / 0 / 0 Регистрация: 26.03.2021 Сообщений: 7 |
|
1 |
|
29.07.2022, 19:39. Показов 2403. Ответов 2
Не знаю куда писать по gulp, попробую сюда). При запуске gulp вылетает ошибка: file:///F:/web/Practice/Funiro/config/gulp-tasks/reset.js:1 Раньше всё было гуд, ничего не устанавливал, не изменял. Как это исправить?
__________________
0 |
Ищу работу React 816 / 621 / 213 Регистрация: 17.07.2021 Сообщений: 1,338 Записей в блоге: 7 |
|
29.07.2022, 21:14 |
2 |
Как это исправить? найти пакет Добавлено через 1 минуту
1 |
2 / 1 / 1 Регистрация: 13.02.2020 Сообщений: 1 |
|
01.08.2022, 18:47 |
3 |
РешениеДобрый день, у меня также было, помогло замена в package.json c
1 |
💡 Take a look at issues for known issues and workarounds
Can’t find loader handling ‘.vue’ files
While we added a workaround to mitigate this, vite recommends explicitly defining extensions for non javascript assets.
- import MyComponent from '~/components/MyComponent'
+ import MyComponent from '~/components/MyComponent.vue'
Uncaught SyntaxError: The requested module … does not provide an export named ‘default’
Vite has an issue for pre-bundling dependencies with named exports (#56 ). Workaround is to exlude them from optimizeDeps
// nuxt.config
export default {
vite: {
optimizeDeps: {
exclude: [
'date-fns'
]
}
}
}
By default some known packages are excluded. Please reply to issue #56 to add more known problematic packages.
No such file or directory, rmdir node_modules/.vite/temp
This is a race condition that server cache dir removes when reloading (vitejs/vite/pull/2299 )
Currently using a fork of vite to address this issue. If you still have the issue, please add version and error in #2
styleResources
styleResources depends on webpack and yet is not supported by nuxt-vite.
You can configure global CSS import using preprocessorOptions
option of CSS loader:
Example with SCSS:
export default {
css: ["@/assets/scss/global.scss"],
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "@/assets/scss/global.scss";',
},
},
},
},
}
Graphql support
Currently there is no module support for handling gql files (#31 ).
Best solution for now is to wrap gql code into js
or ts
and using graphql-tag or using raw GraphQL queries. Remember to add loc.source.body
.
Example:
// queries/products.js
import gql from 'graphql-tag'
export default gql`
query Products {
products {
id
name
}
}
`
// pages/index.vue
import products from '~/queries/products'
export default {
async asyncData({ $strapi }) {
const response = await $strapi.graphql({
query: products.loc.source.body,
})
return {
response
}
}
}
SSR Assets issues
Related to #7 , errors can happen while importing assets from your templates.
An example of breaking import:
<img src="../static/img/logo.svg">
Until this issue is fixed, you need to disable the SSR in development and refer to your images using the complete path from the root folder of your project.
An example of working import:
// nuxt.config.js
export default {
ssr: false
}
<img src="~/static/img/logo.svg" />
Edit this page on GitHub
Updated at Mon, Oct 11, 2021