Webpack cannot resolve file or dic - javascript

MyAPP:
|--src
  |--index.js
  |--content.js
|--webpack.config.js
index.js :
const React = require('react');
const ReactDom = require('react-dom');
const View = require('./content');
ReactDom.render(<View/>, document.body);
content.js :
const React = require('react');
class view extends React.Component {
render() {
return <p> Content </p>
}
}
module.exports = View;
webpack.config.js
module.exports = {
entry: './src/*',
output: {
path: path.join(__dirname, '/build'),
filename: '[name].bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.js|jsx$/,
loader: ['jsx-loader?harmony'],
exclude: /node_modules/
}]
},
plugins: [commonsPlugin]
}
Problems:
webpack --display-error-details
Hash: c47fe037926d0dc83af7
Version: webpack 1.13.0
Time: 62ms`
Asset Size Chunks Chunk Names
common.js 191 bytes 0 [emitted] common.js
ERROR in Entry module not found: Error: Cannot resolve 'file' or 'directory' ./src/* in /Users/xx/WebstormProjects/jianwenji-react
resolve file
/Users/xx/WebstormProjects/jianwenji-react/src/* doesn't exist
/Users/xx/WebstormProjects/jianwenji-react/src/*.js doesn't exist
/Users/xx/WebstormProjects/jianwenji-react/src/*.jsx doesn't exist
resolve directory
/Users/xx/WebstormProjects/jianwenji-react/src/* doesn't exist (directory default file)
/Users/xx/WebstormProjects/jianwenji-react/src/*/package.json doesn't exist (directory description file)
Why webpack can't find that files?

In this case entry should refer to file not to folder,
module.exports = {
entry: './src/index.js'
// ....
}
Note - jsx-loader is deprecated, use babel-loader, babel-preset-react instead

Related

Webpack compiling error if "require('dotenv').config()" is in index.js How can I fix?

require('dotenv').config() cause webpack compiler error:
ERROR in ./node_modules/dotenv/lib/main.js 26:11-24
Module not found: Error: Can't resolve 'os' in 'C:\Users****\node_modules\dotenv\lib'
It seems like webpack can't handle in index.js but I can't understand why.
my webpack.config.js:
const path = require(`path`);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require(`clean-webpack-plugin`);
module.exports = {
watch: true,
mode: `development`,
entry: {
app: `./src/index.js`,
profile: `./src/profile.js`
},
plugins: [
new HtmlWebpackPlugin(),
new CleanWebpackPlugin()
],
output: {
filename: `[name].bundle.js`,
path: path.resolve(__dirname, `dist`)
},
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
index.js
require('dotenv').config()
import "./style.css";
const title = document.createElement("h3");
title.textContent = "Webpack made easy";
document.body.append(title);
title.classList.add("hello");
console.log(process.env.API_KEY);
Please use it in webpack configuration file. (webpack.config.js)
Also, you need to install dotenv-webpack package.
Please look at this link.
https://github.com/mrsteele/dotenv-webpack/blob/master/README.md
Add new Dotenv() to your plugins array

Webpack JSX cannot resolve relative module through ES6 imports

I'm setting up webpack for a large already existing React App.
Seems to be working fine but some modules causes trouble unless I specifically add the extension to the import
//not working
import AppRouter from './router';
//working but meh
import AppRouter from './router.jsx';
It does not occur in all the relative imports but some for what I see look random.
The error, it occur multiple times for different files
ERROR in ./src/main/resources/js/cs/index.js
Module not found: Error: Can't resolve './router' in '<ommited_path>/src/main/resources/js/cs'
# ./src/main/resources/js/cs/index.js
The folder structure for that file
/src
--/main
--/resources
--/js/
--/cs
index.js
router.jsx
store.js
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const paths = require('./config/paths');
const config = {
entry: {
index: path.join(__dirname, paths.custServReactIndex),
},
output: {
path: path.join(__dirname, paths.outputScriptsFolder),
filename: '[name].js',
publicPath: paths.outputScriptsFolder,
},
mode: 'development',
module: {
rules: [
{
// Compile main index
test: /\.jsx?$/,
loader: 'babel-loader',
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
module.exports = config;
.babelrc
{
"ignore": ["node_modules"],
"presets": ["env", "stage-0", "react"]
}
That being said, any idea on why some relative imports are failing and how can I solve so?
You need to add resolve extensions. Add the below config in Webpack and restart React app
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
}

WebPack importing react custom packages in another folder

I am enhancing a website with ReactJS.
My folder structure looks something like this:
_npm
node_modules
package.json
package-lock.json
webpack.config.js
_resources
js
react
reactapp1.js
reactapp2.js
components
FormDisplay.js
I want to import a custom reactjs package into the FormDisplay component.
When I enter:
import PlacesAutocomplete from 'react-places-autocomplete'
This doesn't work. But if I enter:
import PlacesAutocomplete from "./../../../_npm/node_modules/react-places-autocomplete";
This works. I understand why this is the case. I was wondering if there was a way that I can just enter:
import PlacesAutocomplete from 'react-places-autocomplete';
How do I make it work with just that line of code, without having to find the path to node_modules folder?
My webpack config:
const path = require("path");
const webpack = require("webpack");
const PATHS = {
app: path.join(__dirname, "../_resources/react/"),
build: path.join(__dirname, '../wordpress_site/wp-content/themes/custom_theme/assets/js/'),
};
module.exports = {
entry: {
reactapp1: path.join(PATHS.app, "reactapp1.js"),
reactapp2: path.join(PATHS.app, "reactapp2.js")
},
output: {
filename: "[name].bundle.js",
//path: path.join(__dirname, "dist")
path: PATHS.build
},
module:{
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"],
plugins: ["transform-class-properties"]
}
}
}
]// rules array
}, // module
}
Have you tried using webpack's resolve-modules?
resolve: {
modules: ['_npm/node_modules']
}
Might work

React & Webpack: Loading failed for the <script> with source http://localhost:8080/app/bundle.js

I am new in reactjs. I tried to configure react with basic index page including index.js(containing a console.log()) but when i tried to run server index.html showing properly but bundle.js is not loading. I search it a lot but not getting proper answer can any one help me please.
my webpack.config.js is
// Webpack config js.
var webpack = require("webpack");
var path = require("path");
var DIST_VAR = path.resolve(__dirname, "dist");
var SRC_VAR = path.resolve(__dirname, "src");
var config = {
entry : SRC_VAR + "\\app\\index.js",
output: {
path: DIST_VAR + "\\app\\",
filename: "bundle.js",
publicPath : "\\app\\",
},
module: {
rules: [
{
test: /\.js?/,
include: SRC_VAR,
loader: "babel-loader",
query: {
presets: [ "react" , "es2015" , "stage-2"]
}
}
]
}
};
module.exports = config;
Error is showing in console: Loading failed for the with source “http://localhost:8080/app/bundle.js”.
Edit:
Folder Listing added..
Folder PATH listing
Volume serial number is BE9C-4E51
C:.
| package-lock.json
| package.json
| webpack.config.js
|
+---dist
| | index.html
| |
| \---app
| bundle.js
|
+---node_modules
| <Here the node_modules>
\---src
| index.html
|
\---App
index.js
I'll make some assumptions without seeing your project folder structure.
Looks like it could be your publicPath. Unless that's what you intended, the /app folder shouldn't be visible and since your console is showing "localhost:8080/app/bundle.js" that means it's looking for "project-root/src/app/app/bundle.js" instead of "project-root/src/app/bundle.js"
In the webpack docs they're telling you to default to root '/' and looking at my own webpack file thats what mine is currently set to as well.
Reference:
https://webpack.js.org/guides/public-path/
Edit: Here's an example using Webpack 3. Version 4 just came out and this will not work, so I'd be careful where you're getting your config examples from if you are using Webpack 4.
const webpack = require('webpack');
const path = require('path');
module.exports = {
plugins: [
// new webpack.NamedModulesPlugin(),
// new webpack.HotModuleReplacementPlugin()
],
context: path.join(__dirname, 'src'),
entry: [
// 'webpack/hot/dev-server',
// 'webpack-hot-middleware/client',
// 'babel-polyfill',
// 'history',
'./index.js'
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot-loader/webpack', 'babel-loader']
}],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};
after installing
npm init -y
and
npm install --save-dev webpack webpack-dev-server webpack-cli
and your structure files
src/
build/
webpack.config.js
package.json
go to package.json, and add build command:
"scripts": {
"start":"webpack serve --mode development",
"build":"webpack"
},
in webpack.config.js
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
output: {
path: path.resolve(__dirname, './build'),
filename: 'bundle.js',
},
devServer: {
contentBase: path.resolve(__dirname, './build'),
},
};
so,in your build/index.html
<script type="text/javascript" src="./bundle.js"></script>

Wrong URL for images with React + Typescript + WebPack

I'm referencing an image inside my .JSX file but the generated URL is wrong.
It looks like this : http://localhost:43124/dist/dist/9ee7eb54c0eb428bb30b599ef121fe25.jpg
The folder "dist" exists with the picture but not "dist/dist". I think the problem comes from my Webpack.config.js. Here are the files :
module.d.ts
I instruct Typescript what to do with image files as mentionned here.
declare module '*.jpg'
declare module '*.svg'
Layout.tsx
I reference my logo inside React so it can be packed by Webpack.
/// <reference path="./module.d.ts"/>
import * as React from 'react';
import logo from '../img/logo.svg';
export class Layout extends React.Component<{}, {}> {
public render() {
return <img src="{logo}" width="220" alt="logo" />
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
// Configuration in common to both client-side and server-side bundles
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
});
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './ClientApp/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
return [clientBundleConfig];
};
I used the default Visual Studio ASP.NET Core React + Redux template.

Categories