I'm trying to build a simply application using the MEAN stack, and I'm running into an issue with Webpack. When I run "webpack" from the console, I get the following warnings and errors:
WARNING in ./~/require_optional/package.json
Module parse failed: C:\Build\myapp\node_modules\require_optional\package.json Unexpected token (2:9)
You may need an appropriate loader to handle this file type.
WARNING in ./~/require_optional/README.md
Module parse failed: C:\Build\myapp\node_modules\require_optional\README.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
WARNING in ./~/require_optional/LICENSE
Module parse failed: C:\Build\myapp\node_modules\require_optional\LICENSE Unexpected token (1:40)
You may need an appropriate loader to handle this file type.
ERROR in ./~/constants-browserify/constants.json
Module parse failed: C:\Build\myapp\node_modules\constants-browserify\constants.json Unexpected token (2:12)
You may need an appropriate loader to handle this file type.
So my questions are:
1. Should Webpack even be trying to load files like README.md and LICENSE? Why would it care about those?
2. I have a json-loader hooked up and looking for .json files, so why am I still getting warnings and errors about those?
Here's my Webpack config file:
webpack.config.js
var config = require('./environment/shared.js')
var debug = config.env !== 'production';
var webpack = require('webpack');
module.exports = {
context: __dirname,
devtool: debug ? 'inline-sourcemap' : null,
entry: './public/js/app.js',
output: {
path: __dirname + '/public/js',
filename: 'bundle.min.js',
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
module: {
loaders: [
{
test: '/\.json/',
loader: 'json',
},
{
test: '/\.node$/',
loader: 'node-loader',
},
],
},
resolve: {
extensions: ['', '.js', '.json', '.node'],
},
};
question 1:
I think there is something like following in your codebase. namely, require a module whose name is in a variable. In this case, webpack don't know exactly which module you are requiring, so it will load all file.
const moduleName = xxx
const module = require(moduleName)
question 2:
you need to add { test: /\.json$/, loader: "json" } in module/loaders for loading json file.
Related
I am new to webpack. Recently, I wanted to find a way to view pdfs in one of my projects. I have found out a library called "react-pdf" (https://www.npmjs.com/package/react-pdf) and decided to experiment with it. When using it in a test react project (npx create-react-app), everything worked fine, but when I to introduced it to the real project, using Nextjs, things went wrong.
import placeholder from "../src/placeholder.pdf""
Every time the server reloads I get this error:
*
error - ./assets/pdf/placeholder.pdf
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)*
This is the webpack config:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.pdf$/i,
type: 'asset/resource',
generator: {
filename: `[name][ext]`
}
}
],
},
mode: 'development'
};
What am I doing wrong?
next.config.js
module.exports = {
webpack: (config, options) =>
{
config.module.rules.push({
test: /\.pdf$/i,
type: 'asset/source'
})
return config
},
}
I'm trying to integrate a connection to Ledger nano X devices, into a native Swift package. Unfortunately Ledger only provide an SDK as a ReactNative module. I dislike ReactNative and really don't want to integrate it into my entire Swift package, and force it onto my users, just for this one library.
I've had limited success in the past converting NodeModules into plain .js files that I can run directly with iOS's JavascriptContext. I've used webpack to bundle it up into a single plain js file (no require, import, export etc keywords). Adding a native Swift wrapper around that lets me keep all the messy dev setup and tools out of my project and just leverage the plain JS when needed for small use-cases. I've very little experience with this and what i've done in the past isn't working, hours of googling hasn't gotten me any closer.
Building the entire Ledgerjs with webpack was throwing up errors, since I only need pieces of it I started trying to get one of the sub-packages #ledgerhq/react-native-hw-transport-ble to build. I forked the project and added this webpack.config.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
"ledger_transport_ble": ['./src/awaitsBleOn.ts', './src/BleTransport.ts', './src/monitorCharacteristic.ts', './src/remapErrors.ts', './src/timer.ts', './src/types.ts']
},
mode: 'production',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx'],
modules: ['node_modules'],
fallback: {
"stream": require.resolve("stream-browserify")
}
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
library: ['[name]'],
libraryTarget: "var"
},
plugins: [
new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'] })
],
};
with this .babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-flow"
]
}
and I get back this error:
ERROR in ./node_modules/react-native-ble-plx/index.js 11:7
Module parse failed: Unexpected token (11:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| export { State, LogLevel, ConnectionPriority, ScanCallbackType, ScanMode } from './src/TypeDefinition'
|
> export type {
| Subscription,
| DeviceId,
# ./src/BleTransport.ts 87:29-60
Instructions online where to add the .babelrc file that I added above, but it made no difference. Have I missed a step somewhere? Or is there something else I should be doing?
I am currently working on a library which should dynamically load a JavaScript from a remote host and instantiate that.
I am writing the library in TypeScript and my plan is to use Webpack as a bundler.
On another host (remote system) runs a provider which should serve JavaScript code (see here: https://stubs.d-koppenhagen.de/stubs/SimpleStub.js).
The library will dynamically resolve "Identitys" via Webfinger. These Identitys represented by an object and they having a property pointing to a "Stub Provider" which will serve JavaScript code (the link I mentioned before). My library should load this script during runtime (s the library don't know the target for this stubs before) and should use it.
currently my webpack.config.js looks like the following:
var path = require('path');
var webpack = require('webpack');
var WebpackBuildNotifierPlugin = require('webpack-build-notifier');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PATHS = {
src: path.join(__dirname, './src'),
build: path.join(__dirname, './dist')
};
module.exports = {
entry: {
wonder: PATHS.src + '/wonder'
},
output: {
path: PATHS.build,
filename: '[name].js',
library: 'Wonder',
libraryTarget: 'umd'
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.ts$/,
loader: 'ts-loader'
}
]
},
resolve: {
extensions: ['.ts', '.js']
},
plugins: [
new WebpackBuildNotifierPlugin()
]
};
And here is a part of the library code:
require.ensure([], function() {
require(localMsgStubUrl);
});
When I am now including the bundled library in an example app, I will get the following error:
Error: loading chunk failed
So is there a way to tell webpack not to bundle the code which is required from a external resource loaded from a URL so that I can use that code like it is?
I don't want to tell webpack the URL statically in a config as maybe other stubs I am loading are located on a different target.
Thanks in advance for your help!
I don't know how to load with webpack any CSS from node_modules libs, for example I've installed leaflet and each attempt of load leaflet/dist/leaflet.css fails.
Could you provide example how to load static styles from node_modules?
My current webpack config below. Additionaly I'm using extract-text-webpack-plugin and sass-loader my project scss files are working well, I have also css-loader, have I to resolve static css files or add something to stylePathResolves?
//require('leaflet/dist/leaflet.css');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var webpack = require("webpack");
var path = require('path');
var stylePathResolves = (
'includePaths[]=' + path.resolve('./') + '&' +
'includePaths[]=' + path.resolve('./node_modules')
)
module.exports = {
entry: ".js/app.js",
output: {
path: "./static/js",
filename: "app.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
'style',
'css' + '!sass?outputStyle=expanded&' + stylePathResolves
)
}
]
},
plugins: [new ExtractTextPlugin("app.css")]
};
Where to load leaflet.css, commented out require('leaflet/dist/leaflet.css') gives me following error:
home/myproj/node_modules/leaflet/dist/leaflet.css:3
.leaflet-map-pane,
^
SyntaxError: Unexpected token .
For users who have encountered a similar problem, there are steps that I've done to get it working, I'm not sure that this equilibrium way.
npm install file-loader --save
add import 'leaflet/dist/leaflet.css'; in main app.js
change webpack.config.js by following way:
add css-loader to get rid of SyntaxError: Unexpected token . and next add file-loader and match files to get rid of Uncaught Error: Cannot find module "./images/layers.png":
module.exports = {
entry: "./web/static/js/app.js",
output: {
path: "./priv/static/js",
filename: "app.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract(
'style',
'css' + '!sass?outputStyle=expanded&' + stylePathResolves
)
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file-loader'
}]
},
plugins: [new ExtractTextPlugin("app.css")]
};
At the beginning I got this config from some example and it's not 100% clear why I've used ExtractTextPlugin to load scss and what the correlation is with css-loader, maybe to be more coherent should I use ExtractTextPlugin also in this part, maybe someone knows and can code review? But my solution is working and I can work further.
I had to do:
npm install --save-dev style-loader css-loader file-loader
If I didn't configure the file loader for the images, I got:
ERROR in ./node_modules/leaflet/dist/images/layers-2x.png 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/leaflet/dist/leaflet.css (./node_modules/css-loader!./node_modules/leaflet/dist/leaflet.css) 7:8888-8921
# ./node_modules/leaflet/dist/leaflet.css
# ./src/view/component/RouteMap.js
# ./src/index.js
ERROR in ./node_modules/leaflet/dist/images/layers.png 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/leaflet/dist/leaflet.css (./node_modules/css-loader!./node_modules/leaflet/dist/leaflet.css) 7:8716-8746
# ./node_modules/leaflet/dist/leaflet.css
# ./src/view/component/RouteMap.js
# ./src/index.js
ERROR in ./node_modules/leaflet/dist/images/marker-icon.png 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
# ./node_modules/leaflet/dist/leaflet.css (./node_modules/css-loader!./node_modules/leaflet/dist/leaflet.css) 7:9975-10010
# ./node_modules/leaflet/dist/leaflet.css
# ./src/view/component/RouteMap.js
# ./src/index.js
You also MUST import the CSS file in your index.js or main.js (or whatever your main JS file is called). Otherwise, you get an error saying that module.exports is read-only.
import 'leaflet/dist/leaflet.css';
A more updated webpack.config.js snippet is:
{
...
module: {
rules: [
{ test: /\.css$/, use: ["style-loader","css-loader"] },
{ test: /\.(png|svg|jpe?g|gif|woff2?|ttf|eot)$/, use: [ 'file-loader' ] },
],
},
I am getting this error when I npm start my webpack-dev-server:
ERROR in multi main
Module not found: Error: Cannot resolve 'file' or 'directory' /var/www/html/151208-DressingAphrodite/app in /var/www/html/151208-DressingAphrodite
# multi main
Here is my webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require ('html-webpack-plugin');
const PATHS = {
app: path.join (__dirname, 'app'),
build : path.join (__dirname, 'build')
};
module.exports = {
entry : [
'babel-polyfill',
'webpack-dev-server/client?http://localhost:8080',
PATHS.app
],
output : {
publicPath : '/',
filename : 'dressingaphrodite.js',
hash : true
},
debug : true,
devServer : {
contentBase : './app'
},
devtool : 'source-map',
module : {
loaders : [
{
test : /\.jsx?$/,
include : PATHS.app,
loader : 'babel-loader',
query : {
presets : ["es2015"]
}
},
{
test: /\.css$/,
include: PATHS.app,
loader: 'style!css'
}
]
},
plugins : [
new HtmlWebpackPlugin ({
title : 'Dressing Aphrodite',
filename : 'da.html'
})
]
};
ok if any one face this problem, you can solve it in 2 methods:
Method 1:
1- add a file called package.json inside your entry folder (in your case put it inside the folder "{project_dir}/app/package.json")
2- inside this file write any json object for example:
{
"name": "webpack why you do diss :("
}
Method 2:
Change your entry files to be at least 2 level away from your project home directory, for example: "{project_dir}/src/app"
Explanation: for each entry file webpack will try to find a file called package.json to use it for webpack configuration incase this entry file is a module, when you put your entry file only 1 level away from your project home dir webpack will use your project packge.json as configuration file for your entry file and it will fail because of miss configuration.
You should check the browser console. It provides more detailed informations.
In my case:
Uncaught Error: Cannot find module "./src/index"
at webpackMissingModule (webpack:///multi_main?:4)
at eval (webpack:///multi_main?:4)
at Object.<anonymous> (bundle.js:586)
at __webpack_require__ (bundle.js:556)
at bundle.js:579
at bundle.js:582
So here is the error a missing (or misspelled) java script file.
The same problem I met. I found an answer in github Error : ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory'#981. But sadly, in webpack 1.15.12, the --allow-incompatible-update has been remove. Also, I found when set the entry type is array, such as entry: [entry.js], webpack will run, but throw another error:(
I wish it can help you, hopefully.