[英]Webpack + Babel: ReferenceError: {My class} is not defined
我是 Webpack 和 Babel 開發的新手。
我創建了一個 JS class 例如:
export default class Log4js {
#current_appender;
}
當我嘗試在 Firefox 瀏覽器控制台中創建我的 class 的 js 變量時,出現以下錯誤:
ReferenceError: Log4js is not defined [... ] <... > http://localhost:8080/:11
這是我的webpack.config.js
:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
//Webpack configuration
const webpack_config = {
//entrypoint
entry: './src/Log4js.js',
//Developemnt mode
mode: 'development',
//Path tu bundle
output: {
path: path.resolve(__dirname, './libs/bundle'),
filename: 'log4js.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
}
]
},
plugins: [],
};
//Export webpack config
module.exports = webpack_config;
我的"package.json"
文件:
{
"name": "webpack-babel-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/plugin-proposal-class-properties": "^7.10.4",
"path": "^0.12.7",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
},
"dependencies": {
"@babel/cli": "^7.10.5",
"@babel/core": "^7.10.5",
"@babel/preset-env": "^7.10.4",
"babel-loader": "^8.1.0"
}
}
還有我的".babelrc"
字段:
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
Firefox版本:77.0.1;
我的 html 代碼:
<!DOCTYPE html>
<html>
<head>
<title>Hello world!</title>
</head>
<body>
<script src="log4js.js" type="module"></script>
<script type="text/javascript">
var LOGGER = new log4js();
</script>
</body>
</html>
我試過了:
<script>
標記中導入帶有{type="module"}
的 webpack 捆綁包;"export"
和"export default"
;<script>
標簽中使用"import"
語句;如果要從捆綁包中公開功能,則需要將 output 作為庫:
// webpack.config.js
output: {
path: path.resolve(__dirname, './libs/bundle'),
filename: 'log4js.js'
library: 'Log4js' // <-- ADD THIS
},
然后,您應該能夠在其他腳本中引用Log4js
。
您可以在此處找到文檔以獲取更多選項:
https://webpack.js.org/configuration/output/#outputlibrary
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.