1

请参阅示例回购 https://github.com/inspiraller/webpack-and-microbundle


微束码

mymicrobundle/src/index.js

import React from 'react'

const MyMicroBundle = ({session}) => {
  return (
    <div>Session = {session}</div>
  )
}

export default MyMicroBundle

microbundle/package.json - 用于输出

{
 ...
  "source": "src/index.js",
  "main": "dist/index.umd.js",
  "module": "dist/index.module.js",
  "exports": "dist/index.modern.js",
  "unpkg": "dist/index.umd.js"
}

导入微束代码

webpack-loads-microbundle/package.json

{
"dependencies": {
    "@mymicrobundle/example": "file:../mymicrobundle",
  }
}

webpack-load-microbundle/src/index.tsx

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import MyMicroBundle from '@mymicrobundle/example'

import './index.scss'

const App = () => {
  const [session, setSession] = useState('')
  return (
    <div>
      <h1>Hello</h1>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

注意:microbundle 包被捆绑为 javascript,但我使用 typescript 来导入它。虽然不应该有任何区别。我也在使用 pnpm 而不是 npm,但这应该没问题,因为所有其他导入都有效。

我的路径可能有问题。

错误

未找到模块:错误:无法解析“C:\baps\react_all\webpack-and-microbundle\webpack-loads-microbundle\src”中的“@mymicrobundle/example”

4

1 回答 1

1

webpack 默认从其解析模块process.cwd()/node_modules

因此,在您的情况下,它正在(当前工作目录)中寻找您的应用程序目录@mymicrobundle/examplewebpack-and-microbundle

除了webpack项目的node_modules.

这可以使用resolve.modules密钥来完成。请参阅文档:https ://webpack.js.org/configuration/resolve/#resolvemodules

所以你的 webpack 配置应该是这样的:

 resolve: {
    modules: ['node_modules', 'path/to/@mymicrobundle/example'],
  },
于 2021-11-19T18:24:53.397 回答