Webpack + Babel: ReferenceError: {My class} is not defined

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>

我试过了:

  1. <script> 标签中使用 {type="module"} 导入 webpack 包;
  2. 在“log4js.js”class定义中使用"export""export default"
  3. 在 html 文件的 <script> 标签中使用 "import" 语句;

如果你想从你的包中公开功能,那么你需要输出为一个库:

// 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