[英]Webpack + Babel: ReferenceError: {My class} is not defined
I am newbie in development with Webpack and Babel.我是 Webpack 和 Babel 开发的新手。
I created a JS class for example:我创建了一个 JS class 例如:
export default class Log4js {
#current_appender;
}
When I try to create a js variable of my class in Firefox browser console, I got the following error:当我尝试在 Firefox 浏览器控制台中创建我的 class 的 js 变量时,出现以下错误:
ReferenceError: Log4js is not defined [... ] <... > http://localhost:8080/:11
This is my webpack.config.js
:这是我的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;
My "package.json"
file:我的"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"
}
}
And my ".babelrc"
field:还有我的".babelrc"
字段:
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
Firefox version: 77.0.1; Firefox版本:77.0.1;
My html code:我的 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>
I tried:我试过了:
{type="module"}
in <script>
tag;在<script>
标记中导入带有{type="module"}
的 webpack 捆绑包;"export"
and "export default"
in "log4js.js" class definition;在“log4js.js”class 定义中使用"export"
和"export default"
;"import"
statement in <script>
tag in html file;在 html 文件的<script>
标签中使用"import"
语句;If you want to expose functionality from your bundle then you need to output as a library:如果要从捆绑包中公开功能,则需要将 output 作为库:
// webpack.config.js
output: {
path: path.resolve(__dirname, './libs/bundle'),
filename: 'log4js.js'
library: 'Log4js' // <-- ADD THIS
},
You should then be able to reference Log4js
in other scripts.然后,您应该能够在其他脚本中引用Log4js
。
You can fid the docs here for more options:您可以在此处找到文档以获取更多选项:
https://webpack.js.org/configuration/output/#outputlibrary https://webpack.js.org/configuration/output/#outputlibrary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.