webpack can't find module if file named jsx - reactjs

As I write webpack.config.js like this
module.exports = {
entry: './index.jsx',
output: {
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
}
};
And in index.jsx I import a react module App
import React from 'react';
import { render } from 'react-dom';
import App from './containers/App';
let rootElement = document.getElementById('box')
render(
<App />,
rootElement
)
I find if I named module app in App.jsx, then webpack will say in index.jsx can't find module App, but if I named named module app in App.js, it will find this module and work well.
So, I'm confuse about it. In my webpack.config.js, I have writed test: /\.jsx?$/ to check file, but why named *.jsx can't be found?

Webpack doesn't know to resolve .jsx files implicitly. You can specify a file extension in your app (import App from './containers/App.jsx';). Your current loader test says to use the babel loader when you explicitly import a file with the jsx extension.
or, you can include .jsx in the extensions that webpack should resolve without explicit declaration:
module.exports = {
entry: './index.jsx',
output: {
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx'],
}
};
For Webpack 2, leave off the empty extension.
resolve: {
extensions: ['.js', '.jsx']
}

In the interest of readability and copy-paste coding. Here is the webpack 4 answer from mr rogers comment in this thread.
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
resolve: {
extensions: [".js", ".jsx"]
},
use: {
loader: "babel-loader"
}
},
]
}

Adding to the above answer,
The resolve property is where you have to add all the file types you are using in your application.
Suppose you want to use .jsx or .es6 files; you can happily include them here and webpack will resolve them:
resolve: {
extensions: ["", ".js", ".jsx", ".es6"]
}
If you add the extensions in the resolve property, you can remove them from the import statement:
import Hello from './hello'; // Extensions removed
import World from './world';
Other scenarios like if you want coffee script to be detected you should configure your test property as well like:
// webpack.config.js
module.exports = {
entry: './main.js',
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.coffee$/, loader: 'coffee-loader' },
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
resolve: {
// you can now require('file') instead of require('file.coffee')
extensions: ['', '.js', '.json', '.coffee']
}
};

As mentioned in the comments on the answer from #max, for webpack 4, I found that I needed to put this in one of the rules that were listed under module, like so:
{
module: {
rules: [
{
test: /\.jsx?$/,
resolve: {
extensions: [".js", ".jsx"]
},
include: ...
}
]
}
}

Verify, that bundle.js is being generated without errors (check the Task Runner Log).
I was getting 'can't find module if file named jsx' due to the syntax error in html in component render function.

I was facing similar issue, and was able to resolve using resolve property.
const path = require('path');
module.exports = {
entry: './src/app.jsx',
output: {
path: path.join(__dirname,'public'),
filename: 'bundle.js'
},
module : {
rules: [{
loader: 'babel-loader',
test: /\.jsx$/,
exclude: /node_modules/
}]
},
resolve: {
extensions: ['.js', '.jsx']
}
}
As You can see I have used .jsx in there which resolved following error
ERROR in ./src/app.jsx
Module not found: Error: Can't resolve
For Reference: https://webpack.js.org/configuration/resolve/#resolve-extensions

I faced similar issue with imports while building my typescript project having the following webpack dependencies:
"webpack": "^5.28.0",
"webpack-cli": "^4.5.0"
So, I had a App.tsx file present in the correct path and exported with named export. But, yarn build was failing with Module not found: Error: Can't resolve './App' in '/app/sample_proj/src'. The relevant code for this error is: import {App} from './App';. To fix this, I had to add .tsx under webpack known extensions. Sample entry from webpack.config.js is :
module.exports = {
......
resolve: {
extensions: [ '.ts', '.js', '.tsx', '.jsx'],
}
}
Also, for this error, it does not matter, if the imports are default or named. webpack only needs to know the kind of file extensions it should deal with.

I found restarting my server fixed this issue. simply run
npm start

Related

Import css files in typescript-files using aliases, webpack

i set up a project using webpack, react and typescript. I am now trying to use aliases for imports, which works fine for the most part.
However, i can't make importing css files to work with aliases.
I added the following part to my webpack.config.json
...
resolve: {
extensions: ["", ".ts", ".tsx", ".js", ".json", "css", ".scss"],
alias: {
BaseComponents: path.resolve(__dirname, "src", "BaseComponents"),
Pages: path.resolve(__dirname, "src", "Pages"),
Styles: path.resolve(__dirname, "src", "Styles"),
},
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: "babel-loader",
exclude: /node_modules/,
},
{
test: /\.(css)$/,
use: ["style-loader", "css-loader"],
},
],
},
...
and the following part to the tsconfig.json
...
"paths": {
"BaseComponents/*": ["./src/BaseComponents/*"],
"Pages/*": ["./src/Pages/*"],
"Styles/*": ["./src/Styles/*"],
},
...
Importing other react components and normal functions works as expected.
When i write
import "../Styles/test.css";
it works fine. But using the alias
import "Styles/test.css";
doesn't work, even though the ide doesn't complain and intellisense works when typing in the path.
The error is
ERROR in ./src/BaseComponents/App.tsx 3:0-25 Module not found: Error: Can't resolve 'Styles/test.css'
Does anyone know how to solve this?
Thank you.

React component via custom npm package. module cannot be found

I am trying to create a custom npm package that will allow me to import some of my components over multiple projects. I wrote a simple package yesterday which can be found here: demo npm package. It's a simple starter project that has a webpack config and a uses npx babel to transpile and copy the files to the dist and lib folder.
If I include this package into my own project it works but not as I would expect. when I use the following code:
import {NavBar, HelloLib} from "testprivatenprodney;
It gives an error "Module not found".
when I use
import { NavBar, HelloLib } from "testprivatenprodney/lib/HelloLib";
it works as long as the navBar component does not have any child components. If it has I get "Module not found" error again.
I think I am missing something in my webpack configuration. yet all I can find is to have the resolve array, which is included.
const webpack = require("webpack");
module.exports = {
devtool: "source-map",
entry: "./src/index.js",
output: {
path: __dirname + "/dist",
publicPath: "/",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
loaders: ["style-loader", "css-loader"]
}
]
},
resolve: {
extensions: [".js", ".jsx"]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
})
]
};
any help would be much appreciated.

Module not found: Error: Can't find options with ident 'postcss'

I'm new on stackoverflow to ask you a question that I never find on the internet... I hope I'm in the good website :)
So here is my problem : I would like to import some css files to a react application from node_modules dependencies. I use webpack for the developpement and I got an error I don't understand and that is in the title.
So here is the error details from the compiler :
ERROR in ./src/scss/app.scss
Module not found: Error: Can't find options with ident 'postcss'
# ./src/scss/app.scss 9:10-188
# ./src/app/App.js
# ./src/index.js
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src
also, in the nav console I got this :
Error: Cannot find module '-!../../node_modules/css-loader/index.js?{"importLoaders":1}!../../node_modules/postcss-loader/lib/index.js??postcss!react-big-calendar/lib/css/react-big-calendar.css'
that is the content of my scss file cannot load css files.
App.scss :
exports.i(require("-!../../node_modules/css-loader/index.js?{\"importLoaders\":1}!../../node_modules/postcss-loader/lib/index.js??postcss!react-big-calendar/lib/css/react-big-calendar.css"), "");
You can check also my webpack config file :
const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
}
]
},
plugins: [htmlWebpackPlugin],
resolve: {
extensions: ['.js', '.jsx', '.json', '.css']
}
};
What's wrong with my code ?
Thank you very much to help me ! If I'm not very clear, please ask me any other informations
You probably need to change your postcss-loader config to this. Depends really on which version of the loader you have, not needed from 4.0.0 (https://github.com/webpack-contrib/postcss-loader/releases/tag/v4.0.0)
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
},
}

ts-loader / css-loader not being able to import/resolve file

Trying to add css modules using style-loader and css-loader. Having a hard time figuring this out. I'm also not sure whether it's ts-loader to blame or css-loader.
webpack.config.js
const path = require('path');
module.exports = env => {
return {
devtool: "inline-source-map",
entry: "./src/index.tsx",
output: {
path: path.resolve(__dirname, "/public"),
filename: "build/app.js"
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader",
},
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
]
}
}
}
component
import styles from "./Main.css"; // TS2307: Cannot find module './Main.css'.
P.S. I tried using the extract-text-webpack-plugin, but that only messed up everything even more making the errors overwhelming
So since this doesn't seem like a popular problem I managed to find the solution. Hope this will help anyone who struggles with ts-loader + css-loader.
1) Add .d.ts file that handles .css extensions
// I put it in root, but could be anywhere
// <root>/defs.d.ts
declare module "*.css" {
var styles: { [key: string]: string };
export = styles
}
2) Since I use Webpack 3.x, change style to style-loader in webpack.config.js
module: {
rules: [
//...
{
test: /\.css$/,
loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
}
]
}
3) Import styles as * in component file
// In Main.tsx
import * as styles from "./Main.css";
// Usage
<div className={styles.nameOfClass} />
4) In tsconfig.json add .d.ts file to the include part. In my case its...
"include": [
"src",
"./defs.d.ts"
],
Restart webpack-dev-server or whatever and it should be good to go (hopefully).
Happy coding!

You may need an appropriate loader to handle this file type with babel/webpack2/react

I'm currently trying to get webpack 2 working with babel and react.
Heres my webpack.config.js:
'use strict';
module.exports = [
{
entry: './src/client/app/private.jsx',
output: {
path: './',
filename: './src/client/private/bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
rules: [
{
use: [
{
loader: 'babel-loader',
options: {
presets: [
['es2015', { modules: false }],
['es2016', { modules: false }],
'react'
],
}
},
],
exclude: /node_modules/
}
]
}
}
];
.babelrc:
{
"presets": [
"es2015",
"es2016",
"react"
],
"plugins": [
"transform-react-jsx",
"transform-regenerator"
]
}
And the error:
ERROR in ./src/client/app/private.jsx
Module parse failed: /home/karl/dev/node/project/src/client/app/private.jsx Unexpected token (7:16)
You may need an appropriate loader to handle this file type.
| import Index from './containers/Index/index.jsx';
|
| ReactDOM.render(<Index />, document.getElementById('root'));
My suggestion would be to clone this starter: https://github.com/alicoding/react-webpack-babel and then identify the variances. Also, not sure if it's as simple as removing the enclosing square brackets in your module.exports, but I've never seen that before. It's usually just
module.exports = {
//...
}
You have omitted the test property of your rule
rules: [
{
test: /\.jsx$/,
use: [
{
loader: 'babel-loader',
/*
your loader options
*/
},
],
exclude: /node_modules/
}
]
That might be the main issue but there are also others you may want to consider:
On output property you should use path for the path to output bundle, and filename only for the name of the bundle, as it indicates so.
output: {
path: path.resolve(__dirname, src/client/private),
filename: 'bundle.js'
},
You also have to remove the empty string '' from your resolve.extensions. In webpack 2 it's not required anymore.
resolve: {
extensions: ['.js', '.jsx']
},
If you want to export multiple configurations for different targets you can use an array of config objects, otherwise you should export your single config object.
module.exports = {
...
}
You can find more information on migrating to v2 here:
Migrating from v1 to v2

Resources