我刚刚开始使用Webpack和Babel来利用导出ES6的模块的优势。
我的构建设置生成了InventorySystem
中使用的build/main.build.js
,但浏览器控制台显示错误:index.html
我是新来的,我不确定问题出在哪里,是我的Uncaught ReferenceError: calculateInterest is not defined
或webpack.config.js
设置中,还是导出和导入模块中,还是编译时package.json
。
anybuddy可以帮助我正确设置此设置吗?这是构建文件。
package.json
build/main.build.js
Webpack.config.js
{
"name": "learn-webpack",
"version": "1.0.0",
"description": "A shot at learning WebPack",
"main": "index.html",
"scripts": {
"start": "http-server",
"webpack": "webpack"
},
"keywords": [
"webpack",
"learn-webpack"
],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^4.16.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"http-server": "^0.11.1",
"webpack": "^4.16.1",
"webpack-cli": "^3.1.0"
}
}
Index.html
const path = require('path')
module.exports = {
entry: './scripts/main.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'main.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
use: [{
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}]
}
]
},
optimization: {
minimize: false
},
mode: 'development',
stats: {
colors: true
}
};
脚本/main.js
<head>
<title>Babel Learning</title>
<link href="css/style.css" type="text/css" rel="stylesheet">
<script src="build/main.bundle.js" type="text/javascript"></script>
</head>
<body onload="init()">
<button id="btn">Calculate Interest</button>
<div id="result"></div>
<script>
function init() {
var btn = document.getElementById('btn')
var result = document.getElementById('result')
btn.addEventListener('click', function(){
var interest = calculateInterest(3000,29,1)
result.innerHTML = interest
})
}
</script>
</body>
</html>
scripts / js / getSI.js
import getSI from './js/getSI.js'
感谢您的帮助。非常感谢。
appu
答案 0 :(得分:0)
您可以从main.js
导出所需的功能:
import { calculateInterest } from './js/getSI.js';
export { calculateInterest };
并将您的webpack
输出设置更改为
output: {
path: path.resolve(__dirname, 'build'),
filename: 'main.bundle.js',
libraryTarget: 'this',
library: 'LearnWebpack'
},
这样做,您将在浏览器中获得LearnWebpack
<script>
function init() {
var btn = document.getElementById('btn')
var result = document.getElementById('result')
btn.addEventListener('click', function() {
var interest = LearnWebpack.calculateInterest(3000, 29, 1)
result.innerHTML = interest
})
}
</script>
Here,您可以找到有关webpack
的{{1}}可用设置的详细信息。据我所知,这些设置(library)是针对库的,但它应该可以使您的实验继续进行。
我在this older post中发现了类似的问题-想法相同,但所使用的设置适用于webpack @ 2(我认为) 希望对您有帮助