如何导出一个在ES6中被导入的模块?

huangapple go评论81阅读模式
英文:

How to export a module which is imported in ES6?

问题

以下是翻译好的部分:

当我运行index.vue时,出现错误:

SyntaxError: 请求的模块'/@fs/Users/VJ/Desktop/project/app.ts?t=1691652606598'未提供名为'test'的导出

如何修复它?

英文:

Here are 3 files:

// ./app/index.ts
const app = {
  test: 1,
  ...
}
export default app
// ./app.ts
import app from './app/index'

export default app
// ./index.vue
import { test } from './app.ts'

console.log(test)

When I run index.vue an error shows:

SyntaxError: The requested module '/@fs/Users/VJ/Desktop/project/app.ts?t=1691652606598' does not provide an export named 'test'

How can I fix it?

答案1

得分: 1

以下是已翻译的内容:

./app/index.ts:

const app = {
    test: 1,
    // ...
};

export { app };

./app.ts:

import { app } from './app/index';

export default app;

./index.vue:

import app from './app.ts';

console.log(app.test);
英文:

here is the way that should work.

./app/index.ts:

const app = {
    test: 1,
    // ...
};

export { app };

./app.ts:

import { app } from './app/index';

export default app;

./index.vue:

import app from './app.ts';

console.log(app.test);

答案2

得分: 1

只返回翻译好的部分:

对于import { test } from './app.ts'来工作,app.ts需要具有命名导出 test。而你的只有一个默认导出。

如果你不想显式导出对象的每个属性,我建议在index.vue中使用对象解构:

import app from './app.ts'
const {test} = app

console.log(test)

顺便说一下,如果你必须使用app.ts作为中间模块(无论出于什么原因),你可以重写它为:

export {default} from './app/index'
英文:

For import { test } from './app.ts' to work app.ts needs to have a named export test. Yours only has a default export.

If you don't want to explicitly export every property of the object I suggest to use object destructuring in index.vue:

import app from './app.ts'
const {test} = app

console.log(test)

FWIW, if you have to use app.ts as intermediate module (for whatever reason) you can rewrite it to

export {default} from './app/index'

huangapple
  • 本文由 发表于 2023年8月10日 15:40:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定