【问题标题】:Webpack + Babel: ReferenceError: {My class} is not definedWebpack + Babel:ReferenceError:{My class} 未定义
【发布时间】:2020-11-07 00:06:02
【问题描述】:

我是 Webpack 和 Babel 开发的新手。

我创建了一个JS类例如:

export default class Log4js {

    #current_appender; 
}

当我尝试在 Firefox 浏览器控制台中创建我的类的 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"
    ]
}

火狐版本: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. &lt;script&gt; 标签中导入带有{type="module"} 的webpack 包;
  2. 在“log4js.js”类定义中使用"export""export default"
  3. 在html文件的&lt;script&gt;标签中使用"import"语句;

【问题讨论】:

    标签: javascript firefox webpack babeljs package.json


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我添加了 {library} 和 {libraryTarget} 属性并关闭了我的库。
    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多