如何导入 webpack 子模块?

how to import a webpack submodule?

在我的设置中,我有一个 React 组件作为 npm 包的一部分,名为 'share-sheet'。它由 webpack 管理:

webpack.config.js

...
output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js'
},
entry: path.join(__dirname, 'src/index')
...

package.json

...
"main": "dist/bundle.js",
...

index.js

import FancyButton from 'components/FancyButton'
import FancyHellicopter from 'components/FancyHellicopter'

console.log(`my fancy button component: ${FancyButton}`)

module.exports = { FancyButton, FancyHellicopter }

另一方面,我有一个 webapp,它也使用 webpack,它是这样设置的:

app.js

import _ from 'lodash'
import sharesheet from 'share-sheet'
console.log(_) // outputs the lodash object correctly.
console.log(sharesheet) // outputs empty object.
console.log(sharesheet.FancyButton) // outputs undefined.

一旦我 运行 app.js,share-sheet 的 index.js 中的行就会在控制台中正确打印,但是一旦在 app.js 本身,sharesheet 是一个空对象。因此,一旦导入了 share-sheet 模块,在 module.exports 导出的对象就不会返回。究竟出了什么问题?

因为webpack不知道'share-sheet'包的导出策略。将 output.libraryTarget 配置为 commonjs2 应该可以解决问题。

webpack.config.js

...
output: {
  path: path.join(__dirname, '/dist'),
  filename: 'bundle.js',
  libraryTarget: 'commonjs2' // <----------
},
entry: path.join(__dirname, 'src/index')
...

您可以在 here 中找到有关使用 webpack 构建库的更多信息。