首页 > 解决方案 > Webpack 生成的库在 useBuiltIns 设置为“usage”的项目导入时出现问题

问题描述

我想写一个可重用的 UI 组件库并用 Webpack 打包。但是,当我在另一个项目中导入它时,babelrc 已useBuiltIns: 'usage'设置,导入将失败并出现错误:

"export 'default' (imported as 'Component') was not found in 'component'

这是我在库项目中的 webpack 配置的一部分:

output: {
  path: path.resolve(process.cwd(), './dist'),
  filename: 'component.js',
  chunkFilename: '[id].js',
  library: 'Component',
  libraryTarget: 'commonjs2',
  libraryExport: 'default'
},

...

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader'
    },

库项目中的 Babel 配置:

module.exports = {
  presets: [
    [
      "env",
      {
        modules: false,
        targets: {
          "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
        }
      }
    ],
    "stage-2"
  ]
}

消费项目中的 Babel 配置:

module.exports = {
  presets: [
    '@vue/app'
  ]
}

useBuiltIns: 'usage'式设置的位置。

而问题可以通过集合useBuiltIns: falsescriptType: 'unambiguous'消费项目来解决。但这不是我想要的。由于我的目标是提供一个可重用的库,并且预计会在不同的项目中使用。我不能强迫所有的消费项目都这样做。

我在这里错过了什么吗?

标签: javascriptvue.jswebpackbabeljs

解决方案


我在 Vue.js 论坛中找到了答案:https ://forum.vuejs.org/t/export-default-imported-as-components-was-not-found-in-mylib/63905

问题是我正在使用本地路径添加依赖项,即:

$ npm install ../component

在这种情况下,npm 在node_modules. 似乎某些 babel 插件并不真正喜欢符号链接。

在我更改为使用 git 之后:

$ npm install git+file://localhost/path/to/component

一切正常。


推荐阅读