How to configure webpack 5 to output ts files in dist folder from src folder? - node.js

I am using webpack 5 with typescript and a node.js app.
My folder structure is
src/
server.ts
mymodule.ts
public/
index.html
main.ts
utils.ts
but I want to output the compiled files as
dist/
server.js
mymodule.js
public/
index.html
bundle.js
This is my package.json
{
"name": "to-do",
"version": "1.0.0",
"description": "An application for to do list",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
"build": "webpack",
"serve": "webpack serve"
},
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"filenamify": "^5.1.1",
"html-webpack-plugin": "^5.5.0",
"http": "^0.0.1-security",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3"
},
"keywords": [
"todo"
],
"devDependencies": {
"#types/express": "^4.17.13",
"#types/node": "^18.0.6"
}
}
This is my webpack configuration
import path from 'path';
import { fileURLToPath } from 'url';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
entry: {
bundle : './src/public/main.ts'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
target:'node',
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/public/index.html',
scriptLoading:"module"
})
],
output: {
filename: '[name].js',
path: path.join(__dirname, 'dist'),
clean: true
},
mode: 'development',
devtool: 'inline-source-map',
devServer: {
hot: true,
static: {
directory: './dist',
},
compress: true,
port: 3002,
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin'
}
},
stats: {
errorDetails:true
}
};
I get an error about server.js can't be resolved, since I assume it looks at the main from package.json.
ERROR in ./src/public/main.ts 3:0-36
Module not found: Error: Can't resolve './server.js' in 'C:\Users\Desktop\4\src\public'
resolve './server.js' in 'C:\Users\Desktop\4\src\public'
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public)
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public/server.js)
no extension
How can I resolve this?

Related

Webpack can't find module css-loader (Error: Cannot find module '.../webpack_tutorial/node_modules/css-loader/dist/cjs.js')

I'm currently learning webpack with the following tutorial on YouTube: https://www.youtube.com/watch?v=MpGLUVbqoYQ&t=1337s&ab_channel=freeCodeCamp.org, i'm on minute 43.
I want that Webpack loads my css, but when I run "node start", and the error "Cannot find module css-loader" occurs, although I have it installed properly.
This is my webpack.config.js:
const path = require('path');
module.exports = {
mode: "development",
entry: "./src/index.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["css-loader"]
},
],
}
}
package.json:
{
"name": "webpack_tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --config webpack.config.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"webpack": "^5.9.0",
"webpack-cli": "^4.2.0"
},
"devDependencies": {
"css-loader": "^5.0.1",
"style-loader": "^2.0.0"
}
}
index.js:
import { run } from "./app/app";
import "./main.css";
import { AlertService } from "./app/alert.service";
import { ComponentService } from "./app/component.service";
const alertService = new AlertService();
const componentService = new ComponentService();
run(alertService, componentService);
Folder structure:
dist
node_modules
src
app
some other files...
index.js
main.css
package.json
webpack.config.js
Has anyone an idea why webpack is not finding this package?

Entry module not found

ERROR in Error: Child compilation failed:
Entry module not found: Error: Can't resolve '/Users/MarkPierre/Desktop/es6-project-2019/src/index.html' in '/Users/MarkPierre/Desktop/es6-project-2019':
Error: Can't resolve '/Users/MarkPierre/Desktop/es6-project-2019/src/index.html' in '/Users/MarkPierre/Desktop/es6-project-2019'
When I run the command npm run start, I get the error message mentioned above.
I've checked the path and it's there. Any ideas?
Seems like the issue occurs with template: './starter/src/index.html'. I've removed the starter, but still the same issue. Very frustrating as this is the final part of the config :-(
babelrc file
{
"presets": [
["#babel/preset-env", {
"targets": {
"browsers": [
"last 5 versions",
"ie >= 8"
]
}
}]
]
}
package.json
{
"name": "forkify",
"version": "1.0.0",
"description": "forkify project",
"main": "index.js",
"scripts": {
"dev": "webpack: --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.2.3",
"babel-loader": "^8.0.5",
"html-webpack-plugin": "^3.2.0",
"webpack-dev-server": "^3.1.14"
},
"dependencies": {
"#babel/polyfill": "^7.2.5"
}
}
webpack
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['#babel/polyfill', './starter/src/js/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js',
},
devServer: {
contentBase: './dist'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
})
],
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}]
}
};

Webpack has been initialised using a configuration object that does not match the API schema. webpack install by "npm install webpack"

I am learning on React-JS. I have written a simple project. But getting an error when I run "npm start" command.
My Webpack.config.js file is given below--
var webpack= require("webpack");
var path =require("path");
var DIST_DIR= path.resolve(__dirname,
"dist");
var SRC_DIR= path.resolve(__dirname,
"src");
var config={
entry: SRC_DIR + "/app/index.js",
output:{
path: DIST_DIR + "/app",
file: "bundle.js",
publicPath: "/app/"
},
module:{
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query:{
presets: ["react",
"es2015", "stage-2"]
}
}
]
}
};
module.exports=config;
package.json file --
{
"name": "basic-reactjs",
"version": "1.0.0",
"description": "Some Basic ReactJS",
"main": "index.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && cp
src/index.html dist/index.html
&& webpack-dev-server --content-
base src/ --inline --hot",
"build:prod": "webpack -p && cp
src/index.html dist/index.html"
},
"keywords": [
"reactjs"
],
"author": "Numery Zaber",
"license": "MIT",
"dependencies": {
"react": "^16.6.3",
"react-dom": "^16.6.3"
},
"devDependencies": {
"babel-loader": "^8.0.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"webpack": "^4.26.0",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
}
Webpack install by the follwoing command
npm install webpack webpack-dev-server babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-2 --save-dev
Please help me to solve the issue.
The schema in Webpack 4 is now changed.You have imported the loaders which was working in older version of webpack.
For more details : https://webpack.js.org/concepts/loaders/
var webpack= require("webpack");
var path =require("path");
var DIST_DIR= path.resolve(__dirname,
"dist");
var SRC_DIR= path.resolve(__dirname,
"src");
var config={
entry: SRC_DIR + "/app/index.js",
output:{
path: DIST_DIR + "/app",
filename: "bundle.js",
publicPath: "/app/"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ["react","es2015", "stage-2"],
},
}
}
]
}
};
module.exports=config;
You can also use #babel/preset-env.

Ignoring node_modules for compiling server-side ES6 with Webpack locally

I am working with a Raspberry Pi Zero that is my server, running my module.
Raspberry's are not the best to compile code so I want to compile the server-side code locally. To do so I need to compile the code without resolving my imports. Why that ?
Because the Server module uses other modules that can only be installed on the Raspberry (such as UPM or MRAA for sensors).
For now I compile on the Pi but it's slow.
So I'm trying to compile to ES6 locally with my config:
const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry:
{
index: __dirname + "/src/index.js"
},
output: {
// sourceMapFilename: "[name].map",
path: path.resolve(__dirname, "build"),
filename: "[name].js",
sourceMapFilename: "[name].map",
chunkFilename: "[id].chunk.js"
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
presets: ["env"],
plugins: [
["transform-runtime"],
["transform-es2015-modules-commonjs-simple", { // Very important
"noMangle": true
}]
]
}
}
}
]
},
plugins: [
new webpack.ProvidePlugin({Hardlets: path.resolve(__dirname, "../Hardlets/build/index")}),
new webpack.IgnorePlugin(new RegExp("/(node_modules)/"))
// new webpack.optimize.UglifyJsPlugin(),
// new HtmlWebpackPlugin({template: "./src/index.html"})
],
target: "node",
externals: [nodeExternals()],
devtool: "source-map"
};
Which gives me an error because only the devDependencies are installed locally but not the other dependencies (sensors...):
ERROR in ./src/hardlets/relays/Relays.js Module not found: Error:
Can't resolve 'jsupm_relay' in
'/home/stinky/Projects/gardener/Sensors/src/hardlets/relays' #
./src/hardlets/relays/Relays.js 1:1008-1030 #
./src/HardletInstances.js # ./src/index.js
ERROR in ./src/hardlets/dht22/DHT22.js Module not found: Error: Can't
resolve 'rpi-dht-sensor' in
'/home/stinky/Projects/gardener/Sensors/src/hardlets/dht22' #
./src/hardlets/dht22/DHT22.js 1:925-950 # ./src/HardletInstances.js
# ./src/index.js
How can I prevent webpack from trying to resolve/import these dependencies ? The dependencies must be resolved at runtime.
There is my package.json:
{
"name": "gardener",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "http://192.168.8.100:3000/pi/Gardener.git"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-runtime": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-plugin-transform-es2015-modules-commonjs-simple": "^6.7.4",
"webpack": "^3.8.1",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"upm": "^1.0.0",
"rpio": "^0.9.19",
"rpi-dht-sensor": "^0.1.1"
}
}
The modules could not be excluded with nodeExternals() because it lists the modules in /node_modules/. However, the modules that are to be excluded are not installed locally so nodeExternals() does not do the job.
It needs to exclude them from by reading package.json.
This will read the modules from the package.json file & exclude them instead of the node_modules directory:
// webpack.config.js
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
externals: [nodeExternals({
modulesFromFile: true
})], // in order to ignore all modules in package.json when bundling
...
};

Error: Cannot find module "." mongodb with webpack and typescript

I have a problem when I can use mongoose with webpack. I already installed it as a dependency but when I want to use the mongoose object and execute it it commands me that it can not find the "." Module. And that seems very strange, I've been looking for a good time, I installed the dependencies again, delete the npm cache, reinstall webpack
I would appreciate your support, thank you very much
webpack.config.js
var path = require("path");
var typescriptLoader = {
test: /\.ts$/,
loader: 'ts-loader'
};
module.exports = {
entry: "./src/main.ts",
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
publicPath: "dist/",
filename: "main.js"
},
node: {
__filename: true,
__dirname: true
},
watch: true,
devServer: {
contentBase: path.join(__dirname, "public_html"),
watchContentBase: true
},
module: {
rules: [ typescriptLoader ]
},
resolve: {
extensions: [ '.js', '.ts' ]
},
externals: {
}
}
package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --config webpack.config.js -p",
"start": "node dist/main.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"karma": "^1.5.0",
"ts-loader": "^2.0.1",
"typescript": "^2.2.1",
"webpack": "^2.2.1"
},
"dependencies": {
"#types/core-js": "^0.9.39",
"#types/helmet": "0.0.34",
"#types/mongoose": "^4.7.10",
"#types/node": "^7.0.11",
"body-parser": "^1.17.1",
"cheerio": "^0.22.0",
"express": "^4.15.2",
"helmet": "^3.5.0",
"mongoose": "^4.9.4",
}
}
index.ts
import * as mongoose from 'mongoose'; // ALL OK
console.log(mongoose); // Error when is used
Error
var n;n="undefined"==typeof window?!function(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}():r(204),/*!
^
Error: Cannot find module "."
Your mongoose is npm module. TypeScript may not recognized the way you import it. try the nodejs require module loading system.
var mongoose = require('mongoose');
or
const mongoose = require('mongoose');

Resources