简体   繁体   English

如何正确导出/导入模块以在JavaScript中使用库

[英]How to properly export/import modules for library usage in javascript

I want to write a javascript library with two files: 我想编写一个包含两个文件的JavaScript库:

snabbpixi.js

export function init() {
}

pixiapi.js

export function createElement() {
}

I want to use this library like this: 我想像这样使用这个库:

import { init } from 'snabbpixi';
import { createElement } from 'snabbpixi/pixiapi';

If I don't do anything and set the package.json for library as: 如果我什么也不做,请将库的package.json设置为:

{
  "main": "src/snabbpixi.js"
}

second import doesn't work ( import { createElement } from 'snabbpixi/pixiap' ) 第二次导入不起作用( import { createElement } from 'snabbpixi/pixiap'

If I compile this library and export as umd format using webpack it also doesn't work. 如果我编译该库并使用webpack导出为umd格式,则它也将不起作用。

How can I configure my library so I can import like this: 如何配置我的库,以便可以像这样导入:

import { createElement } from 'snabbpixi/pixiap'

I normally do this sort of thing in TypeScript rather than straight JavaScript, but hopefully this works in basically the same way... 我通常在TypeScript中执行这种操作,而不是直接在JavaScript中执行,但希望它的工作方式基本上相同...

Try creating a new file (typically named index.js ), with contents like this: 尝试创建一个新文件(通常名为index.js ),其内容如下:

export * from './snabbpixi'; // Adjust paths as needed for your particular case.
export * from './snabbpixi/pixiapi';

Then make index.js your main . 然后将index.js main

The import you would use would then be flattened-out, however, looking more like: 然后,您将使用的导入将被展平,但是看起来更像:

import { init, createElement } from 'snabbpixi';

When you are using import { Something } from 'somewhere' you are calling on a named export from a given file or directory. import { Something } from 'somewhere'使用import { Something } from 'somewhere'您正在调用给定文件或目录中的命名导出。

If the two files are in different directories then you can add an index.js file to each directory and then use export { default as function } from './file' To do this you would have to export the default file from pixiapi and snabbpixi . 如果两个文件位于不同目录中,则可以将index.js文件添加到每个目录中,然后使用export { default as function } from './file'为此,您必须从pixiapisnabbpixi导出默认文件。

If you have both files importing into your index.js then you will still want to export them as defaults. 如果您都将两个文件都导入到index.js则仍将它们导出为默认文件。 But then you would do the following.. 但随后您将执行以下操作。

import file1 from './file1'
import file2 from './file2'

export default {
file1,
file2,
}

This will allow you to use the named imports as well and keep them in the same directory 这也将允许您使用命名的导入并将它们保留在同一目录中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM