我想将我的react组件打包为umd
lib.
下面是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
需要设置不同的外部值(参考文档).
因为我将外部反应设置为{react: React}
,webpack会尝试找到一个名为的包React
.
因此,您需要在不同的模块定义中设置不同的值.
externals: { "react": { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }
然后它修复!