Node - Fails to run Webpack bundles - javascript

I'm bundling my app using webpack and I'm making sure to specify the target to "node" (otherwise the webpack build fails).
With my current configuration the build is successful, but when I try to run it using node I'm getting an error:
C:\Users\myuser\Desktop\myproject\dist\app.js:20 /******/
modules[moduleId].call(module.exports, module, module.exports,
webpack_require);
^
TypeError: Cannot read property 'call' of undefined
It refers to a line inside of the webpackBootstrap function injected into the beginning of app.js. It feels as though node is not compatible with Webpack, even though from what I understood it should be.
I doubt it's relevant to the issue, but in order for you to have the full picture:
I'm transpiling ts and having each file from src exported as a separate chunk into dist instead of bundling everything together, in order to dynamically import files on demand at runtime.
For instance:
src/app.ts
src/compA.ts
src/compB.ts
will become:
dist/app.js
dist/compA.js
dist/compB.js
Here's my webpack.config.js:
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const { CheckerPlugin } = require('awesome-typescript-loader');
const glob = require('glob');
let entry = {};
glob.sync('./src/**/*.*').forEach(component => {
let name = component.match(/.*\/(.*)\..*/)[1];
entry[name] = component;
});
module.exports = {
mode: 'development',
entry,
target: 'node',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(['dist']),
new CheckerPlugin()
],
output: {
filename: (chunkData) => {
let name = chunkData.chunk.name;
let src = chunkData.chunk.entryModule.id;
let path = src.split('/');
let dir = path[path.length -2];
let pathPrefix = dir !== 'src' ? dir + '/' : '';
return pathPrefix + name + '.js';
},
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
optimization: {
splitChunks: {
chunks: 'all'
},
},
};

I needed to include node externals in the config.
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
target: "node",
entry: {
app: ["./back.js"]
},
output: {
path: path.resolve(__dirname, "../build"),
filename: "bundle-back.js"
},
externals: [nodeExternals()],
};
https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-end-b95f1b429810

Related

Webpack bundle behaviour different from 5.21.0 and 5.22.0

I am doing some upgrades to node a package which uses webpack. The package used to use webpack 5.9 for generating a small bundle, then using eval() was extracting some js code.
This is the webpack conf:
function getBaseWebpackConfig() {
return {
context: path.resolve(__dirname, '../'),
mode: 'development',
entry: "./test/input/icon.js",
devtool: false,
output: {
path: outputDir,
filename: bundleFileName,
publicPath: '',
library: {
type: 'commonjs2',
}
},
module: {
rules: [
{
test: /\.svg/,
exclude: /node_modules/,
loader: svg-loader,
options: {}
}
]
}
}
}
Now, moving to 5.73.0, this behaviour has changed; tests stopped running. After doing some debug, I have found the following.
With webpack < 5.21.2 the bundle starts as:
module.exports =
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
With webpack > 5.22.0 the bundle starts as:
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
Essentially, it does not have a top module.exports anymore and this breaks the rest of the code.
I could not find any reason this. The changelog does not give me any clue. Might it be a bug?
I'm not a webpack expert. But, comparing yours with my webpack configs I created recently (using the latest webpack for a PWA app). My settings are inside a module.exports. Maybe that's why module.exports is not in your bundle. e.g.
module.exports = {
context: path.resolve(__dirname, '../'),
mode: 'development',
entry: "./test/input/icon.js",
devtool: false,
output: {
path: outputDir,
filename: bundleFileName,
publicPath: '',
library: {
type: 'commonjs2',
}
},
module: {
rules: [
{
test: /\.svg/,
exclude: /node_modules/,
loader: svg-loader,
options: {}
}
]
}
}
}
Plus I've got three webpack config files common,dev and prod and use merge to combine them.
e.g. my webpack.dev.js
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
const path = require('path');
module.exports = merge(common, {
mode: 'development',
devtool: 'inline-source-map',
output: {
filename: "[name].bundle.js",
},
module: {
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css"
}),
new ForkTsCheckerNotifierWebpackPlugin(),
]
});

Compiling a typescript project with webpack

I have a question for you - how is it possible to implement multi-file compilation while preserving the tree of folders and documents, while not writing each file into entry in this way
entry: {
index:'./src/index.ts',
'bot/main':'./src/bot/main.ts'
}
But at the same time, the files had their names and their position, as before compilation in js, only instead of the src folder, they were in the dist folder?
My current config webpack.config.js
const path = require('path')
const nodeExternals = require('webpack-node-externals')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
module.exports = {
context: __dirname,
entry: {
index:'./src/index.ts',
'bot/main':'./src/bot/main.ts'
},
externals: [nodeExternals()],
module: {
rules: [
{
exclude: /node_modules/,
test: /.ts$/,
use: {
loader: 'ts-loader'
}
}
]
},
node: {
__dirname: false
},
resolve: {
extensions: ['.ts', '.js'],
plugins: [
new TsconfigPathsPlugin({
baseUrl: './src'
})
]
},
output: {
filename: '[name]js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/'
},
target: 'node'
}
And when building in production mode, all this was compiled into one file, taking into account all URLs, imports, etc.
Is it even possible?
Webpack itself won't do that for you. You will need to write litter helper function to achieve this. The basic idea is to crawl the directory, find all the files and then provide them to Webpack:
const path = require('path');
const glob = require('glob');
const extension = 'ts';
// Recursively find all the `.ts` files inside src folder.
const matchedFiles = glob.sync(`./src/**/*.${extension}`, {
nodir: true
});
const entry = {};
matchedFiles.forEach((file) => {
const SRC_FOLDER = path.join(__dirname, 'src');
const ABS_PATH = path.join(__dirname, file);
// Generates relative file paths like `src/test/file.ts`
const relativeFile = path.relative(SRC_FOLDER, ABS_PATH);
// fileKey is relative filename without extension.
// E.g. `src/test/file.ts` becomes `src/test/file`
const fileKey = path.join(path.dirname(relativeFile), path.basename(relativeFile, extension));
entry[fileKey] = relativeFile;
});
module.exports = {
context: __dirname,
// Use the entry object generated above.
entry,
// ... rest of the configuration
};

after upgrade to Webpack 5 not able to access the menifest in copy-webpack-plugin

My config was working fine in webpack version 4.6.0 and webpack-assets-manifest version 3.1.1
since I upgraded to webpack 5 and webpack-assets-manifest to 5. I'm not getting value in my manifestObject it's just empty object
I suspect this is happening because transform function running before manifest is created
looked into the new documentation of webpack-assets-manifest but could not get it working
my goal is to access manifest value in transform function, but it looks like transform function is running before manifest is generated
var CopyWebpackPlugin = require('copy-webpack-plugin');
var SaveHashes = require('webpack-assets-manifest');
const manifest = new SaveHashes({
entrypoints: true,
entrypointsKey: 'entryPoints'
});
module.exports = {
entry: {
main: ['./src/apps/main'],
games: ['./src/apps/games'],
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: assetsUrl,
filename: 'assets/javascript/[name].[contenthash].js',
chunkFilename: 'assets/javascript/[name].[contenthash].js'
},
.
.
.
.
.
plugins: [
new CleanWebpackPlugin(),
manifest,
new CopyWebpackPlugin([
{
from: './views/**/*',
to: path.join(__dirname, 'dist'),
transform(content, path) {
// I want to access manifest here
// so that I can inject the final script(javascript bundle with content hash)
// in my view template
const manifestObject = JSON.parse(manifest);
}
}
])
]
};
you need to export it like this
const ManifestPlugin = require("webpack-manifest-plugin").WebpackManifestPlugin;
.....
new ManifestPlugin({
fileName: "asset-manifest.json",
publicPath: paths.publicUrlOrPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[ file.name ] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
(fileName) => !fileName.endsWith(".map")
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
and it will work WebpackManifestPlugin is what you need

Webpack watch is failing me

EDIT: It's now resolved. Got in to work this morning and thought "have you tried turning it on and off again?". So I did. Removed node_modules, reinstalled all packages - it worked. FML.
I'm upgrading to Webpack 4 and can't seem to get the watch to work.
When I run the watch script everything runs as expected the first time, but errors out during a file update.
The scripts I try:
"dev": "cross-env ENV=dev webpack --config config/bundling/webpack.config.js --mode=development",
"watch": "cross-env WATCH=true yarn run dev --watch"
(redundancies in the cross-env variables will be fixed later)
The errors I get are the following:
"WARNING in configuration
The 'mode' option has not been set, webpack will fallback to
'production' for this value. Set 'mode' option to 'development' or
'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior.
Learn more: https://webpack.js.org/concepts/mode/"
"ERROR in multi (webpack)-dev-server/client?http://localhost:8080 ./src
Module not found: Error: Can't resolve './src' in [MY PATH HERE]
# multi (webpack)-dev-server/client?http://localhost:8080 ./src main[1]"
It seems like it doesn't read my webpack.config.js or the mode variable the on watch? Also, it succeeds in building the bundle, leading me to thing this might be an issue solely with the built-in webpack-dev-server.
I've tried everything I can think of, changing the scripts, changing the syntax of the mode flag, setting mode in webpack.config.js, tried relative paths, tried absolute paths, tried different versions of webpack and webpack-dev-server, moved my config file to the project root, sacrificed a small CPU to the Gods of code - nothing works.
I've been at this for days without any progress. Any help would be appreciated.
Versions:
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
Config:
require('dotenv').config()
const CopyWebpackPlugin = require('copy-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const moduleRules = require('./module.rules')
const config = require('./editable.config')
module.exports = function() {
const isDev = !!(process.env.ENV === 'dev')
const isProd = !!(process.env.ENV === 'prod')
const doServe = !!(process.env.SERVE === 'true')
const doWatch = !!(process.env.WATCH === 'true')
const webpackConfig = {
// Set mode
mode: isProd ? 'production' : 'development',
// Entry points.
entry: config.entrypoints,
// JS output name and destination.
output: {
path: config.paths.public,
filename: config.outputs.javascript.filename
},
// External dependencies.
externals: config.externals,
// Custom resolutions.
resolve: config.resolve,
// Rules for handling filetypes.
module: {
rules: [
moduleRules.javascript,
moduleRules.sass,
moduleRules.fonts,
moduleRules.images,
]
},
// Plugins running in every build.
plugins: [
new FriendlyErrorsWebpackPlugin(),
new MiniCssExtractPlugin(config.outputs.css),
new CleanWebpackPlugin(config.paths.public, { root: config.paths.root }),
new CopyWebpackPlugin([{
context: config.paths.images,
from: {
glob: `${config.paths.images}/**/*`,
flatten: false,
dot: false
},
to: config.outputs.image.filename,
}]),
new CopyWebpackPlugin([{
context: config.paths.fonts,
from: {
glob: `${config.paths.fonts}/**/*`,
flatten: false,
dot: false
},
to: config.outputs.font.filename,
}]),
],
devtool: isDev ? config.settings.sourceMaps : false,
watch: doWatch
}
// Set BrowserSync settings if serving
if (doServe) {
// setting our default settings...
const browserSyncSettings = {
host: 'localhost',
port: 3000,
proxy: process.env.HOME,
files: [
{
match: ['../../**/*.php'],
fn: function (event, file) {
if (event === 'change') {
this.reload()
}
}
}
]
}
// ...and overwriting them with user settings
Object.assign(browserSyncSettings, config.settings.browserSync)
webpackConfig.plugins.push(new BrowserSyncPlugin(browserSyncSettings))
}
return webpackConfig;
}
Config, part 2
const path = require('path')
module.exports = {
paths: {
root: path.resolve(__dirname, '../../'),
public: path.resolve(__dirname, '../../public'),
src: path.resolve(__dirname, '../../src'),
javascript: path.resolve(__dirname, '../../src/js'),
sass: path.resolve(__dirname, '../../src/sass'),
fonts: path.resolve(__dirname, '../../src/fonts'),
images: path.resolve(__dirname, '../../src/images'),
relative: '../../',
external: /node_modules/
},
entrypoints: {
main: ['./src/js/app.js', './src/sass/style.scss']
},
outputs: {
javascript: { filename: 'js/[name].js' },
css: { filename: 'css/[name].css' },
font: { filename: 'fonts/[path][name].[ext]' },
image: { filename: 'images/[path][name].[ext]' }
},
externals: {
},
resolve: {
},
settings: {
sourceMaps: 'cheap-module-source-map',
autoprefixer: {
browsers: ['last 3 versions', '> 1%', 'ie >= 10'],
},
browserSync: {
host: 'localhost',
port: 3000
}
}
}
Bonus question: is it possible to watch without having Webpack 4 start up a new devServer?
Thanks! <3

Require is not defined on reflect-metadata - __webpack_require__ issue

I'm trying to launch my angular app on visual studio but when it starts, it stucks on "Loading..." section.
If i read Chrome's error console i get the following error:
Uncaught ReferenceError: require is not defined at Object. < anonymous > __ webpack_require __
The reflect-metadata contains the following: module.exports = require("reflect-metadata"); , which "require" causes the error.
Here's some of my code...
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: { modules: false },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '#ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};
Searching on the internet, all of the troubleshooting suggests doing something on the systemjs.config file but mine is not an angular-cli app so I can't do it.
UPDATES SECTION
UPDATE #1
Looks like the problem is caused by webpack-node-externals executed in browser mode.
Got to find another way for that.
Got any troubleshooting or potential solution suggestion?
Thanks in advance!
UPDATE #2
I've made it, see my answer below
GOT IT!
The issue was caused by webpack-node-externals used on my common configuration.
See my question and my answer to my own question at the following: Webpack - Excluding node_modules with also keep a separated browser and server management for more details.
So, in a nutshell, the steps that I followed are these:
Installing requireJS ==> http://requirejs.org/docs/node.html
Removing externals: [nodeExternals()], // in order to ignore all modules in node_modules folder from my common webpack configuration and adding it under my server configuration (done before my question, but it's a really important step) [see webpack.config.js content in the question linked right above in this answer or in the snippet below]
Adding target: 'node', before my externals point above, under my server side section (done before my question, but it's a really important step) [see webpack.config.js content in the question linked right above in this answer or in the snippet below]
This makes sure that browser side keeps target:'web' (default target), and target becomes node just for the server.
launched webpack config vendor command manually from powershell webpack --config webpack.config.vendor.js
launched webpack config command manually from powershell webpack --config webpack.config.js
That worked for me! Hope It will works also for anyone else reading this question and encountering this issue!
webpack.config.js content:
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
var nodeExternals = require('webpack-node-externals');
module.exports = (env) => {
// Configuration in common to both client-side and server-side bundles
const isDevBuild = !(env && env.prod);
const sharedConfig = {
//removed from here, moved below.
//externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
stats: { modules: false },
context: __dirname,
resolve: { extensions: [ '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '#ngtools/webpack' },
{ test: /\.html$/, use: 'html-loader?minimize=false' },
{ test: /\.css$/, use: [ 'to-string-loader', 'style-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
};
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig, {
entry: { 'main-client': './ClientApp/boot.browser.ts' },
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.browser.module#AppModule'),
exclude: ['./**/*.server.ts']
})
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
const serverBundleConfig = merge(sharedConfig, {
resolve: { mainFields: ['main'] },
entry: { 'main-server': './ClientApp/boot.server.ts' },
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./ClientApp/dist/vendor-manifest.json'),
sourceType: 'commonjs2',
name: './vendor'
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new AotPlugin({
tsConfigPath: './tsconfig.json',
entryModule: path.join(__dirname, 'ClientApp/app/app.server.module#AppModule'),
exclude: ['./**/*.browser.ts']
})
]),
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
//added target and externals HERE, in order to prevent webpack to read node_modules
//this also prevents fake-positives parsing errors
target: 'node',
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder,
devtool: 'inline-source-map'
});
return [clientBundleConfig, serverBundleConfig];
};

Categories

Resources