react-native icon indicating copy to clipboard operation
react-native copied to clipboard

[Packager] Configure the locations from which modules can be imported

Open mschwartz opened this issue 11 years ago • 43 comments

require() and import are really important features that deserve some love, IMO.

Forcing us to use relative paths in all our import/require statements is not ideal. It works only ok for the react demos that have a handful of files all in the root. For example, the Movie example in this repo:

image

The require on line 19 works because you've basically hardcoded require to search node_modules/ where react-native exists.

The require on line 26 forces you to put a ./ on the beginning of the path, and it works, but not ideally as I said.

Consider you want to actually break up this file: https://github.com/facebook/react-native/blob/master/Examples/Movies/SearchScreen.js

One file per component, even if they're private (for now). Reusability is the goal, no?

If you move this file into a directory called "components/", now you have to go and edit the require() statement to reflect the new path.

Things get really ugly if you want to organize your project into a more complex structure. Consider search/component1, search/component2, details/movie1, details/movie2, and so on. Now you're relative paths, if they are sharing code, are ../search/whatever, ../details/whatever. Moving these files around to reorganize your project now means you have to deduce what the new relative paths must be and you have to edit all those files.

I suggest you think about implementing a robust require() implementation. I suggest at least the following features:

require.paths array

This is an array of search paths used by require. It searches the paths in the order of the array. It is allowed by the CommonJS require specification.

Example:

// In your index.ios.js at the very top:
require.paths.unshift('search');
require.paths.unshift('movies');

Now you can simply require('component1) ANYWHERE in your source code and search/component1 will be used. You can move your files around without having to edit your require() statements in every one. Just change the require.paths.

Support directories

If you require('foo') and foo is a directory, you should:

  1. Look for index.js and use that to locate the module requested.
  2. THEN Look for package.json and use that to locate the module requested.
  3. THEN look for bower.json and use that to locate the module requested.
  4. THEN look for the module requested by filename (e.g. require('foo').bar means foo/bar.js)

Benefits

If you implement these changes, people will be easily able to share components via mechanisms other than npm. You will easily be able to copy components from one project to another without having to refactor the require() statements in each.

Please consider this.

mschwartz avatar Sep 28 '15 17:09 mschwartz

Do systems like Webpack and Browserify support require.paths? I thought Node deprecated that feature awhile ago too and asks for NODE_PATH. It's been a few years since I've looked into this so perhaps things have changed.

Generally the packager needs to be able to resolve requires statically so it can produce a bundle. So we could support NODE_PATH or a similar kind of configuration at compile-time but I don't know how we'd support require.paths because client code doesn't have the same capability as server code in this way.

ide avatar Sep 28 '15 18:09 ide

NODE_PATH would be fine.

However, I don't think there's an issue client vs. server.

On the client, you can still use search paths.

2015-09-28 at 11 14 am

Instead of modulesMap[id], you'd loop through require.paths and try modulesMap[require.paths[i] + id) until found. Or not found...

mschwartz avatar Sep 28 '15 18:09 mschwartz

This help?

http://stackoverflow.com/questions/27502608/resolving-require-paths-with-webpack

mschwartz avatar Sep 28 '15 18:09 mschwartz

Couple caveats to consider:

  1. NODE_PATH is processed only when Node starts. You cannot modify it at runtime. (i.e. everyone has to be very careful to set up their environment properly for all entry points. packager, tests, etc)
  2. A lot of existing tooling would not be not aware of this (linters, webpack, etc) and will need to add support for it.

Also, there's a great thread for and against this pattern over at https://gist.github.com/branneman/8048520, which might lend some more insight

nevir avatar Sep 28 '15 18:09 nevir

The key thing is that (some of) the configuration needs to happen at compile-time because we need to create a bundle. NODE_PATH and Webpack's resolve config meet this requirement... I prefer the latter because the config is more visible than NODE_PATH but they're isomorphic from what I can tell.

Another important point to consider is how this will interact with ES6 import and ES7 System. I believe they are compatible with a NODE_PATH-like option but something to keep in mind.

ide avatar Sep 28 '15 19:09 ide

NODE_PATH would be a huge win.

I was just looking at webpack myself and saw the resolvers configuration options. Another win.

mschwartz avatar Sep 28 '15 19:09 mschwartz

System.js

https://github.com/systemjs/systemjs/blob/master/docs/overview.md#paths-config

mschwartz avatar Sep 28 '15 20:09 mschwartz

Take a look at the ES7+ spec loader, too (System.js will layer on top of it): https://github.com/whatwg/loader

nevir avatar Sep 28 '15 21:09 nevir

Excellent. See 10.3.1.

node_modules is not in their tbd search path ...

FWIW

On Monday, September 28, 2015, Ian MacLeod [email protected] wrote:

Take a look at the ES7+ spec loader, too (System.js will layer on top of it): https://github.com/whatwg/loader

— Reply to this email directly or view it on GitHub https://github.com/facebook/react-native/issues/3099#issuecomment-143884737 .

mschwartz avatar Sep 28 '15 22:09 mschwartz

http://webpack.github.io/docs/configuration.html#resolve-alias

Read on in that link...

Read the through the comment thread on that gist linked by @nevir ...

Node's require is poorly implemented. No reason to have a bad require for react-native.

IMO

mschwartz avatar Oct 01 '15 00:10 mschwartz

Might be possible to implement an offline version of this: https://github.com/systemjs/systemjs/blob/master/docs/config-api.md#map

ide avatar Oct 01 '15 23:10 ide

I like it.

mschwartz avatar Oct 01 '15 23:10 mschwartz

Just a question: would support for symlinks help you out with this problem? I haven't read through all the material linked about different module systems, all I know is that with React Native being based on CommonJS (node) and relying on NPM it'll be quite the change to break from that. While that may or may not be inevitable in the future is not a question I'm looking to answer or claim I have answer to, but perhaps the symlink support is a more short term achievable goal.

JaapRood avatar Nov 11 '15 01:11 JaapRood

You can use an absolute path on imports/requires:

import {ProximaNovaText} from 'MyApp/src/components';
require('MyApp/src/utils/moment-twitter');

where 'MyApp' is whatever name you registered in your index.ios.js file

marcshilling avatar Nov 11 '15 01:11 marcshilling

Well, looks like this has improved slightly in latest versions. As long as your folder added to rootFolders have package.json inside it, you can use the name from that package.json instead of a relative path.

See my structure with React Native 0.15 below:

assets/
core/package.json (@g/core name in package.json)
platform/mobile/package.json (@g/mobile name in package.json)
platform/mobile/node_modules/react-native
platform/web/package.json (@g/web - ignored as not included in mobile app)

packager starts from platform/mobile with ../../core added to roots with a help of rn-cli.config.js that also works for bundle command:

const defaultConfig = require('react-native/local-cli/default.config.js');

module.exports {

  getProjectRoots() {
    const roots = defaultConfig.getProjectRoots();
    roots.unshift(path.resolve(__dirname, '../../assets'));
    roots.unshift(path.resolve(__dirname, '../../core'));
    return roots;
  }

};

I can see the paths getting transformed from:

require('../../core/redux/reducer.js')

to

require('@g/core/redux/reducer.js')

and

require('./index.ios.js')

to

require('@g/mobile/index.ios.js')

which basically means package name from package.json is used which works exactly as you would've npm link them all together. So who needs symlinks then?

@brentvatne @mkonicek is that how packager works or have I just entered an edge-case that I should not rely on?

Something is definitelly in the air since when I set up the same name for core and mobile (e.g. acme) I get:

{"type":"InternalError","message":"react-packager has encountered an internal error, please check your terminal error output for more details"}

Note Looks like the approach for assets is slightly different:

require('../../../../../assets/a.png')

is converted to

require('/Users/grabbou/project/assets/a.png')

However, when you have package.json in your assets as well (@g/assets name in package.json), you could write

require('@g/assets/a.png')

which is equivalent.

grabbou avatar Dec 10 '15 10:12 grabbou

Hey @mschwartz! Thanks for bringing this issue up. I'm closing this sine we're trying to focus Github issues on bugs, and this is potentially solved by @grabbou's solution. Feel free to submit a PR or add a Product Pains entry to get more attention on this issue.

jsierles avatar Mar 20 '16 17:03 jsierles

The ability to define import paths is an absolutely essential part of any programming environment that "has" even the vaguest notion of "import". Its absence from React Native is a bug-level deficiency. I request reopening this issue. Product Pains looks like a toy; I am unconvinced that it receives any actual attention.

rulatir avatar Apr 28 '16 18:04 rulatir

Have you seen my article on Medium how to define import paths? https://medium.com/@grabbou/a-cure-for-relative-requires-in-react-native-2b263cecf0f6 It works well :)

Also Product Pain was working really well recently and we closed one of the most up voted issues - see this for more details https://www.facebook.com/groups/react.native.community/permalink/759574700844777/

grabbou avatar Apr 28 '16 20:04 grabbou

It doesn't work well for inherited codebase with dozens of files, most of them importing several other files from the same codebase. Your solution would still require rewriting every last one of those 500+ import lines, it would just require rewriting them with something that only depends on the imported module's location and not on the importing module's location.

rulatir avatar Apr 28 '16 21:04 rulatir

@grabbou the problem with this solution is that it breaks intellisense, for example, in visual studio (don't know the rest of gui). Then it cannot find where is the file, which are the properties and worse of it, you cannot jump to class definition with cmd+click

miqmago avatar Apr 29 '16 15:04 miqmago