[英]Webpack: Trying to expose a bundled object to be usable by other scripts, object is still undefined
I'm trying to get just the basics down, transpiling a jsx file to js. 我正在尝试将基础知识简化下来,将jsx文件转换为js。 However, my transpiled code needs to be called by non-transpiled code. 但是,我的转译代码需要由非转译代码调用。 output.library is supposed to help with that. output.library应该可以帮助您。
In the resulting bundle I see a definition for var react. 在生成的包中,我看到了var react的定义。 But just after stepping through the entire bundle, it's clear react still isn't getting set. 但是就在逐步浏览整个捆绑包之后,很明显,仍然没有做出反应。
my webpack.config.js 我的webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: "./public/js/ui/react/dialog.jsx",
output: {
path: path.resolve(__dirname, "public/js/ui/react/"),
filename: "bundle.js",
libraryTarget: "var",
library: "react"
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: [
path.resolve(__dirname, "node_modules/")
],
query: {
presets: ['es2015', "react"]
}
}
]
},
node: {
fs: "empty"
}
}
and the jsx I am trying to transpile: 和我试图转换的jsx:
'use strict';
react.Dialog = class extends React.Component {
render() {
return (
<div class="bubble-speech">Hello World</div>
)
}
}
elsewhere in my code, AND BEFORE THE BUNDLE, I have this, so that the react.Dialog assignment is not a null reference error: 我在代码中的其他地方,以及在捆绑之前,都有这个,所以react.Dialog分配不是空引用错误:
var react = {};
If I take that one line away, the bundle.js will throw an error trying to assign react.Dialog. 如果我把那一行拿走,bundle.js将在尝试分配react.Dialog时抛出错误。 But if I leave it in, var react remains set to the empty object. 但是,如果我将其保留,则var react仍设置为空对象。 That seems like a contradiction! 这似乎是一个矛盾! What am I missing here? 我在这里想念什么?
I think react should be set as an externally defined global var, like this: 我认为应将react设置为外部定义的全局变量,如下所示:
{
output: {
// export itself to a global var
libraryTarget: "var",
// name of the global var: "Foo"
library: "Foo"
},
externals: {
// require("react") is external and available
// on the global var React
"react": "React"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.