I am newbie in development with Webpack and Babel.
I created a JS class for example:
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:
ReferenceError: Log4js is not defined [... ] <... > http://localhost:8080/:11
This is my 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:
{
"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:
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
Firefox version: 77.0.1;
My html code:
<!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;"export"
and "export default"
in "log4js.js" class definition;"import"
statement in <script>
tag in html file;If you want to expose functionality from your bundle then you need to output as a library:
// 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.
You can fid the docs here for more options:
https://webpack.js.org/configuration/output/#outputlibrary
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.