[英]es6 - import all function from some js files without alias for create webpack bundle
[英]Webpack in ES6 create an empty bundle
我正在尝试在 ES6 中使用 webpack,但出了点问题,包已创建,但似乎什么也没有。
源代码/index.js
console.log("inside");
export const testData = 15;
webpack.prod.js
import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
export default {
entry: {
myApp: './src/index.js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Production',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(".", './dist'),
clean: true,
module: true,
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: "babel-loader",
include: path.resolve(".", "src")
}
]
},
mode: "production",
devtool: "source-map"
};
package.json
{
...
"scripts": {
"build": "webpack --config ./webpack.prod.js"
},
"devDependencies": {
"html-webpack-plugin": "5.5.0",
"path": "0.12.7",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-middleware": "5.3.1",
"webpack-dev-server": "4.8.1",
"webpack-merge": "^5.8.0",
"babel-core": "6.26.3",
"babel-loader": "8.2.5",
"babel-preset-es2015": "6.24.1"
},
"type": "module"
...
创建包后, dist
文件夹中的index.html
文件我插入了一个日志,但是当它启动时不显示日志并给我错误testData is not defined
分布/索引.html
...
<head>
<title>Production</title>
<script defer="defer" src="myApp.bundle.js"></script>
<script>
window.addEventListener("load", () => {
console.log( "window load" );
console.log( "testData" );
console.log( testData ); // <--------------------- it give the error
}, false)
</script>
</head>
...```
由于您要导出 const 值,因此会在构建和 webpack 优化过程中溶解。 最好将其作为某个模块的一部分并导出。 通过少量修改,您可以获得您期望的结果。
export default {
fuel: 100,
passengers: 7,
target: 'mars',
launch: function () {
console.log('Saturn VI ready to launch');
},
reportPorblem: function () {
return 'Houston, we have a problem';
},
land: function () {
console.log('Saturn VI landed successfully')
}
};
Remove module: true
from output,你可以在这里了解它是什么。
此外,您还需要对 webpack 中的 output 进行少量更改。删除libraryTarget
并将library
添加到 output。这里的库名称是MyLibrary
,您可以访问导出的详细信息。 Type 属性设置如何公开模块,webpack 允许您使用libraryTarget
或library.type
以特定标准公开您的模块。 这里它应该是var
。
output: {
...
library: {
name: 'MyLibrary',
type: 'var',
export: 'default',
},
},
webpack 支持的选项很少。
您可以在此处了解有关 libraryTarget 的更多信息
所以最后你可以从图书馆MyLibrary
访问你想要的一切。
<script>
window.addEventListener("load", () => {
const mySpaceShip = MyLibrary;
console.log(`Traveling to ${MyLibrary.target} with ${MyLibrary.crewmates} crewmates`)
}, false)
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.