【问题标题】:Basic implementation of using microbundle not working使用 microbundle 的基本实现不起作用
【发布时间】:2021-12-30 11:36:00
【问题描述】:

请参阅示例 repo 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”

【问题讨论】:

    标签: reactjs npm webpack pnpm microbundle


    【解决方案1】:

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

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

    你需要让webpack知道,除了你的项目的node_modules之外,它还需要在哪里搜索。

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

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

     resolve: {
        modules: ['node_modules', 'path/to/@mymicrobundle/example'],
      },
    

    【讨论】:

    • 谢谢。您对我的解决方案并不完全,但它引导我朝着正确的方向前进。这不起作用 - modules: ['node_modules', path.resolve(__dirname, '../mymicrobundle/dist')] 但这样做了: { alias: { '@mymicrobundle': path.resolve(__dirname, '. ./mymicrobundle/dist') },}
    • 我意识到 microbundle 的另一个问题是它不默认捆绑成 npm 格式 - 即常见的 js。我必须将格式实际设置为 --format cjs。立即更新 repo 以显示修复。
    • 我错了。我得到了它:模块:[path.resolve(__dirname, '../microbundle')],我只需要删除 dist。现在我不需要不必要的别名了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多