Unable to implement webpack in project with node-red - node.js

I am trying to implement webpack in my project which contains node-red. However, I keep getting the following warning. Please suggest how to solve this error -
WARNING in ./node_modules/node-red/red/runtime/storage/localfilesystem/projects/git/node-red-ask-pass.sh 1:26
Module parse failed: Unexpected token (1:26)
You may need an appropriate loader to handle this file type.
> "$NODE_RED_GIT_NODE_PATH" "$NODE_RED_GIT_ASKPASS_PATH" "$NODE_RED_GIT_SOCK_PATH" $#
|
# ./node_modules/node-red/red/runtime/storage sync ^\.\/.*$ ./localfilesystem/projects/git/node-red-ask-pass.sh
# ./node_modules/node-red/red/runtime/storage/index.js
# ./node_modules/node-red/red/runtime/index.js
# ./app.js
My webpack.config.js is -
const path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
target: 'node',
externals: [nodeExternals()],
entry: './app.js',
output: {
path: path.resolve(__dirname, './output'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js','.json', '.sh'],
modules: [
'node_modules'
],
},
module: {
rules: [
{
test:/\.css$/,
use:['style-loader','css-loader']
},
{
test: /\.coffee$/,
use: [ 'coffee-loader' ]
}
]
}
};

For Webpack, every file is a .js. In order to handle other extensions, like .css or .sh, you're supposed to use a loader, like you did with css-loader, that will tranform CSS rules into JS.
The issue you're facing is that you've got an import chain (./app.js -> .../index.js -> .../index.js -> .../node-red-ask-pass.sh), so Webpack will, at some point, will import a .sh file, but will throw an error because shell code is obviousouly invalid JavaScript. that is why you're seeing the error that you have.
By the way, I couldn't reproduce the issue you're facing:
npm init -y
npm i node-red
# ./node_modules/node-red/red is not a directory
So it was probably a node-red bug. Update the package to the latest version.

Related

How to: 1 Webpack for all project with importing lib from node_modules

// Project Tree View: My idea about using Webpack.
+ Toolkit:
- D:/Toolkit/Webpack/webpack.config.js
+ Project:
- D:/Project/A/build/index.ts
- D:/Project/B/build/index.ts
- D:/Project/C/build/index.ts
// Toolkit: [webpack.config.js] file
const path = require('path');
module.exports = (env) => {
let project_root = env.path;
console.log(env);
console.log(__dirname);
return {
mode: env.mode,
entry: project_root+'/build/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
include: [
path.resolve(project_root, 'build'),
path.resolve('./node_modules'),
]
}, {
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
}
]
},
output: {
publicPath: 'public',
filename: 'script.js',
path: path.resolve(project_root, 'assets/js')
},
resolve: {
modules: ['node_modules'],
},
}
}
Build command: yarn build --env=path=D:/Project/C
The command works without error, but when importing any library from the node_modules
Ex:
import {lib} from "example_lib";
import {lib} from "~example_lib";
import {lib} from "#example_lib";
import {lib} from "node_modules/example_lib";
import {lib} from "./node_modules/example_lib";
The Error
ERROR in ../A/build/index.ts 1:0-52
Module not found: Error: Can't resolve 'example_lib' in 'D:\Project\A'
resolve 'example_lib' in 'D:\Project\A'
Parsed request is a module
No description file found in D:\Project\A\build or above
resolve as module
D:\Project\A\build\node_modules doesn't exist or is not a directory
...
D:\node_modules doesn't exist or is not a directory
ERROR in D:\Project\A\build\index.ts
../A/build/index.ts 1:20-49
[tsl] ERROR in D:\Project\A\build\index.ts(1,21)
TS2792: Cannot find module 'example_lib'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?
webpack 5.26.2 compiled with 2 errors in 1939 ms
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
The Question is:
How to use ONLY 1 Webpack node_modules for all projects ?
Gulp can resolve this issue but how about Webpack ?
I do not want every project to have 1 node_modules or webpack, package,... inside (it trash my PC !)
The issue has been resolved !
The above code is correct.
Format ".js" works normally; however ".ts" need to add // #ts-ignore above every import external node_modules.
This is the answer !
// #ts-ignore
import {lib} from "example_lib";
NOTE: 7 days researching Webpack
This is my opinions:
Gulp is much more than Webpack even it has lower user
These are the Pros about Gulp that Webpack should have !
Less time for controlling the core.
User-friendly.
Clear and Clean Structure, less bracket.
Easy and Flexible for creating the custom config.
Easy to use, develop through time.
Not just for web field, on the backup data, auto,... as well.
1 node_modules for all external projects (Gulp less bug and coding line than Webpack).
Compile time are the same.
👉🏾 Gulp is the King 👑 !

Running webpack throws 'Callback was already called' error

I just started learning webpack to manage dependencies in my project. I am trying to use it to build bundles for my typescript and javascript files. For the typescript files, I am using the ts-loader plugin for handling it. For CSS, I am using the mini-css-extract and an optimize-css-assets plugin. When I try to run webpack, I get the following error and I am not able to figure out what might be causing this error.
user#system spl % npm run build
> spl#1.0.0 build /Users/user/Downloads/spl
> webpack --config webpack.config.js
/Users/user/Downloads/spl/node_modules/neo-async/async.js:16
throw new Error('Callback was already called.');
^
Error: Callback was already called.
at throwError (/Users/user/Downloads/spl/node_modules/neo-async/async.js:16:11)
at /Users/user/Downloads/spl/node_modules/neo-async/async.js:2818:7
at processTicksAndRejections (internal/process/task_queues.js:79:11)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! spl#1.0.0 build: `webpack --config webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the spl#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/user/.npm/_logs/2020-05-14T14_23_32_985Z-debug.log
The following is my webpack.config file that I am using to build my dist files.
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = {
mode: 'production',
entry: "./static/js/index.js",
output: {
filename: "bundle.[contentHash].js", // File name with hash, based on content
path: path.resolve(__dirname, 'dist')
},
optimization: {
minimizer: [
new OptimizeCssAssetsPlugin(),
new TerserPlugin(),
new HtmlWebpackPlugin({
template: "./static/index.html",
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true
}
})
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[contentHash].css"
}),
new CleanWebpackPlugin(),
],
module: {
rules: [
{
test: /\.html$/,
use: [ "html-loader" ]
},
{
test: /\.[tj]s$/,
use: "ts-loader",
exclude: /(node_modules|tests)/
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
}
],
},
resolve: {
alias: {
src: path.resolve(__dirname, 'src'),
static: path.resolve(__dirname, 'static'),
},
extensions: [ '.ts', '.js' ]
}
}
I had the same issue and I realized that I was importing CSS file from my index.html file:
<link rel="stylesheet" href="./css/main.css">
although the CSS file should have been imported from entry file (index.js) using import:
import '../css/main.css';
so I deleted the line <link rel="stylesheet" href="./css/main.css"> and solved the problem.
You can see your HTML file and check if there are any assets imported from your HTML file. I hope it helped.
tl;dr: Upgrading webpack to a newer version solved it for me.
I went into node_modules/neo-async/async.js and modified the onlyOnce so that it gives a bit more descriptive stack trace like this:
/**
* #private
* #param {Function} func
*/
function onlyOnce(func) {
const defined = new Error('onlyOnce first used here')
return function(err, res) {
var fn = func;
func = () => {
console.error(defined);
throwError();
};
fn(err, res);
};
}
The stack trace points into webpack’s internal code, which, when I upgraded to the latest version, solves this issue.
I ran into this issue and was able to determine that the cause was circular dependencies in Typescript, not outdated dependencies as suggested by other answers here. This error appeared when I refactored code from import MyClass from "folder/file" into import { MyClass } from "folder".
I only considered this possibility after reading this post about differences in semantics between export default and other types of exports.
I had this issue and it was related to a recent downgrade someone had made to mini-css-extract-plugin. We are using pnpm, so this answer is specific to that. I had to delete the pnpm-lock.yaml file in the module I was trying to run out of spring boot dashboard in VSCode. This file is generated if it is missing, but for us anyway, it was committed to the repo. If that doesn't work for you, you might also consider deleting the npm-cache and .pnpm-store dirs. The locations of those files are configured in the .npmrc file in your user's home directory.
For me, the issue came after upgrading css-loader. Downgrading it back to the original version did the trick for me
diff --git a/package.json b/package.json
index 7151c509..b0eba48b 100644
--- a/package.json
+++ b/package.json
## -111,7 +111,7 ##
"webpack-merge": "^4.1.3"
},
"devDependencies": {
- "css-loader": "^6.5.1",
+ "css-loader": "^1.0.0",

Node.js: How to import test files in custom test runner

I'm trying to create my own custom testing framework for learning purpose. Test files are written in following way
import { somemethod } from './some/module'
test(/I click on a button)/, () => {
browser.get("someSelector").should("have.text",somemethod());
});
I user require(file) to load test files. But it throw error SyntaxError: Unexpected token {
for import statement in test file. I'm using node js version 11.15.
If I switch to node v13.14 and define "type": "module" in my package.json then it doesn't let me use require(file) to load a test file or any module in my package.
How can I import tests files considering the user may be importing the modules using import or require?
This answer is very empirical...
Considering that it works using canonical commonjs approach you can try to debug it with newer version of NODE (currently I would use 14). For it, I would suggest you to use a node version manager like NVM so you can switch between node version easily and test that accordling seeing differences between various node installations.
Make a minimal project with npm init with a single dependency, save your index with the .mjs extension and try an import the above dependency. If you are be able to import that dependency with that minimal environment you can blame either your previous node or your configuration or both of them.
At the moment you should only create a small 2 files project to reproduce the problem. It seems your current node does not consider the "type": "module" configuration and runs everything in its classic way.
Regarding your comments....
As far as I know import can be used even in your code, not just at the beginning:
(async () => {
if (somethingIsTrue) {
// import module for side effects
await import('/modules/my-module.js');
}
})();
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Additionally you can try Webpack with a configuration like:
// webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'production',
target: 'node',
externals: [nodeExternals()],
entry: {
'build/output': './src/index.js'
},
output: {
path: __dirname,
filename: '[name].bundle.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: [
['env', {
'targets': {
'node': 'current'
}
}]
]
}
}
}]
}
};
With NodeExternals you don't put your node dependencies in the bundle but only your own code. You refer to node_modules for the rest. You might not want that.

Building ReactJS Project with Webpack causes graceful-js to report error "can't resolve 'fs'"

I was building my project last night. It's a Node project building React distributable frontend code with webpack. When I was done, I shut down my computer. I turned on my computer this morning and now, with no code or config changes to my knowledge, I get errors that some kind of dependency of a dependency is missing.
ERROR in ./~/fsevents/~/graceful-fs/fs.js
Module not found: Error: Can't resolve 'fs' in '/Users/stevenkitzes/Documents/Career Dev/C2 to A1/react-lnl/demo/react-lnl/node_modules/fsevents/node_modules/graceful-fs'
# ./~/fsevents/~/graceful-fs/fs.js 3:9-22
# ./~/fsevents/~/graceful-fs/graceful-fs.js
# ./~/fsevents/~/fstream/lib/reader.js
# ./~/fsevents/~/fstream/fstream.js
# ./~/fsevents/~/tar-pack/index.js
# ./~/fsevents/~/node-pre-gyp/lib/package.js
# ./~/fsevents/~/node-pre-gyp/lib ^\.\/.*$
# ./~/fsevents/~/node-pre-gyp/lib/node-pre-gyp.js
# ./~/fsevents/fsevents.js
# ./~/chokidar/lib/fsevents-handler.js
# ./~/chokidar/index.js
# ./~/watchpack/lib/DirectoryWatcher.js
# ./~/watchpack/lib/watcherManager.js
# ./~/watchpack/lib/watchpack.js
# (webpack)/lib/node/NodeWatchFileSystem.js
# (webpack)/lib ^.*$
# (webpack)/lib/webpack.js
# ./jsx-map/jsx-build.js
Here is my webpack config file:
var webpack = require('webpack');
var path = require('path');
var APP_DIR = path.resolve(__dirname, '.');
var plugins = [];
var config = {
entry: APP_DIR + '/jsx.js',
output: {
path: APP_DIR,
filename: 'jsx-out.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
exclude: /node_modules/,
include: APP_DIR,
loader: 'babel-loader',
query: {
presets: ['react']
}
}
]
},
plugins: plugins
};
module.exports = config;
It sounds like you may be trying to bundle both server-side (node) and client-side (react stuff) with webpack. If so you need to bundle them separately to create 2 different bundle files.
One for node for your to exeucte e.g., node bundle-server.js (assuming your server-side bundle is generated as 'bundle-server.js')
Another for inclusion into your front-end html code, e.g., <script src='./bundle-client.js'></script> (assuming your client-side bundle is generated as 'bundle-client.js').
Specifically you need to set options in your webpack config file to have two 'output' and two 'target', one for server-side, and another for client-side.
For details on doing client-side and server-side bundling with webpack, you can refer to https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-end-b95f1b429810

"You may need an appropriate loader for this file type", webpack can't parse angular2 file

I'm trying to get a very simple Angular2 app working, with Webpack as a module bundler. I'm following this code, and I copied all the configuration files as they are, only changing file paths. However, when I run npm-start, I get the following error, which I think is a Webpack error:
ERROR in ./hello.js
Module parse failed: /home/marieficid/Documentos/cloud/cloud/hello.js Line 1: Unexpected token
You may need an appropriate loader to handle this file type.
| import {bootstrap} from "angular2/platform/browser";
| import {Component} from "angular2/core";
|
# ./app.ts 2:0-21
As a result, the Angular2 code in my app isn't loaded.
This is my app.ts:
import "./hello.js";
This is hello.js, where the error seems to be (which I take to mean that webpack parsed app.ts just fine):
import {bootstrap} from "angular2/platform/browser";
import {Component} from "angular2/core";
#Component({
selector: 'app',
template: '<div>Hello world</div>'
})
class App{}
bootstrap(App);
And this iswebpack.config.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
module.exports = {
entry: {
'app': './app.ts',
'vendor': './vendor.ts'
},
output: {
path: "./dist",
filename: "bundle.js"
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
new HtmlWebpackPlugin({
inject: false,
template: './index.html'
})
],
resolve: {
extensions: ['', '.ts', '.js']
},
module: {
loaders: [
{ test: /\.ts$/, loader: 'ts-loader' },
],
noParse: [ path.join(__dirname, 'node_modules', 'angular2', 'bundles') ]
},
devServer: {
historyApiFallback: true
}
};
All these files and node_modules are in the same directory.
I have found similar questions online but nothing worked for me. I also didn't install babel because the sample code I'm using as base doesn't use it, but if it's necessary I'm will.
As suggested by #napstablook
Since in your webpack.config.js file you have
resolve: {
extensions: ['', '.ts', '.js']
},
Webpack will try to handle those .js files but it needs a specific loader to do so which is, if I'm not wrong, script-loader.
In your case the solution is as simple as deleting the .js files, or changing their extension to be .ts.
For me this issue occurred when I ran ng test,
please check below points,
Console will list out the files that is causing the error.
Check the html file is correctly mapped from the typescript.
styleUrls file should point to the CSS file not html, this is the mistake I
did.
this error also comes up for me in angular forms when i had patch value set then an extra = sign
ncont.controls[position].patchValue({[cardname]:file}) = file
which is a dumb part on me and angular for not telling me

Resources