-
-
Notifications
You must be signed in to change notification settings - Fork 26.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Symlink behaviour #3547
Comments
It sounds like a bug, but this should be working. Can you give more details to reproduce this easily & some test files? A repo with README would be fantastic. |
I created a repo here. This was just initialisation with CRA under MacOS High Sierra and then symlinking in terminal with:
|
Thanks! |
I actually have only problems with Symlinks when building for deployment: #3650 On dev it works well. |
@BrunoVanDamme Can you elaborate on your use case? (Is it related to trying to share source between cra-apps and/or monorepo?) |
I am trying to share components between projects, so I would like to have these components in another directory and symlink to them from all the cra-apps where i would like to use them. |
@BrunoVanDamme Have a look at #1333 which is for supporting source sharing via monorepo manager (lerna and/or yarn workspace). I proposed a more generic source-sharing solution in #3436, but it has some downsides vs using a monorepo manager: (1) required some cra-configuration to specify allowable source paths, and (2) managing dependencies of those shared components is a job best left to some monorepo manager anyways...so, my favor has turned more toward using monorepo w/ managers for sharing source between apps. Curious if there's a reason for not using lerna and/or yarn workspace? |
As I understand yarn workspaces uses symlinks in the node_modules directory to other locations. My understanding is that CRA does not process files from node_modules, so I would have to do the transpiling on these external components myself. Is this correct? I would expect CRA to process the files symlinked from src as these files appear as if they where in the project itself. |
Correct, currently CRA does not process those files, but #1333 tracks the feature request to make CRA process those files. I think PR 3741 is pretty close to completing that feature, but there are some (minor?) open questions about how it should work. See questions in #1333 (comment) -- any feedback you could provide in that thread would be awesome and helpful in building consensus as to how it should work. |
@bradfordlemley Thanks a lot for jumping on that issue btw. I'm sorry repo infra changes are being a bit disruptive right now; hopefully we can review them soon! |
We also merged Jest 22 into |
@bradfordlemley Thanks for clarifying. I am not knowledgeable enough on this topic, but I don't understand where the technical difficulties are in handling these symlinks. (I can imagine processing the dependencies in node_modules is a whole different matter, as not all dependencies should be handled the same way). Why isn't just resolving these symlinks a simple solution to this problem? |
I don't think it's really a technical issue (although the comments in #3695 maybe show that it's not as simple as it seems), maybe more about encouraging maintainable practices. If you symlink from under /src, you have to import via relative path (unless you do some other magic with NODE_MODULES) and then maintain various symlinks if you change locations, and then there's defining, installing, and resolving dependencies for your external source. These are things that can make your build fragile, but monorepo managers seem to do those things well. There is a bit of a learning curve to the monorepo managers, but maybe worth it in the long run, seems like the direction many folks are headed (???), btw, they also help with de-duplicating dependencies. |
All that said, it is really easy to just create a symlink from under /src and seems like a reasonable expectation that it should be treated as if it was in /src, so hope others will chime in on this discussion. |
I also interesting in building two separate ReactJS projects. Both of them are using the same shared library or UI Components. I created a symlink in both projects to this shared UI Components directory. When I'm trying to import something from that UI Components directory - it tells the same error message as in the original message:
It happening because code isn't viable by a watcher from Can someone give me a hint how to solve this problem for now? Because I potentially can copy he entire directory to both projects, and write some watcher that will do it for me on the regular basis. But it looks ugly solution. I wish to use the same shared directory between two projects and include "raw" files that then will be compiled. Need your help. Thank you, |
BTW, here webpack/webpack#1643 I found some information about webpack and symlinks. It looks like webpack can find our files but doesn't run a compilation process for them. |
@1st Have you looked at monorepo support in 2.0? See 2.0 roadmap for updates and on how to use the alpha builds. Sharing code that way has several advantages over manual symlinks, but mainly allows your shared code to be truly modularized with its own dependencies, etc. Manual symlinks like you're requesting aren't supported in 1.0 or 2.0 yet -- if you find manual symlinks preferable, it'd be great to give the reasons here. |
Finally I found a workaround. You can run a watch process to compile your shared library and use it as symlink in your project. Here is my gist. |
I have a similar issue as @ali-wetrill except I haven't set up a symlink but rather uses the project reference feature in typescript. So in my clients tsconfig I've added this:
Interfaces and types work fine, but enums break with this error:
|
It's not a problem with enums. Everything else you've tried to export is valid javascript AND valid typescript. Try writing a function with a type signature; I expect you'll see the same issues. Forcing |
@mako-taco I have a similar problem as @ali-wetrill. I added |
It seems customize-cra doesn't help symlink paths by |
Here's the Solution we've arrived to at Vim (no, not the text editor :) ) for working with CRA + symlinked components in a monorepo:
Portions of our const cracoLessPlugin = require('craco-less');
const path = require('path');
const { whenProd } = require('@craco/craco');
/* Allows importing code from other packages in a monorepo. Explanation:
When you use lerna / yarn workspaces to import a package, you create a symlink in node_modules to
that package's location. By default Webpack resolves those symlinks to the package's actual path,
which makes some create-react-app plugins and compilers fail (in prod builds) because you're only
allowed to import things from ./src or from node_modules
*/
const disableSymlinkResolution = {
plugin: {
overrideWebpackConfig: ({ webpackConfig }) => {
webpackConfig.resolve.symlinks = false;
return webpackConfig;
},
},
};
const webpackSingleModulesResolution = {
alias: {
react$: path.resolve(__dirname, 'node_modules/react'),
'react-dom$': path.resolve(__dirname, 'node_modules/react-dom'),
'react-router-dom$': path.resolve(__dirname, 'node_modules/react-router-dom'),
},
};
const jestSingleModuleResolution = {
moduleNameMapper: {
'^react$': '<rootDir>/node_modules/react',
'^react-dom$': '<rootDir>/node_modules/react-dom',
'^react-router-dom$': '<rootDir>/node_modules/react-router-dom',
},
};
module.exports = {
plugins: [...whenProd(() => [disableSymlinkResolution], [])],
webpack: webpackSingleModulesResolution,
jest: {
configure: {
jestSingleModuleResolution,
},
},
}; Sadly this does require manual management of each broken import. Over a few months we haven't seen too many of these, so this is fine for now. Please excuse syntax errors if any, this is edited from our real configuration for brevity. |
Had this issue with symlinking a TS file, where non-TS syntax works, but on adding any TS syntax, get the "Unexpected token" error. In my case so far, adding CRACO with their instructions, with the following simple module.exports = {
webpack: {
configure: (webpackConfig, { env, paths }) => ({
...webpackConfig,
resolve: {
...webpackConfig.resolve,
symlinks: false
}
})
}
} Presumably when #7993 is merged this fix will no longer be needed. |
With |
@nitinkatyal1314 The hot reload functionality doesn't work for me either, when disabling the symlinks. Does anyone know how to solve it? |
For googlers ending up here, there is a (better) alternative to /* craco.config.js */
const path = require('path')
const updateWebpackConfig = {
overrideWebpackConfig: ({ webpackConfig }) => {
// This is a bit brittle, but this retrieves the `babel-loader` for me.
const loader = webpackConfig.module.rules[1].oneOf[2]
loader.include = [
path.join(__dirname, 'src'),
path.join(__dirname, '../backend/src'), // This is the directory containing the symlinked-to files
]
return webpackConfig;
}
}
module.exports = {
plugins: [
{ plugin: updateWebpackConfig, options: {} }
]
} /cc @romgrk |
@romgrk-comparative This really helped me :-). Thanks. I improved the 'bit brittle' part by using built-in utilities from craco to grab const path = require('path');
const {getLoader, loaderByName} = require('@craco/craco');
// Relative paths to shared folders.
// IMPORTANT: If you want to directly import these (no symlink) these folders must also be added to tsconfig.json {"compilerOptions": "rootDirs": [..]}
const SRC_LOCATIONS = [
'src',
'../../shared/src',
];
const updateWebpackConfig = {
overrideWebpackConfig: ({webpackConfig}) => {
// Get hold of the babel-loader, so we can add shared folders to it, ensuring that they get compiled too
const {match:{loader}} = getLoader(webpackConfig, loaderByName("babel-loader"));
loader.include = SRC_LOCATIONS.map(p => path.join(__dirname, p)),
return webpackConfig;
}
}
module.exports = {
plugins: [
{ plugin: updateWebpackConfig, options: {} }
]
} |
The solution from @romgrk-comparative and @benvium is working great for me now, but I had a lot of trouble getting started because of a quirk in the Windows When you're creating a symlink, the
Note that I didn't bother upper-casing the The resulting symlink remembered the lower-case I'll never get back the hours I wasted figuring this out, but maybe I can save someone else the trouble. |
I don't really understand what's going on with this symlinking soup. All I know my CRA app crashes due to library being imported twice in my const path = require('path')
const updateWebpackConfig = {
overrideWebpackConfig: ({ webpackConfig }) => {
// As described in https://github.com/facebook/create-react-app/issues/3547
// there are some issues with how CRA treats symlinks which pnpm heavily uses.
// This hack should fix this issue (loading prosemirror-model twice) for now
webpackConfig.resolve.alias = {
'prosemirror-model$': path.resolve(__dirname, '../editor/node_modules/prosemirror-model'),
}
return webpackConfig;
}
}
module.exports = {
plugins: [
{ plugin: updateWebpackConfig, options: {} }
]
} Basically I'm aliasing the library to the main module that uses it. Not really scalable but I hope I'll be able to contain it to only a few broken modules. |
I'm using another method to solve the duplicate package problem. Replace @TeemuKoivisto's webpackConfig.resolve.alias line with:
Explanation: CRA configures this Note: You will need to npm install in your main ClientApp the union of all packages you've installed in your shared code projects. (In @TeemuKoivisto's example above, Note 2: It's important to prevent all module duplication even if it doesn't cause a runtime error, because it can significantly increase the size of your webpack bundle. (You can use |
@RandScullard hi and no I don't. It works fine with the dependency being just inside editor (which in turn imports another workspace package that uses |
I just had to add another thing to my overrideWebpackConfig for my TypeScript project:
Explanation: 1 This is the default value for reportFiles:
|
All this to try to get symlinks to work the way the OS designers intended them to work? Surely, this needs re-evaluation on the part of CRA? If an application developer is creating symlinks, he/she probably has a good reason - I don't think its right to second guess them. |
FWIW, I used the techniques described in this issue to get my shared module working without symlinks. Rather than symlinking my shared module into my main project, I have it linked in my package.json like so:
|
Thanks @RandScullard - yes, there are workarounds but they shouldn't really be necessary. I sometimes use a similar workaround to the one you describe but HMR doesn't work; package manager caching gets in the way. I have to delete node_modules and/or clean caches when updating components - all very unproductive. |
Hi @RandScullard, Since I've upgraded my code to v5.0.0 none of the above workarounds seem to work. To get rid of the duplicates, I had to remove duplicated packages from the main app and rely on the nested dependencies of linked packages. |
@hasan-aa I am not using CRA v5, I am still on 4.0.3. I am waiting to upgrade until craco fully supports v5. (dilanx/craco#378) I have taken a look at the changes to webpack.config.js in CRA v5 and I can tell you that the workarounds above will definitely have to be modified to be compatible with the new config. I believe they still can be made to work, but not exactly as shown above. |
Hi @RandScullard Thanks for the clarification. It turned out the caching behavior was making it almost impossible to debug. If the previous build was creating duplicate modules, even if you fix the configuration and build again, it was still resolving the wrong modules due to the cache I believe. Once I enable memory cache, it became debuggable and now it's working fine. By the way, my solution is to move 'node_modules' to second position in the before: config.resolve.modules:["node_modules", "path/to/project/node_modules"] after config.resolve.modules:["path/to/project/node_modules", "node_modules"] |
For the ones hoping for a fix for webpack and when you
To fix
{
resolve: {
symlinks: true,
}
}
{
test: /\.(js|jsx|mjs)$/,
include: [paths.appSrc, paths.myPackage],
use: {
...
}
}
const resolveRealPathApp = relativePath => fs.realpathSync(process.cwd() + relativePath)
module.exports = {
...
myPackage: resolveRealPathApp('/node_modules/myPackage')
}; Catches: watchOptions: {
ignored: ignoredFiles(paths.appSrc),
} |
Has any progress been made on this issue? I was using symlinks as a way to share interfaces between my Firebase Cloud Functions project and its React frontend project, but was surprised to find that as soon as I added enums everything broke (similar to the issue that @ali-wetrill was having above). Unfortunately, all the workarounds above seem to rely on unmaintained stuff, with react-app-rewired, customize-cra, and craco all not supporting CRA 5.0. If not, does anyone have any alternative suggestions for how to achieve the same thing? |
It's a decades old trick to symlinks to a single source directory for multiple architecture builds. This issue has broken that for me. 👎 |
FWIW, I've added a small |
I've elaborated on this solution by using
This is what my script look like: "scripts": {
"watch-shared": "watch \"rm -rf src/shared && cp -a ../other-project/shared/ src/\" ../other-project/shared src/shared --ext ts",
"sync-shared": "rm -rf src/shared && cp -a ../other-project/shared/ src/",
"start": "run-p watch-shared start-react",
"start-react": "react-scripts start",
"build": "run-s sync-shared build-react",
"build-react": "react-scripts build",
"test": "run-p watch-shared test-react",
"test-react": "react-scripts test",
"eject": "react-scripts eject"
}
I don't recommend trying to re-use the |
On linux-like systems you might also be able to use |
If I add a symlink in my src directory to another directory, and then include files from that path, create-react-app gives an error:
I assume create-react-app wants to have this import already built/transpiled. I would expect this to be the case for imports outside the src directory (node_modules for example). But since the symlink resides in the src directory, I would assume create-react-app would fetch these files as if they were truly in src directory.
Is this a bug, or expected behaviour? It makes it really hard to extract common components.
The text was updated successfully, but these errors were encountered: