webpack umd lib 和外部文件

webpack umd lib and external files

我想将我的 React 组件打包为 umd 库。

下面是我的webpack设置:

module.exports = {
  devtool: 'eval',
  entry: [
    './lib/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'lib.js',
    library: 'lib',
    libraryTarget: 'umd'
  },
  resolve: {
    extensions: ['', '.js']
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
      }
    ]
  },
  externals: {
    "react": "React"
  }
}

然后在我以这种方式在我的其他组件中请求包之后

example.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {lib} from "../dist/lib";

以上组件的 webpack 设置为:

module.exports = {
  devtool: 'eval',
  entry: [
    './examples/example'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  resolve: {
    extensions: ['', '.js']
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel'],
        exclude: /node_modules/
      }
    ]
  }
}

编译example.js文件后,报错:

Line 3: Did you mean "react"?
  1 | (function webpackUniversalModuleDefinition(root, factory) {
  2 |   if(typeof exports === 'object' && typeof module === 'object')
> 3 |       module.exports = factory(require("React"));
    |                                    ^
  4 |   else if(typeof define === 'function' && define.amd)
  5 |       define(["React"], factory);
  6 |   else if(typeof exports === 'object')

我认为错误来自外部设置,因为在我删除 externals: {react: "React"} 后,它起作用了。

我搜索了一些相关答案,但无法修复。

有人知道吗?谢谢。

我找到答案了!

原因是umd需要设置不同的外部值(参考doc)。

因为我将外部反应设置为 {react: React},webpack 会尝试查找名为 React.

的包

所以你需要在不同的模块定义中设置不同的值。

externals: {
  "react": {
    root: 'React',
    commonjs2: 'react',
    commonjs: 'react',
    amd: 'react'
  }
}

然后修复!