I am using webpack
and webpack-dev-server
to run my react app. For some reason the require statement for the sweetalert2
package isn't working, and I get a TypeError when the application runs.
Here is the original code, before webpack:
const Swal = require('sweetalert2');
const alertToast = Swal.mixin({
toast : false
});
And the "after-webpack" code I can see in the browser when I try to chase the issue:
var Swal = __webpack_require__(/*! sweetalert2 */ "./node_modules/sweetalert2/src/sweetalert2.js");
var alertToast = Swal.mixin({
toast: false
});
Why is webpack having an issue resolving this module?
Here is my webpack config:
const HtmlWebPackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
// Config directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'build');
// Any directories you will be adding code/files into, need to be
// added to this array so webpack will pick them up
const defaultInclude = [SRC_DIR];
module.exports = {
context: __dirname,
entry : `${SRC_DIR}/index.js`,
output : {
path : OUTPUT_DIR,
publicPath: '/',
filename : 'bundle.js',
pathinfo : true
},
resolve: {
alias: {
src: path.join(__dirname, 'src')
}
},
devServer: {
historyApiFallback: true
},
module: {
rules: [
{
test: /\.(s*)css$/,
use : [
'style-loader',
'css-loader',
'sass-loader'
]
},
{
test : /\.js$/,
exclude: /node_modules(?!(\/|\\)js-utils)/,
loader : 'babel-loader'
},
{
test : /\.jsx$/,
exclude: /node_modules(?!(\/|\\)js-utils)/,
loader : 'babel-loader'
},
{
test : /\.(jpe?g|png|gif|JPG|webp)$/,
use : [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
},
{
test : /\.(eot|svg|ttf|woff|woff2)$/,
use : [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: path.resolve(__dirname, 'public/index.html'),
filename: 'index.html'
}),
new CopyWebpackPlugin([
{ from: 'public' }
])
],
target: 'node'
};
My .babelrc
{
"presets": [
[
"@babel/preset-env", {
"modules": false,
"targets": {
"browsers": [
"last 2 Chrome versions",
"last 2 Firefox versions",
"last 2 Safari versions",
"last 2 iOS versions",
"last 1 Android version",
"last 1 ChromeAndroid version",
"ie 11"
]
}
}
],
"@babel/preset-react"
],
"plugins": [ "@babel/plugin-proposal-class-properties" ]
}
And my file structure
And I am starting my app by running webpack-dev-server --mode=development
I fixed the issue by changing:
const Swal = require('sweetalert2')
to import Swal from 'sweetalert2';