I am using React with FuseBox as bundler. The issue I am having at the moment is that aliasing isn't working so I can help deal with relative path hell.
My structure of the project:
stores folder has my MobX stores and an index.ts file that exports all the stores.
services has a bunch of service classes all exported in there respective files (no index.ts)
So in my fuse.ts I have:
alias: {
"services": "~/services",
"stores": "~/stores"
},
Then in my ui folder for example I am importing like so:
import AccountStore from "stores";
I get [ts] Cannot find module 'stores' error on that line at "stores".
Not sure have I got the alias section wrong? My homeDir in fuse.ts is set to "src/". I don't have any paths or baseUrl set in tsconfig like I did have when we were using webpack to setup absolute paths. Not sure if those are needed again or if it is something I am doing wrong with alias.
Any tips would be great :)
I have looked at the alias documentation on the fusebox site and followed it and tried a few different combinations but not getting any closer to it working. Would love some examples from people who have got this working.
Edit:
I have additionally done the following while trying to figure this out:
remove .fusebox folder
restarted vscode
have checked the bundle and it is adding a tilde there so fusebox must be recognising it?
will continue to add more things I try..
My solution to the problem I was having was to put the tsconfig.json file inside my src folder and the project/app inside ~.
Inside tsconfig.json i set baseUrl to root.
{
"compilerOptions": {
"baseUrl": ".",
// ...
}
}
This then allowed me to do absolute imports that would be the same across all files so it would be easy to reuse imports and quickly copy if needed.
import { service1, service2, service3 } from '~/services';
import { store1, store2 } from '~/stores';
The tilde usually represents home or base on a lot of systems so a few devs agreed it would be appropriate to use it in our folder structure. Though did have to remember to remove ~ from .gitignore if you have something that is autogenerated and its automatically in there.
Related
I'm moving forward with the project and I want to start writing tests.
But I came across a problem that I don't know how to solve.
I'm using path mapping in the project, but when I write the tests the page (or component) is not found.
I care like this
import Dashboard from '#pages/dashboard';
and the error is
Cannot find module '#pages/dashboard' from 'src/__tests__/pages/dashboard.test.tsx'
Does anyone know why?
After taking another look at the Jest documentation I realized that the jest.config.ts settings were wrong.
I changed it to this and it worked.
moduleNameMapper: { '^#pages/(.*)$': '<rootDir>/src/pages/$1' }
Just for the record, my tsconfig looks like this:
"paths": { "#pages/*": ["./src/pages/*"] }
I am trying to import all urls for images in a directory in a wildcard fashion, with two possible extensions:
import urls from "../static/images/**/*.{png,svg}";
Currently there are three files in this directory, importing them individually works fine. When I use this syntax, the files are not found:
Failed to resolve import "../static/images/**/*.{png,svg}" from
"src/routes/index.svelte". Does the file exist?
I had heard that it was possible to do this out of the box in SvelteKit, do I need to enable or define the pattern of import in jsconfig.json file in order to achieve this functionality, or install a dependency?
Fixed by changing import to use meta.glob:
const urls = import.meta.glob("../static/images/**/*.{png,svg}");
In my case, I additionally had to set the eager option to true to load all components in a certain folder:
const components = import.meta.glob('./../lib/test/**.svelte', { eager: true });
Without this option, I always received an empty object.
I see that this answer suggests the syntax for importing images as shown below (commented out). In my case, it didn't work out (complaining there's no modules to find in that file) and I had to switch to the syntax that's currently active.
// import Author from "../assets/author.png";
var Author = require("../assets/author.png");
The difference I can imagine is that I'm using TypeScript (transpiling my TSX by awesome-typescript-loader and loading my PNG file-loader) and they seem to use JSX. But as far my understanding goes, it all transpiles to plain JS and require in the end.
Being a noob on React, I'm not sure what the reason of this discrepancy is but also I'm not sure what to google for to investigate myself.
This is more of a problem with typescript than webpack itself, you might need to declare modules on a declaration file.
Create a declarations.d.ts
Update your tsconfig.json
"include": [
"./declarations.d.ts",
],
Put this on that file:
declare module '*.png';
Error might be gone.
You can declare a module for your images like this:
declare module "*.png" {
const value: any;
export default value;
}
Then, you will be able to import your image like this:
import AuthorSrc from "../assets/author.png";
This is happening because webpack doesn't support image import out of the box. So you need to add a rule for that in the webpack config file. When you add a new rule, TypeScript doesn't automatically know that, so you need to declare a new module to resolve this. Without the module, you will be able to import images, but TypeScript will throw an error because you didn't tell to it is possible.
This issue has nothing to do with webpack or any bundler and is not quite a problem with typescript.
Typescript has stated that `require("path") is a way to include modules to the scope of your current module, whilst it can be also used to read some random files (such as json files, for example).
As Vincent and Playma256 specified, you can declare a module wildcard to match certain file types, so you can import it as an import statement. But you don't really need to do this. Typescript won't give you an error if you are trying to import a png or a json file (tslint might, but that depends on your configuration).
By the way, if your declaration is within the source folder of your project as defined in tsconfig.json, you don't need to include it as specified by Playma256.
I've created a sample project in node for you to test:
https://github.com/rodrigoelp/typescript-declare-files
I think you can solve this problem with Webpack&&typescript.The official webpage of webpack has introduced something about this in
https://webpack.js.org/guides/typescript/
And I have try this myself in
https://github.com/reactpersopnal/webpack-root/tree/feature/typescript
The reason is that you would like to use non-code assets with TypeScript, so we need to defer the type for these imports for webpack.
Your could simply add custom.d.ts.
declare module "*.jpg" {
const content: any;
export default content;
}
Lodash allows import like
import merge from 'lodash/merge';
This reduces the size of the import drastically. I maintain an npm module called react-spinners, and I want to allow the same import.
https://github.com/davidhu2000/react-spinners
For example, the current way to import is
import { BarLoader } from 'react-spinners';
I want to allow
import BarLoader from 'react-spinners/BarLoader';
Based on what I found, to do this, I need to have the following folder structure
main
- index.js <- the file that exports everything
- BarLoader.js
- ... other loaders
This structure is pretty messy because all the js files will be in the root directory.
The current set up I have is
main
- index.js
- dist <- output folder from compiling
- index.js
- BarLoader.js
- src <- uncompiled react code
- index.js
- BarLoader.js
So, currently, in order to import only a single loader is
import BarLoader from 'react-spinners/dist/BarLoader';
I cannot find anything that tells me how I can remove the dist from the above statement.
If you really want to mess with the npm-package You can create a file like
BarLoader.js on the main package folder and only export BarLoader(just like index.js exports every items)
Then you can import it via
import BarLoader from 'react-spinners/BarLoader';
But I would not recommend it as it would be a tedious task to create one file for each import
I guess it is a fair question, What is wrong with import BarLoader from 'react-spinners/dist/BarLoader';? maybe code readability?
I ran into the exact same issue, and did a bit of research on this.
Hackfix
Using Webpack, you can use config.resolve.alias, like so:
const webpackCfg = {
// ...
resolve: {
alias: {
'react-spinners': path.resolve(__dirname, 'node_modules/react-spinners/dist')
}
}
// ...
};
This way all files will be directly looked for in the dist folder.
import reactSpinners from 'react-spinners'; resolves to <root>/node_modules/react-spinners/dist (or node_modules/react-spinners/dist/index.js)
import BarLoader from 'react-spinners/BarLoader' will resolve to <root>/node_modules/react-spinners/dist/BarLoader etc...
How does Lodash do it?
As lodash points out in their README and also in this thread:
The Lodash github repository is not the pure source code, but rather "Lodash exported as a UMD module". They go further to explain:
Generated using lodash-cli:
$ npm run build
$ lodash -o ./dist/lodash.js
$ lodash core -o ./dist/lodash.core.js
However, they also mention here that they want to make this work without having two separate repositories in Lodash v5... Gonna be interesting to see how they end up doing it!
I myself did some experiments, and I could not get it to work quite yet. E.g. I tried to link to the dist folder and copy a modified version of the package.json into it after every build, and that kinda starts working. But sometimes the depending project will be unhappy about folders starting to get messed up. I'm sure, this can work (basically mixing source + dist into the dist folder) but it started to feel like a rabbit hole, so I have not continued pursuing this path (quite yet).
I have a react application, managed using react-scripts.
In my app i am using an external js script. The external script doesn't do any module exports.
The structure of the external script is as below (too big to include it in full).
var TradingView = {.... various functions }
At the end of the file:
if (window.TradingView && jQuery) {
jQuery.extend(window.TradingView, TradingView)
} else {
window.TradingView = TradingView
}
My goal is to create a simple react component using the external script, and call the function: TradingView.widget({...});
I have been searching online for ways to include an external script in a react component/ES6 style, and have tried various options: react-async-script-loader, and various webpack plugins: script-loader, imports-loader, ProvidePlugin etc. But i haven't been able to make it work.
The error i am getting after using the imports-loader or ProvidePlugin is:
1189:31 error 'jQuery' is not defined no-undef
1190:9 error 'jQuery' is not defined no-undef
In my webpack config, i have:
In the loaders section:
{
test: /tv\.exec\.js/,
loader: 'imports?jQuery=jquery,$=jquery,this=>window'
}
In the plugins section:
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
When i create a simple webpage (no react), and include the script, and call TradingView.widget(), the page just works fine.
The closest i could get help was to look at:
Managing jQuery plugin dependency in webpack
But it didn't work for me. I am quite new to the react, webpack ecosystem, so I am not sure what i am missing here.
Please let me know if you need any additional info.
Update: I tested the above, including the script in a simple react component, but not using the react-scripts this time, and directly using webpack configurations. I was simply able to import the external js in my component directly, and it worked. I was also able to use imports-loader plugin in webpack to expose jQuery, which also worked. So its possible that using react-scripts needs something else to make it work.
It looks like your external script is handling its "exports" by adding them as members of window. You can use the import keyword on a file that doesn't define exports like so:
import "modulename";
There's nothing special about that syntax except that it doesn't imply that any functions or variables will be made available via the import facility. The code in "modulename" that assigns members to .window will execute, which is the important thing.
For compiler complaints about accessing window.* globals, try assigning the variable you want to access to a local variable:
const jquery = window.jquery;
...or maybe...
const TradingView = window.TradingView;
Then you'll have the variable in scope, and it should be usable.