Javascript 浏览器看不到Web包导出的变量
这是我的包文件,我在这里包含了组件Javascript 浏览器看不到Web包导出的变量,javascript,webpack,Javascript,Webpack,这是我的包文件,我在这里包含了组件 import Container from './Components/Container/Container.component.js'; import Heading from './Components/Heading/Heading.component.js'; const Components = { Container: Container, Heading: Heading } module.exports = Component
import Container from './Components/Container/Container.component.js';
import Heading from './Components/Heading/Heading.component.js';
const Components = {
Container: Container,
Heading: Heading
}
module.exports = Components;
目标是使此组件变量在浏览器标记中可见。到目前为止,console.log(组件)
是未定义的
module.exports = {
entry: {
bundle: "./src/bundle.js"
},
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "bundle.js",
library: "Components",
libraryTarget: "var",
},
module:{
rules: [
{
test: /\.js$/,
exclude: path.resolve(__dirname, "node_modules"),
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}
]
},
target: "web"
}
这是我的网页配置文件。在我的webpack配置中,我该怎么做才能使组件在浏览器中可见,而无需将其指定给窗口对象。换句话说,让它成为全局的,并且能够通过webpack将它导入到其他js文件中。解决方案(据我所知,这里是一个副本,由@dreyescat回答)
1) 输出目标必须是库。所以webapck输出应该是
output: {
path: path.resolve(__dirname, "dist/js"),
filename: "Bundle_name",
library: "Library_name",
libraryTarget: "var" //See below
},
libraryTarget:“var”-(默认)加载库时,入口点的返回值将分配给变量-
对于希望执行相同操作的用户,请确保将varibale导出为
module.exports = your_variable;
所以出于某种原因,我把它都放在了我的文件里,但它不起作用,我使用了webpack——看。我在没有手表的情况下运行了webpack来编译它一次,它成功了。不知道为什么
它只是不能与webpack cli--watch一起工作,而webpack--watch完全没有问题如何渲染
和
呢?我还没有开始渲染。我想先把它出口。但是render是标准的,ReactDOM.render()
我刚刚运行了renderer,react抛出错误“预期的字符串或对象等…”。它是未定义的,那么我想这里有两个问题:1)包是否正确加载到您的站点上?2)如果1是真的,那么如果我在它工作的捆绑文件中运行console.log(Components),那么您的网页配置可能会有问题。但如果我从浏览器中的外部脚本调用它,它会说它未定义,我已经有了答案。/webpack将它放在名称空间中。所以问题是如何绑定浏览器中另一个脚本标记提供的全局变量