1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

複数のファイルに分割されて定義された prototype の function をまとめて import する

Last updated at Posted at 2022-06-28

何がしたいか

JavaScript (ES6) で Obj.prototype.func = function(){} みたいな定義を、複数のファイルに分割して書いてあるときに、分割された Obj の定義をまとめて import します。

具体例:

bar.js
export function Foo(){
    console.log("foo");
}

Foo.prototype.bar = function()
{
    console.log("bar");
}
baz.js
Foo.prototype.baz = function()
{
    console.log("baz");
}

こんな二つのファイルがあるとき、

app.js
import { Foo } from './bar.js';
import { Foo } from './baz.js';

const foo = new Foo();
foo.bar();
foo.baz();

これで、出力が下記のようになってほしい。

foo
bar
baz

ちなみに、上の app.js は普通にエラーになります。(Foo が重複宣言されているということで)

結論

下記のいずれかで想定通りの結果になります。

解決法1

export {} を使う。

bar.js
export function Foo(){
    console.log("foo");
}

Foo.prototype.bar = function()
{
    console.log("bar");
}
baz.js
import { Foo } from './bar.js';

Foo.prototype.baz = function()
{
    console.log("baz");
}

export { Foo };
app.js
import { Foo } from './baz.js';

const foo = new Foo();
foo.bar();
foo.baz();

bar.jsbaz.js 経由で import します。

``bar.js` は下記のように書いてもOKです。

bar.js
function Foo(){
    console.log("foo");
}

Foo.prototype.bar = function()
{
    console.log("bar");
}

export { Foo };

解決法2

export default を使う。

bar.js
export function Foo(){
    console.log("foo");
}

Foo.prototype.bar = function()
{
    console.log("bar");
}
baz.js
import { Foo } from './bar.js';

Foo.prototype.baz = function()
{
    console.log("baz");
}

export default Foo;
app.js
import Foo from './baz.js';

const foo = new Foo();
foo.bar();
foo.baz();

node で実行する場合の注意

node で実行する場合は、下記のような package.json を作って、npm run start なり yarn start なりで実行する必要があります。node は v12 以上でないとダメかも。

package.json
{
    "type": "module",
    "scripts": {
        "dev": "node --experimental-modules app.js"
    }
}

実行結果:

$ npm run start

> start
> node --experimental-modules app.js

foo
bar
baz

おわり

prototype を使って書かれた古いコードをリファインしないといけない、みたいなときに使え・・・ますかね??

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?