I have a problem with dynamic require js files after webpack bundling.
Environment:
webpack, ts-loader, typescript.
src/index.ts:
require(path.resolve(__dirname, './test.js'));
dist/test.js:
console.log('I should be printed after require # index');
I don't know why but webpack think that there is no file:
1) Warning while running webpack -p
WARNING in ./src/index.ts
5:0-43 Critical dependency: the request of a dependency is an expression
# ./src/index.ts
2) Error while running script:
Error: Cannot find module "C:\Users\user\path\to\dist\test.js".
3) My webpack config is:
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: {
index: "./src/index.ts"
},
output: {
filename: "[name].js"
},
target: "node",
externals: [ nodeExternals() ],
node: {
"__dirname": false
},
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
module: {
rules: [
{ test: /\.tsx?$/, loader: "ts-loader" }
]
}
}
Expected:
NodeJS just dynamically require path while index.js script execution.
Please help to setup that properly.
Thanks!
Problem solved using __non_webpack_require__ function.
Related
I have two HTML pages, each will include it's own bundle. Here is my project structure:
public/
-- dist/
src/
-- firebase/
-- network/
webpack.config.js
Here's my webpack config:
const path = require('path');
const CleanTerminalPlugin = require('clean-terminal-webpack-plugin');
module.exports = {
mode: "development",
entry: {
network: path.resolve(__dirname, 'src') + '/network/index.ts',
firebase: path.resolve(__dirname, 'src') + '/firebase/index.ts'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
path: path.resolve(__dirname, 'public') + '/dist',
},
plugins: [new CleanTerminalPlugin()]
};
I expect this to create two bundles in public/dist with the names firebase.js and network.js. Instead I get an error:
ERROR in main Module not found: Error: Can't resolve './src/' in 'path/to/project/root'
It also says Field 'browser' doesn't contain a valid alias configuration /path/to/project/root/src/index doesn't exist
And repeats that for .tsx, .ts and .js
I don't know why it's looking for an index.* file in my src/. I didn't specify that as an entry file. If I create a src/index.ts it builds, but only makes one bundle called main which is not my expected behavior.
It ended up being a really stupid issue, but I'll post the answer in case someone needs it.
I was invoking webpack with webpack ./src but webpack without the ./src worked as expected.
I want to create a JavaScript function with which I can specify a path to a folder and load each of the files in that folder into PixiJS, without having to know the name and extension of each of those files. It seems like the fs module in Node.js is the thing to use here.
When I use import * as fs from 'fs'; at the top of my game.ts file, I get this error:
ERROR in ./src/my-subproject/game.ts
Module not found: Error: Can't resolve 'fs' in 'C:\Users\me\WebDev\MyProject\src\my-subproject'
# ./src/my-subproject/game.ts 33:24-37
# multi ./src/my-subproject/game.ts
This thread seems possibly relevant to my situation. It says it won't work because it's "web and not a local file system." What does this mean? If I really can't access my asset files for whatever reason, how is PixiJS able to load them when I give it the file paths?
If that's not the problem, I think it might be an issue with my Webpack. I've seen many different suggestions for modifying my Webpack online and none of them worked for me. For instance,
https://www.freecodecamp.org/news/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8/
https://github.com/pugjs/pug-loader/issues/8
Module not found: Error: Can't resolve 'fs' when using readFileSync
This is my complete webpack.config.js file:
const path = require('path');
module.exports = {
mode: "development",
entry: [
path.resolve('src/my-subproject', 'game.ts')
],
output: {
path: path.resolve('dist'),
filename: 'game-bundle.js'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: '/node_modules/',
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
useBuiltIns: 'usage',
targets: {
"chrome": "61",
}
}]
]
}
},
],
},
resolve: {
extensions: [ '.txs', '.ts', '.js'],
modules: [
path.resolve('src'),
'node_modules'
]
},
devtool: 'inline-source-map',
devServer: {
port: 8000,
open: true,
contentBase: path.resolve('dist'),
watchContentBase: true
}
};
If I do need to add something to webpack.config.js, could you specify where exactly I should put it? Most sources are unclear about that. Thanks!
I am trying to bundle one of our microservices which is using MQTT.js and I am struggling with really strange issue.
It is working fine without bundling, so ws is available in node_modules.
Stuff which I think matters:
error:
TypeError: WS is not a constructor
at WebSocketStream (dist/index.js:159329:16)
at createWebSocket (dist/index.js:147450:10)
at Object.buildBuilderBrowser (dist/index.js:147476:10)
at MqttClient.wrapper [as streamBuilder] (dist/index.js:147937:36)
at MqttClient._setupStream (dist/index.js:146471:22)
at new MqttClient (dist/index.js:146452:8)
at Function.connect (dist/index.js:147940:10)
webpack config:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const { NODE_ENV = 'production' } = process.env;
module.exports = {
entry: { index: './src/index.ts' },
mode: NODE_ENV,
target: 'node',
watch: NODE_ENV === 'development',
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
resolve: {
extensions: ['.ts', '.js'],
},
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.ts$/,
use: [{ loader: 'ts-loader', options: { transpileOnly: true } }],
},
{
test: /(\.md|\.map)$/,
loader: 'null-loader',
},
],
},
};
Function where it happens:
createMqttClient(): MqttClient {
return mqtt.connect(this.mqttOptions.url, { ...this.mqttOptions.options });
}
The url is like: ssl://url-to-our-mqtt
Can anybody help please?
I also ran into same issue.
The problem for me was that I used
plugins: [
new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
],
in webpack.config.js order to fix the shebang error that comes with mqtt.js since it is a CLI tool.
Then instead I have used
{
test: [
/node_modules[/\\]mqtt[/\\]mqtt.js/,
/node_modules[/\\]mqtt[/\\]bin[/\\]sub.js/,
/node_modules[/\\]mqtt[/\\]bin[/\\]pub.js/,
],
loader: 'shebang-loader'
},
And my problem was fixed. Do you also use mqtt/dist/mqtt.js instead of mqtt in your imports or if you do something similar to mine, the shebang-loader rule I have posted above might solve your problem.
I experienced the same with Amazon aws-iot-device-sdk-js and Microsoft azure-iot-device-mqtt which both include mqtt.
The initial issue is the build error:
ERROR in ./node_modules/mqtt/mqtt.js Module parse failed: Unexpected character '#' (1:0)
This error is caused by the package mqtt. Three files (mqtt.js, pub.js and sub.js) contain a shebang line
#!/usr/bin/env node
The solution using module replacement suggested some places
plugins: [
new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
],
unfortunately changes the build error with the run time error
TypeError: WS is not a constructor
As mentioned in other answers, webpack can be configured (https://webpack.js.org/concepts/loaders/) to use the shebang loader (https://www.npmjs.com/package/shebang-loader)
TL;DR
Install shebang-loader
npm install shebang-loader --save
In webpack.config.js use the loader
module.exports = {
...
module: {
rules: [
{
test:
[
/.*mqtt\.js$/,
/.*sub\.js$/,
/.*pub\.js$/
],
use: 'shebang-loader'
}
]
}
}
When I want to create my bundle.js with:
$ ./node_modules/.bin/webpack --config webpack.config.js
I get the following error
ERROR in ./dev/js/source/scripts/components/TextInput.js Module not
found: Error: Cannot resolve module
'source/scripts/components/IconButton' in
/Users/sebastien/Documents/Javascript/Tests/MyApp/dev/js/source/scripts/components
# ./dev/js/source/scripts/components/TextInput.js 4:18-65
ERROR in ./dev/js/source/scripts/components/TextInput.js Module not
found: Error: Cannot resolve module 'source/scripts/SDK/classNames' in
/Users/sebastien/Documents/Javascript/Tests/MyApp/dev/js/source/scripts/components
# ./dev/js/source/scripts/components/TextInput.js 15:17-57
The project tree is the following
/Users/sebastien/Documents/Javascript/Tests/MyApp
- webpack.config.js
- dev
- js
- index.js
- source
- scripts
- components
- TextInput.js
- IconButton.js
- SDK
- classNames.js
In TextInput.js there's the following statement
import IconButton from "source/scripts/components/IconButton";
and my webpack.config.js contains the following
var path = require('path');
var webpack = require('webpack');
module.exports = {
devServer: {
inline: true,
contentBase: './src',
port: 8080
},
devtool: 'cheap-module-eval-source-map',
entry: './dev/js/index.js',
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!sass-loader'
}
]
},
output: {
path: 'src',
filename: 'js/bundle.min.js'
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin()
]
};
How can I configure webpack to add the path ./dev/js to search for modules? I have tried with:
- modules: [path.resolve(__dirname, "./dev/js"), "node_modules"]
without any success. Can you help?
Regards,
Try
import IconButton from "./source/scripts/components/IconButton";
and see if that helps.
or
import IconButton from "../source/scripts/components/IconButton";
but the first one should probably work. Give it a try.
I have a project like this:
root/
webpack-config.js
app/
app.js
js/
dep.js
core/
module.js
Here is the webpack config file:
module.exports = {
entry: './app/app.js',
output: {
path: __dirname,
filename: "[name]-bundle.js"
},
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
resolve: {
modulesDirectories: ['core']
}
...
in app.js, I have:
import local_dep from './js/dep';
import myModule from 'module';
This works as expected with webpack 1.x, but the myModule module isn't resolved with webpack 2, I'm getting "Module not found: can't resolve 'module' in ... \app".
It seems the modulesDirectories entry is ignored and the base URL corresponds to the entry's folder.
What can I do to make modules resolve correctly with webpack 2 ?
from: http://moduscreate.com/webpack-2-tree-shaking-configuration/
In Webpack 2, resolvers from root, modulesDirectories, and fallback settings will merge into a single property – modules. Here is how we can resolve file and module locations in Webpack 2:
resolve: {
modules: [
path.resolve('./client'),
'node_modules'
]
},
You can specify a number of directories in modules, but make sure not to forget node_modules or npm package dependencies will fail to load.
So in your case what was before:
resolve: {
modulesDirectories: ['core']
}
now needs to be
resolve: {
modules: ['core'] // also 'node_modules'
}
Edit: As others have noted, for Webpack 2, something like this works:
{
resolve: {
extensions: ['.js', '.jsx'],
modules: ['node_modules', path.resolve(__dirname, 'core')]
},
}
For Webpack 1, I have a setup that has this entry:
config.resolve = {
// Allows us to include js and jsx files without specifying the extension
extensions: ['', '.jsx', '.js'],
root: [path.resolve('./core')]
};
Thanks to Christopher Davies I fixed the problem by adding:
resolveLoader: {
root: path.join(__dirname, 'node_modules')
},
resolve: {
root: ['./core']
}
I had to add resolveLoader line otherwise I was getting an error about babel-loader that could not be loaded.