Skip to content

Commit

Permalink
Optionally output eager es modules
Browse files Browse the repository at this point in the history
I have two problem which can be solved with this change

1. Rollup handles only es modules. To handle commonjs there is a plugin
which converts it into esm. Though it always skips module if
import/export statements are found. As a result I get runtime error:
"require is not defined".

To workaround this I wrote custom plugin. Though it would be cool to
have proper solution out of the box.

```js
{
  name: 'relay-generated',
  transform(code) {
    // convert __generated__ requires into imports
    // remove after relay-compiler will be able to emit esm
    if (code.includes('__generated__')) {
      let i = -1;
      const paths = [];
      const processed = code.replace(
        /require\((.+__generated__.+)\)/g,
        (req, pathString) => {
          i += 1;
          paths.push(pathString);
          return `__generated__${i}`;
        },
      );
      const imports = paths.map(
        (p, i) => `import __generated__${i} from ${p};\n`,
      );
      return {
        code: imports.join('') + processed,
      };
    }
  },
},
```

2. Another problem is flow bug (facebook/flow#7444) which treats all not existent types as any.
This leads to many type unsafe places.

```js
import type {NotExistentType} from './__generated__/MyQuery.graphql';

type Props = {|
  my: NotExistentType
|}
```
  • Loading branch information
TrySound committed Jan 11, 2020
1 parent a3fcfa3 commit 05f4b02
Show file tree
Hide file tree
Showing 8 changed files with 885 additions and 10 deletions.
4 changes: 4 additions & 0 deletions packages/babel-plugin-relay/BabelPluginRelay.js
Expand Up @@ -27,6 +27,10 @@ export type RelayPluginOptions = {
haste?: boolean,
// Check this global variable before validation.
isDevVariable?: string,

// enable generating eager es modules for modern runtime
eagerESModules?: boolean,

// Directory as specified by artifactDirectory when running relay-compiler
artifactDirectory?: string,
...
Expand Down
@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+relay
*/

'use strict';

const transformerWithOptions = require('./transformerWithOptions');

const {generateTestsFromFixtures} = require('relay-test-utils-internal');

generateTestsFromFixtures(
`${__dirname}/fixtures-modern`,
transformerWithOptions({
eagerESModules: true,
}),
);

0 comments on commit 05f4b02

Please sign in to comment.