webpack umd lib 和外部文件 [英] webpack umd lib and external files

查看:56
本文介绍了webpack umd lib 和外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to package my react component as a umd lib.

下面是我的 webpack 设置:

below is webpack my setting:

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"
  }
}

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

And then after I require the package in my other component in this way

example.js

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

以上组件的 webpack 设置是:

And above component's webpack setting is :

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文件后,显示错误:

After I compile the example.js file, it shows the error:

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"} 后,它起作用了.

I think the error is from the externals setting, cause after I remove externals: {react: "React"}, it works.

我搜索了一些相关的答案,但无法解决.

I search some related answers but can't fix it.

有人知道这个吗?谢谢.

Does anyone have any idea of this? thanks.

推荐答案

我找到了答案!

原因是umd需要设置不同的外部值(参考文档).

The reason is umd need to set the different external value (reference doc).

因为我将外部 react 设置为 {react: React},webpack 会尝试找到一个名为 React 的包.

Because I set the external react as {react: React}, webpack would try to find a package named React.

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

So you need to set the different value in different module definition.

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

然后修复!

这篇关于webpack umd lib 和外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆