While updating some deps (react-bootstrap) I ran into a react error
You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Compiling the same code with other setups (storybook, create react app, codesandbox, ...) doesn't show the issue.
Looks like the component we import (react-bootstrap/Dropdown), imports another component (react-overlays/Dropdown) which causes the problem.
I tracked the error down to this line which does NOT get outputted:
/* harmony import */ var react_overlays_Dropdown__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_overlays_Dropdown__WEBPACK_IMPORTED_MODULE_4__);
Instead, the non-working code uses the ..._MODULE_4__['default'] syntax, which fails and raises the error.
After hours of searches I found out the problem...
Changing this
module.exports = {
resolve: {
modules: [path.join(__dirname, 'node_modules')]
}
};
to this
module.exports = {
resolve: {
modules: ['node_modules']
}
};
solves the problem.
Related
I am currently having trouble with my React TypeScript project.
I created my project with npx create-react-app my-app --template typescript.
I recently added tsyringe for dependency injection and was trying to implement it for an apiService. After following the readme(https://github.com/microsoft/tsyringe#injecting-primitive-values-named-injection) for adding primitive values I have hit a block. I already add experimentalDecorators and emitDecoratorMetadata to my tsconfig.json file with no success.
The error actual error I am encountering is:
./src/ts/utils/NetworkService.ts 9:14
Module parse failed: Unexpected character '#' (9:14)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|
| let NetworkService = (_dec = singleton(), _dec(_class = (_temp = class NetworkService {
> constructor(#inject('SpecialString')
| value) {
| this.str = void 0;
I am fairly sure this problem is caused by Babel, however I created this with npm create react-app --template typescript and do not seem to have access to the Babel configuration.
NetworkService.ts
#singleton()
export default class NetworkService
{
private str: string;
constructor(#inject('SpecialString') value: string) {
this.str = value;
}
}
Invocation method
bob()
{
const inst = container.resolve(NetworkService);
}
Registering Class in index.ts
container.register('SpecialString', {useValue: 'https://myme.test'});
#registry([
{ token: NetworkService, useClass: NetworkService },
])
class RegisterService{}
React-Scripts manages many of the configs related to the project. For many cases, this is fine and actually a nice feature. However, because React-Scripts uses Babel for it's development environment and does not expose the config.
You have to run npm run eject to expose the configurations.
Please note, this is a one-way operation and can not be undone.
Personally, I prefer more control with my configuration.
After this you can edit the webpack.config.js in the newly created config folder.
Find the section related to the babel-loader in the dev-environment and add 'babel-plugin-transform-typescript-metadata' to the plugins array.
Expanding on Jordan Schnur's reply, here are some more pitfalls I encountered when adding TSyringe to my CRA app:
Use import type with #inject
If you get this error "TS1272: A type referenced in a decorated signature must be imported with 'import type' or a namespace import when 'isolatedModules' and 'emitDecoratorMetadata' are enabled." replace import with import type for the offending imports. You will encounter this when working with #inject
E.g. replace import { IConfig } from "iconfig" with import type { IConfig } from "iconfig"
Fixing Jest
Your Jest tests will also break with TSyringe, especially when using #inject. I got the error "Jest encountered an unexpected token" with details constructor(#((0, _tsyringe.inject)("")) ("#" marked as the offending token). I took the following steps to fix that in CRA:
Add the line import "reflect-metadata"; to the top of the file src/setupTests.ts
In config/jest/babelTransform.js replace line 18 and following:
From
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
babelrc: false,
configFile: false,
});
to:
module.exports = babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-react-app'),
{
runtime: hasJsxRuntime ? 'automatic' : 'classic',
},
],
],
plugins: [
require.resolve('babel-plugin-transform-typescript-metadata')
],
babelrc: false,
configFile: false,
});
Instead of eject, you may use a lib that "overrides" some of your params.
I used craco : https://www.npmjs.com/package/#craco/craco
I've created an simpler DI library that doesn't need decorators or polyfill. Works with CRA like a charm and has cool React bindings
iti
import { useContainer } from "./_containers/main-app"
function Profile() {
const [auth, authErr] = useContainer().auth
if (authErr) return <div>failed to load</div>
if (!auth) return <div>loading...</div>
return <div>hello {auth.profile.name}!</div>
}
I found this but I can't seem to figure out what to do. How can I change my .eslintrc file so it ignores absolute imports of React components. I get the Unable to resolve path to module 'products/nomad_insurance/routing'.eslint(import/no-unresolved) error when trying to import something.
Also, I have ./src as a baseUrl in jsconfig.json
This solved the issue:
settings: {
'import/resolver': {
node: {
paths: ['src']
}
}
}
I have a standalone React application that uses webpack for bundling with a requirement of being able to run this bundle within a web component. Can anyone suggest how I should approach this?
I'm thinking something like:
//webpack.config.js
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
library: 'reactUmd',
libraryTarget: 'umd',
umdNamedDefine: true
},
//react-component.js
import '../../packages/react-umd/dist/bundle.js'
class ReactComponent extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement('span');
this.attachShadow({ mode: 'open' }).appendChild(mountPoint);
reactUmd.renderSomeComponentTo(mountPoint)
}
}
customElements.define('react-component', ReactComponent)
But I'm not sure how I can import the compiled bundle and get a reference to React, ReactDOM, the Main component etc, would exporting as UMD provide the references I need?
So you basically want to access the react component outside the minified bundle file.
Here is one approach:
You tell webpack to create a library for your file. This will basically create a global variable using which you can access all the exported functions from you js entry file.
To do so, add a key called library int your webpack config under output object.
module.exports = {
entry: './main.js',
output: {
library: 'someLibName'
},
...
}
After doing this, restart your webpack server and on console, type window.someLibName. This should print all the methods exported by main.js as an object.
Next step is to create a function which accepts a DOM element and renders the react component on the element. The function would look something like this:
export const renderSomeComponentTo = (mountNode) => {
return ReactDOM.render(<App />,MOUNT_NODE);
}
Now you can access the above function from anywhere in the project, using
const mountNode = document.getElementById('theNodeID');
window.someLibName.renderSomeComponentTo(mountNode);
This way, all the react specific code is abstracted :)
I hope I answered your question. Don't forget to hit star and upvote. Cheers 🍻
In my Angular/Typescript/Webpack project, I was rewriting unit tests after code modifications.
The symptom of the issue was an error when running a very basic component test: "Error: Unexpected value 'undefined' declared by the module 'DynamicTestModule'"
In order to debug the issue, I wound up stripping out all dependencies from the constructor of the component and essentially all code. The component did nothing and yet I still got the error. It couldn't be a circular dependency because there were no dependencies.
The folder files were:
--profile
----profile.component.ts
----profile.component.spec.ts
----profile.component.html
----index.ts (barrel)
The component (with most meaningful code removed in order to figure out problem) is:
import { Component } from '#angular/core';
#Component({
selector: 'profile',
template: `<h1></h1>`
})
export class ProfileComponent {
title = 'Test Tour of Heroes';
constructor(){}
}
And the spec is:
import { NO_ERRORS_SCHEMA, DebugElement } from '#angular/core';
import { ComponentFixture, TestBed }
from '#angular/core/testing';
import { ProfileComponent } from './profile.component';
console.log(ProfileComponent);
fdescribe('Component: Jasmine Spy Test', () => {
console.log(ProfileComponent);
let fixture: ComponentFixture<ProfileComponent>;
let component: ProfileComponent;
let fixture2: ComponentFixture<ProfileComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ProfileComponent]
}).compileComponents();
fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
});
it(`should create instance of objects`, () => {
expect(1).toBe(1);
});
});
Versions:
"#angular/core": "^4.0.0",
"karma": "~1.4.1"
"webpack": "^2.3.3"
There are lots of other packages but I don't think that was the issue.
I was using VisualCode 1.14.0 (1.14.0).
The Real Issue VisualCode identified that ProfileComponent was in ./profile.component but the console.log lines printing that out said 'undefined' and no compile/transpile error was thrown.
Notice that there is a separate .html file in the folder but the code doesn't reference it.
ProfileComponent began to have value (no longer undefined) when I renamed the profile.component.html file -- must have been something about the webpack build.
I don't know what is wrong with this particular set of files because there any many folders with this exact same naming convention/setup in this project that do run the tests correctly.
I'm leaving this here in case someone runs across this error.
I also faced this issue. The component I was testing was not declared in any module. I had commented out the code in the module, after removing the comments, the error was fixed.
I am getting a webpack TypeError when I am trying to simplify an import. The following code works without any issues. Here I am importing a React Higher-Order-Component (HOC) called smartForm from core/components/form/index.js.
core/components/form/index.js (does a named export of smartForm)
export smartForm from './smart-form';
login-form.jsx (imports and uses smartForm)
import { smartForm } from 'core/components/form';
class LoginForm extends React.Component {
...
}
export default smartForm(LoginForm);
However, I want to simplify the import to just import { smartForm } from 'core'. So I re-exported smart-form in core/index.js and imported it from core. See the code below:
core/index.js (does a named export of smartForm)
export { smartForm } from './components/form';
// export smartForm from './components/form'; <--- Also tried this
login-form.jsx (imports and uses smartForm)
import { smartForm } from 'core';
class LoginForm extends React.Component {
...
}
export default smartForm(LoginForm); // <--- Runtime exception here
This code compiles without any issues, but I am getting the following runtime exception at the line export default smartForm(LoginForm);:
login-form.jsx:83 Uncaught TypeError: webpack_require.i(...) is not a function(…)
What am I missing?
P.S. Here are the Bable and plugin versions that I am using:
"babel-core": "^6.18.2",
"babel-preset-es2015-webpack": "^6.4.3",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-1": "^6.16.0",
tl;dr
For the questioner: Add this to your webpack.config.js:
resolve: {
alias: {
core: path.join(__dirname, 'core'),
},
},
For the general audience: Make sure the thing you try to import is indeed exists in that package.
Explanation
Questioner's problem: importing own code like npm modules
You try to import your module's exports in the same fashion how you import something from an npm package from the node_modules folder: import { something } from 'packagename';. The problem with this is that doesn't work out of the box. The Node.js docs give the answer on why:
Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.
So you either has to do what Waldo Jeffers and Spain Train suggested and write import { smartForm } from './core', or you can configure webpack so it can resolve your import path via its aliases which are created to solve this exact problem.
Debugging the error message in general
This error can arise if you try to import something from an existing npm package (in node_modules) but the imported thing doesn't exist in the exports. In this case, make sure there were no typos and that the given thing you try to import is indeed in that package. Nowadays it is trendy to break libraries into multiple npm packages, you might be trying to import from a wrong package.
So if you get something like this:
TypeError: __webpack_require__.i(...) is not a function
at /home/user/code/test/index.js:165080:81
at Layer.handle [as handle_request] (/home/user/code/test/index.js:49645:5)
To get more information on what import you should check, just open the output file generated by webpack and go to the line marked by the topmost line in the error stack (165080 in this case). You should see something like: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_9_react_router_dom__["match"]). This tells us that there is no match export (or there is but it isn't a function) in react-router-dom, so we need to check our stuff around that import.
Since core is a folder of your app and not an npm module, Webpack can not understand which file you want to load. You must use a correct path pointing to a file. You have to replace import { smartForm } from 'core'; by import { smartForm } from './core/index.js
This error will occur by many reasons. Once I encountered this error when I add js in file-loader then when I removed it start to work correctly.
{
test: /\.(ttf|eot|svg|gif|jpg|png|js)(\?[\s\S]+)?$/,
use: 'file-loader'
},
When I remove |js it works
{
test: /\.(ttf|eot|svg|gif|jpg|png)(\?[\s\S]+)?$/,
use: 'file-loader'
},
Just remove these 2 line from config
const context = resolve.alias.context('./', true, /\.spec\.ts$/); context.keys().map(context);