Critical dependency: require function is used in a way in which dependencies cannot be statically extracted - NodeJS, Express & Webpack - node.js

I am developing a web application using Node.js, Express & Webpack. Everything was going well until Webpack was upgraded to Webpack 5 and lots of bugs appeared. I have managed to solve all the errors but there is a warning I can't solve. I have seen this post but it's related to Angular so I don't think it helps me much: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
WARNING in ./node_modules/terser-webpack-plugin/dist/minify.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
This is my webpack.config.js; resolve fields and node-polyfill-webpack-plugin are used to solve Webpack 5 bugs and errors.
const path = require("path")
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
module.exports = {
resolve:{
fallback: {
"fs": false,
"path": false,
"worker_threads":false,
"child_process":false,
"http": false,
"https": false,
"stream": false,
"crypto": false,
}
},
entry: {
main: './src/js/main.js',
index:'./src/js/'
},
output: {
path: path.join(__dirname, 'dist'),
//publicPath: '/',
filename: '[name].js'
},
mode:"development",
target: 'web',
devtool: 'source-map',
module: {
rules: [
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
test: /\.bpmn$/,
use: 'raw-loader'
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.html$/,
use: [
{
loader: "html-loader",
//options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/index.ejs',
filename: "./index.ejs",
excludeChunks: [ 'server', 'main' ]
}),
new HtmlWebPackPlugin({
template: '!!raw-loader!./src/views/pages/bmv.ejs',
filename: "./bmv.ejs",
excludeChunks: [ 'server', 'index' ]
}),
new webpack.NoEmitOnErrorsPlugin(),
new NodePolyfillPlugin()
]
}

configure the webpack:
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
'terser-webpack-plugin': path.resolve(__dirname, 'node_modules/terser-webpack-plugin/dist/minify.js'),
},
},
};

Related

asset_url_for() returns None in flask cookie cutter (flask-webpack)

Im new to webpack. Im using flask-cookie-cutter which in turn uses Flask-Webpack
Im having issues in that App wont find my images in development.
Images are in assets/img folder
Ive tried using {{ asset_url_for('img/img_name.png') }} and various variations of it - and it just returns none.
Ive tried the usual flask way of {{ url_for('static', filename='img/img_name.png') }}
But I cant seem to access them.
const path = require('path');
const webpack = require('webpack');
/*
* Webpack Plugins
*/
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://0.0.0.0:2992' : '';
const rootAssetPath = path.join(__dirname, 'assets');
module.exports = {
// configuration
context: __dirname,
entry: {
main_js: './assets/js/main',
main_css: [
path.join(__dirname, 'node_modules', 'materialize-css', 'dist', 'css', 'materialize.css'),
path.join(__dirname, 'assets', 'css', 'style.css'),
],
},
output: {
path: path.join(__dirname, 'dsi_website', 'static', 'build'),
publicPath: `${publicHost}/static/build/`,
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].js',
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
devtool: 'source-map',
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' },
},
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader!less-loader',
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader',
],
},
{
test: /\.html$/,
loader: 'raw-loader'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i,
loader: `file-loader?context=${rootAssetPath}&name=[path][name].[hash].[ext]`
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env'],
cacheDirectory: true
}
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[hash].css', }),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new ManifestRevisionPlugin(path.join(__dirname, 'dsi_website', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
]),
};
I was the same problem with flask-cookie-cutter and solve it by update/upgrade npm and add extensionsRegex: /\.(jpe?g|png|gif|svg)$/i at down file: webpack.config.js like this:
ManifestRevisionPlugin(path.join(__dirname, '<your app>', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
extensionsRegex: /\.(jpe?g|png|gif|svg)$/i
}),
source solution. Proper call to show image in temaplate:
{{ asset_url_for('img/img_name.png') }}
after that i check startup screen and i see that all my images load properly
[WEBPACK] _/assets/img/image_name.20aed528d50316c91ffedb5ba47b8c74.jpg 18.9 KiB [emitted]

Migrating from Grunt+Bower to Webpack

I am trying to migrate away from Bower+Grunt to Webpack (and eventually to YARN instead of Bower).
However, any documentation I have come across for WebPack3 doesn't even talk about handling bower components.
WebPack 2 used a plugin for Bower, however the same isn't supported for WebPack 3.
Here's my WebPack config:
const webpack = require('webpack');
const path = require('path');
const frontEndConfig = {
entry: {
client: './client/app/app.js'
},
output: {
path: path.resolve(__dirname, 'dist/client/'),
filename: '[name].app.js'
},
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
]
},
resolve: {
modules: ['bower_components'],
descriptionFiles: ['bower.json'],
}
};
const backEndConfig = {
entry: {
client: './server/app.js'
},
output: {
path: path.resolve(__dirname, 'dist/server/'),
filename: 'app.js'
},
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
}
],
rules: [{
exclude: ['node_modules']
}]
},
resolve: {
modules: ['node_modules'],
descriptionFiles: ['package.json'],
}
};
module.exports = [
frontEndConfig,
backEndConfig
];;
The whole idea is to first run using webpack and then move completely to YARN.
They say plugins have been stopped for WebPack3, so what's the workaround for this?

Webpack build fail when adding a specific external lib

It happens on a build for server side, i am already using a lot of external modules and everything worked great until now.
I am trying to add the module auth0-js and the error happens when i add the import on this lib var crypto = require('crypto'); TypeError: require is not a function.
Here is my webpack config (for server side):
const path = require('path');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
module.exports = {
entry: './handler.js',
target: 'node',
profile: false,
output: {
path: path.resolve(__dirname, '../dist-server'),
publicPath: '/',
filename: 'handler.js',
libraryTarget: 'commonjs'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, '..'),
use: 'babel-loader'
},
{
test: /\.pug$/,
use: 'pug-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
__CLIENT__: false,
__SERVER__: true
}),
new StatsPlugin('stats.json', {
chunkModules: true,
exclude: [/node_modules[\\\/]react/]
})
],
resolve: {
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
devtool: 'source-map'
};
My .babelrc file is:
{
"presets": [
"react",
"latest"
],
"plugins": [
"transform-object-rest-spread",
"transform-runtime"
]
}
I tried to remove the exclude node_modules but i get other errors.
I am curious to know how a single library can break everything, what should i do?

TypeScript typings broken (error TS2687): All declarations of 'iterator' must have identical modifiers

I'm having an issue getting my typings correctly after I've added the router package to my Angular application (which required an upgrade of Core, Common, Compiler etc.).
Googling ob that specific error code led me to a number of problems, the main resolution for which is removing node_modules and typings and recreating them. I've done so but experience the same misbehavior.
On SO, there's another question but it's old, relates to a different versions of most of the packages and I hardly see how it relates to my problem.
Frankly, I'm a bit lost because I have no idea how to troubleshoot it at all. Below is my tsconfig.json if it helps to spot something odd.
edit
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const distribution = path.resolve(__dirname, "distribution");
const application = path.resolve(__dirname, "source/application");
const resources = path.resolve(__dirname, "source/resources");
module.exports = {
entry: "./source/application/main.ts",
output: {
path: distribution,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.png$/, loader: "raw-loader", include: [resources] },
{ test: /\.s(a|c)ss$/, loaders: ["raw-loader", "sass-loader"] },
{ test: /\.html$/, loader: "raw-loader", include: [application] },
{ test: /\.ts$/, loader: "ts-loader", include: [application] },
]
},
resolve: {
modules: ["node_modules", application],
extensions: [".js", ".ts"]
},
performance: {},
devtool: "source-map",
context: __dirname,
target: "web",
externals: [],
stats: {},
devServer: {
contentBase: distribution,
port: 3002
},
plugins: [
new HtmlWebpackPlugin({ template: "./source/index.html" }),
new CopyWebpackPlugin([{ from: "./source/resources", to: "resources" }])
]
}
In Webpack.common.js remove the line debug=true, and change the below code
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['*', '.js', '.ts']
},
module: {
rules: [
]},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),

karma Uncaught SyntaxError: Unexpected token export

I use karma + jasmine to write test cases for vue and webpack, and it once worked. But after I upgrade vue for 1 to 2, and update vue-loader accordingly, it starts to give error.
Now when I run karma start karma.config.js, it give me error like:
Chrome 53.0.2785 (Windows 7 0.0.0) ERROR
Uncaught SyntaxError: Unexpected token export
at test/index.js:8995
My karma.config.js is:
var webpackConf = require('./webpack.config.js')
delete webpackConf.entry
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine'],
reporters: ['progress', 'html'],
htmlReporter: {
outputFile: 'tests/unit-test.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// this is the entry file for all our tests.
files: [
{pattern: './test/index.js', watched: false},
],
// we will pass the entry file to webpack for bundling.
preprocessors: {
'./test/index.js': ['webpack']
},
// use the webpack config
webpack: webpackConf,
// avoid walls of useless text
webpackMiddleware: {
noInfo: true
},
singleRun: true,
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-webpack',
'karma-htmlfile-reporter'
]
})
}
My webpack.config.js is:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: ['webpack-hot-middleware/client','./index.js'],
output: {
path: path.resolve(__dirname, '../output/static'),
publicPath: '/',
//filename: '[name].[hash].js'
filename: 'main.js'
//chunkFilename: '[id].[chunkhash].js'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
},
extensions: ['', '.js', '.vue']
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel?presets=es2015',
exclude: /node_modules/
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'index.html'),
inject: true
})
]
}
Looks like the es6 export syntax is not translated correctly. Also, I did not know where to take a look at the test/index.js:8995 because this is auto generated by webpack. The real index.js is quite simple, just 2 lines:
var testsContext = require.context('.', true, /\.spec\.js$/)
testsContext.keys().forEach(testsContext)
How to debug this and what can I do to solve the problem?

Resources