我有一个通过 webpack 捆绑的 Project1。我的要求是将此bundle.js放在CDN上,以便我可以在Project2中使用项目1中导出的模块。
项目 1 文件 ->
Hello.jsx:
import React, { Component } from "react";
export default class Hello extends Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
index.js:
export {Hello} from "./src/Hello.jsx";
<小时/>
我正在创建一个名为 bundle.js 的 bundle ,出于演示目的,我只是复制此 bundle.js(在相同的目录中),而不是将其添加到 CDN 中。文件夹(App.jsx)并在 Project2 中引用它。
项目 2 文件 ->
App.jsx:
import React, { Component } from "react";
import Hello from "./bundle.js";
export default class App extends Component {
render() {
return (
<Hello/>
);
}
}
index.js:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import App from "./src/App.jsx";
ReactDOM.render(
<App />,
document.getElementById("root2")
);
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>webpack 2 demo</title>
</head>
<body>
<div id="root2">
</div>
</body>
</html>
我尝试使用启用了 HMR 的 webpack-dev-server 来运行 Project2,但它在 Google Chrome 控制台中出现错误:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
- 软件包的当前版本:
"react": "^15.4.2" "webpack": "^2.2.1", "webpack-dev-server": "^2.4.2", "babel-core": "^6.24.0"
我是否以错误的方式进行导入?还是导出有问题?请帮忙。
编辑: 作为 Joe Clay suggested 为 Project1 添加 webpack.config.js :
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
libraryTarget: 'umd',
library: 'Hello'
},
devtool: 'eval-source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
React: 'react'
})
],
};
最佳答案
为了做到这一点,您需要更新您的 webpack 配置以输出可以导出的包。
您的配置需要包含这些行
{
output: {
libraryTarget: 'umd', // make the bundle export
externals: {
'react': { // import react from an external module so you don't have multiple instances
'commonjs': 'react',
'amd': 'react'
},
'react-dom': { // some versions of react had links to react-dom so its good to include this
'commonjs': 'react-dom',
'amd': 'react-dom'
}
}
}
}
需要注意的是,如果您在项目中使用 create-react-app,则需要弹出子项目来更改配置
关于reactjs - 如何导入在 webpack 中创建的包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42949247/