gpt4 book ai didi

reactjs - webpack umd lib 和外部文件

转载 作者:行者123 更新时间:2023-12-03 13:21:21 25 4
gpt4 key购买 nike

我想将我的 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需要设置不同的外部值(引用doc)。

因为我将外部react设置为{react: React},所以webpack会尝试查找名为React的包。

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

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

然后就修复了!

关于reactjs - webpack umd lib 和外部文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34252424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com