Do I need to add my server.js into my webpack file? - node.js

I have a node server with es6 syntax, like import statements, which it cannot recognize. I am pretty sure I would have to add that to my webpack file, but unsure on how to do that and whether it is required. My node server file is called server.js
var webpack = require('webpack');
module.exports = {
entry: {
app: './src/index.js',
vendor: './src/vendor.js'
},
output: {
path: __dirname,
publicPath: '/',
filename: '[name].js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor','vendor.js', Infinity)
],
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};

To use the import keyword in Node you have to transpile it so it either has to be processed by webpack if you use it or at least transpiled with a tool like Babel. See this for more info:
https://github.com/babel/babel-preset-env

Related

TreeShaking with RxJS 7.x and WebPack 5

I would like to treeshake rxjs in my TypeScript application that is bundled via WebPack:
rxjs#7.5.7
webpack#5.74.0
According to https://rxjs.dev/guide/installation I would have to use the ES2015 exports of rxjs, but I cannot find out how to do that.
Are you aware of an example or a link to some documentation?
My current webpack config is:
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'source-map',
target: 'node16',
mode: 'production',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
This config has successfully tree shaken the rxjs#6 version (which has the module entry point) but it fails to tree shake rxjs#7 and uses the full CJS version instead.
Thanks for any pointers!
Looks like this is a viable approach:
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'source-map',
target: 'node18.12',
mode: 'development',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
conditionNames: ['es2015', 'import'],
mainFields: ['es2015', 'module', 'main'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};

How do I ignore a an import in webpack?

I have a webpack file that looks like the one below, and I have a line in my handler.ts which looks like this:
import { PayoutEntity, IPayout, payoutEntityManager } from "/opt/nodejs/orm";
However I get the following error as the module/path for "/opt/nodejs/orm" doesn't exist locally:
Module not found: Error: Can't resolve '/opt/nodejs/orm'
The webpack build is for a lambda and the files for "/opt/nodejs/orm" are in a lambda layer that will only be accessable from the application once it's deployed to aws.
So in fact I would like webpack to ignore completely /opt/nodejs/orm and not even try to pack it.
I've tried using the ignore plugin with const ignore = new webpack.IgnorePlugin({resourceRegExp:/^(\/opt\/nodejs\/search|\/opt\/nodejs\/orm|\/opt\/nodejs\/put-event)$/}) but this just results in baking the "module not found" error into the bundled output file.
"use strict";
const path = require("path");
module.exports = {
devtool: "source-map",
entry: "./src/handler.ts",
mode: "production",
target: "node",
externals: [nodeExternals()],
node: {
__dirname: true,
},
output: {
filename: "index.js",
libraryTarget: "commonjs2",
path: path.resolve(__dirname, ".build"),
},
module: {
rules: [
{
test: /\.(graphql|gql)$/,
loader: "graphql-tag/loader",
exclude: /node_modules/,
},
{
test: /\.(tsx?)$/,
loader: "ts-loader",
exclude: [
[
path.resolve(__dirname, "node_modules"),
path.resolve(__dirname, ".serverless"),
path.resolve(__dirname, ".webpack")
],
],
options: {
transpileOnly: false,
experimentalWatchApi: true,
},
},
],
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
};

Typescript library build

I am new with webpack and I am currently trying to build my library which is similiar to LINQ, Java 8 Stream API #szilanor/stream for npm.
Here is my webpack.config.ts
import {Configuration} from 'webpack';
import TerserPlugin from 'terser-webpack-plugin';
import * as path from 'path';
const config: Configuration = {
mode: 'production',
devtool: 'source-map',
entry: './src/index.ts',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'build'),
library: 'Stream',
libraryTarget: 'umd',
clean: true,
},
optimization: {
minimize: true,
minimizer: [new TerserPlugin({extractComments: false})],
},
module: {
rules: [
{
test: /\.([mjt])s$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
},
},
],
},
resolve: {
extensions: ['.ts', '.js', '.json'],
},
};
export default config;
as it show I am trying to create an 'umd' bundle with babel and generate the type definitions with tsc.
So my question is that is gonna work in every situation whatever project I am trying to use it in (for example angular, react, node...)? If not can you help me to fix it?

Cannot find module "fs" - at webpackMissingModule

My server starts and runs correctly, but when I hit the URL in the browser it gives an error "cannot find module 'fs'".
I tried to setting:
target: 'node', but it starts another error
node: { fs: 'empty' }, but then it gives an error "cannot find exports"
"use strict";
const webpack = require('webpack');
const argv = require('minimist')(process.argv.slice(2));
const DEBUG = !argv.release;
const path = require('path');
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
names: ['common', 'vendors'],
filename: '[name].js',
minChunks: Infinity
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
"process.argv.verbose": !!DEBUG
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
jquery: "jquery"
})
].concat(DEBUG ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: true
}
}),
new webpack.optimize.AggressiveMergingPlugin()
]);
module.exports = {
entry: {
app: path.join(__dirname, '..', 'app', 'app.js'),
vendors: [
'react',
'react-dom',
'react-bootstrap',
'react-router',
'alt',
'lodash',
'superagent',
'react-router-role-authorization',
'react-validation-decorator'
]
},
output: {
publicPath: '/js/',
path: './wwwroot/js/',
filename: '[name].js',
chunkFilename: "[id].[name].js"
},
context: path.join(__dirname, '..'),
plugins: plugins,
cache: DEBUG,
debug: DEBUG,
watch: DEBUG,
stats: {
colors: true
},
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.(less|css)$/,
loaders: ["style", "css", "less"]
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|ttf|wav|mp3|mp4)$/,
loader: 'file-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
node: {
net: 'mock',
dns: 'mock'
}
};
It should not give this error and work correctly.
I don't see any mention of the fs module in your posted webpack setup. So, my guess is that your output application (app.js?) is trying to require and use fs. Webpack is building a client-side, front-end application, one that will be loaded in the browser; fs is not available in the browser.
(Double-check and make sure you aren't trying to, for example, read and write files on the user's machine using fs inside your client-side application. That is not possible in a browser-based application. For an intro to the concept of web applications with a front end and back end, check out the article React App With Node Backend.)

React + Webpack Dev Server: page is NOT interactive when visiting http://localhost:8080/webpack-dev-server/

When I visit http://localhost:8080, everything works as expected including hot reloading.
However, when I visit http://localhost:8080/webpack-dev-server/, nothing seems to work; can't type into the input components, can't scroll, etc.
It's almost like the page is frozen. This just started happening after a fresh npm install. It wasn't a problem previously.
Is anyone else experiencing this?
Here's my webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const PATHS = {
app: './src/index.js',
html: './src/index.html',
dist: path.join(__dirname, 'dist')
};
module.exports = {
entry: {
javascript: PATHS.app,
html: PATHS.html
},
output: {
path: PATHS.dist,
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
historyApiFallback: true,
contentBase: PATHS.dist
},
eslint: {
emitWarning: true
},
module: {
preLoaders: [
{
test: /\.(js|jsx)$/,
loaders: ["eslint-loader"],
exclude: /node_modules/
}
],
loaders: [
{
test: /\.html$/,
loader: "file?name=[name].[ext]"
},
{
test: /\.(js|jsx)/,
exclude: /node_modules/,
loaders: ["react-hot", "babel-loader"]
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};
Here's my file layout:
-dist
-node_modules
-src
- components
--index.js
--index.html
--webpack.config.js
try changing your public path like below
module.exports = {
entry: {
javascript: PATHS.app,
html: PATHS.html
'webpack/hot/dev-server', // For hot style updates
// The script refreshing the browser on none hot updates
'webpack-dev-server/client?http://localhost:8080',
},
output: {
path: PATHS.dist,
publicPath: '/webpack-dev-server/',
filename: 'bundle.js'
},

Resources