Skip to content
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

babel 7 configuration format #30

Closed
elmpp opened this issue May 16, 2018 · 16 comments
Closed

babel 7 configuration format #30

elmpp opened this issue May 16, 2018 · 16 comments

Comments

@elmpp
Copy link

elmpp commented May 16, 2018

Hi there,

I'm trying to bumble my way through to having a working babel7-based setup but there seems to be something wrong the moment i pull in "babel-plugin-inline-import-graphql-ast"

Here is my babel.config.js (this is now the babel7 method to specify a project-wide babel config, in lieu of .babelrc):

// https://github.com/babel/babel/pull/7358#issuecomment-388311941
module.exports = {
  overrides: [{
    test: '*',
    presets: [
      ['@babel/preset-env', {'node': 'current'}],
    ],
    plugins: [
      [
        "babel-plugin-inline-import",
        {
          extensions: [
            ".css"
          ]
        }
      ],
      "babel-plugin-inline-import-graphql-ast"
    ],
    env: {
      development: {
        presets: [
          "next/babel",
        ]
      },
      production: {
        presets: [
          [
            "next/babel",
            {
              ["preset-env"]: {
                targets: {
                  browsers: "> 5%"
                }
              }
            }
          ]
        ]
      },
      test: {
        presets: [
          [
            "next/babel",
            {
              ["preset-env"]: {
                modules: true
              }
            }
          ]
        ]
      }
    }
  }],
  ignore: [
    "/*.plain/"
  ]
}

Example usage of the graphql inlining:

# ---- https://github.com/apollographql/graphql-tag
#import "./Category3Fragment.graphql"
#import "./Category2Fragment.graphql"
#import "./Category1Fragment.graphql"


query Category1(
  $canonicalised_name: String,
  $category1__canonicalised_name: String,
) {
  category1 (
    canonicalised_name: $canonicalised_name,
    category1__canonicalised_name: $category1__canonicalised_name,
  ) {
      ...Category1Fragment
  }
}

Error text:

Module build failed: Error: Configuration contains explicit test/include/exclude checks, but no filename was passed to Babel
    at configFieldIsApplicable (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/config-chain.js:401:11)
    at configIsApplicable (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/config-chain.js:396:41)
    at forEach (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/config-chain.js:242:13)
    at Array.forEach (<anonymous>)
    at /Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/config-chain.js:239:42
    at buildRootChain (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/config-chain.js:90:20)
    at loadPrivatePartialConfig (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/partial.js:51:55)
    at loadFullConfig (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/config/full.js:43:39)
    at transformSync (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/lib/transform-sync.js:15:38)
    at buildVariableAST (/Users/matt/dev/partridge/frontend/node_modules/babel-plugin-inline-import-graphql-ast/build/index.js:87:58)
    at /Users/matt/dev/partridge/frontend/node_modules/babel-plugin-inline-import-graphql-ast/build/index.js:72:26
    at Array.map (<anonymous>)
    at buildReplacements (/Users/matt/dev/partridge/frontend/node_modules/babel-plugin-inline-import-graphql-ast/build/index.js:65:31)
    at PluginPass.exit (/Users/matt/dev/partridge/frontend/node_modules/babel-plugin-inline-import-graphql-ast/build/index.js:59:34)
    at newFn (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/node_modules/@babel/traverse/lib/visitors.js:237:21)
    at NodePath._call (/Users/matt/dev/partridge/frontend/node_modules/@babel/core/node_modules/@babel/traverse/lib/path/context.js:65:20)
@detrohutt
Copy link
Owner

Would you mind running npm list @babel/core and letting me know what version that outputs? (It could be different from what's in your package.json). Babel just released an update in the last day or two and I've not gotten around to seeing if there are any breaking changes that affect my plugin.

@loganfsmyth
Copy link

loganfsmyth commented May 16, 2018

This line https://github.com/detrohutt/babel-plugin-inline-import-graphql-ast/blob/678284600731bc77b632766f969a6033d9304700/plugin/index.js#L54 will attempt to load the user's babel.config.js file too, because it is not passing configFile: false when calling transformSync.

My recommendation would be to drop the usage of transformSync entirely.

export default ({ types: t }) => ({

should expand to

export default ({ types: t, template }) => ({

and then

function buildVariableAST(graphqlAST, importName) {
  const { ast } = transformSync(`var ${importName} = ${JSON.stringify(graphqlAST)}`, {
    ast: true
  })
  return ast.program.body[0]
}

can be

const buildAst = template(`var IMPORT_NAME = AST;`);
function buildVariableAST(graphqlAST, importName) {
  return buildAst({ 
    IMPORT_NAME: t.identifier(importName), 
    AST: t.valueToNode(graphqlAST),
  });
}

@detrohutt
Copy link
Owner

detrohutt commented May 16, 2018

Wow, thanks for taking the time to detail what needs to be done @loganfsmyth! Do you think this is likely to be a breaking change (major version bump) for my plugin? I mean do you think anyone would have been relying on their config being loaded by my plugin in some way?

I'm guessing no since I don't use anything from the config other than my own plugin's options?

@loganfsmyth
Copy link

Nope! It's a brand new feature in Babel 7, so I can't imagine anyone would be relying on it, and your code already skips reading .babelrc files since the JS snippet doesn't have a filename.

@elmpp
Copy link
Author

elmpp commented May 16, 2018

here are both npm's and yarn's outputs for @babel/core (there's something funky going on with npm's resolution):

Matthews-MacBook-Pro:frontend matt$ npm list @babel/core
frontend@0.1.0 /Users/matt/dev/partridge/frontend
└─┬ UNMET DEPENDENCY next@6.0.2
  └── UNMET DEPENDENCY @babel/core@7.0.0-beta.42

npm ERR! missing: next@6.0.2, required by frontend@0.1.0
npm ERR! missing: @babel/core@7.0.0-beta.42, required by next@6.0.2
Matthews-MacBook-Pro:frontend matt$ yarn list !$
yarn list @babel/core
yarn list v1.6.0
warning Filtering by arguments is deprecated. Please use the pattern option instead.
└─ @babel/core@7.0.0-beta.47
✨  Done in 0.64s.

Note i have the following in my package.json:

{
  "name": "frontend",
  "version": "0.1.0",
  "description": "Partridge Website",
  "main": "index.js",
  "dependencies": {
    "apollo-cache-inmemory": "^1.2.1",
    "apollo-client": "^2.3.1",
    "apollo-link-http": "^1.5.4",
    "classnames": "^2.2.5",
    "cookie-parser": "^1.4.3",
    "express": "^4.15.4",
    "flat-combine-reducers": "^0.1.2",
    "graphql": "^0.13.2",
    "graphql-tag": "^2.4.2",
    "material-ui": "^1.0.0-beta.10",
    "material-ui-icons": "^1.0.0-beta.5",
    "next": "^6.0.2",
    "next-routes": "^1.4",
    "react": "^16.3.2",
    "react-apollo": "^2.1.4",
    "react-dd-menu": "^2.0.2",
    "react-dom": "^16.3.2",
    "react-grid-layout": "^0.16.6",
    "react-proptype-conditional-require": "^1.0.4",
    "react-redux": "^5.0.6",
    "react-treeview": "^0.4.7",
    "redux": "^4.0.0",
    "redux-responsive": "^4.3.2",
    "redux-thunk": "^2.2.0",
    "reselect": "^3.0.1",
    "rimraf": "^2.6.2",
    "ua-parser-js": "^0.7.14",
    "yarn": "^1.6.0"
  },
  "devDependencies": {
    "@babel/node": "7.0.0-beta.44",
    "babel-plugin-inline-import": "^2.0.6",
    "babel-plugin-inline-import-graphql-ast": "^2.3.7",
    "enzyme": "^3.0.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "fkill": "^5.1.0",
    "graphql-tools": "^3.0.0",
    "jest": "23.0.0-beta.0",
    "jsdom": "^11.3.0",
    "portfinder": "^1.0.13",
    "react-addons-test-utils": "^15.6.2",
    "react-test-renderer": "^16.3.2"
  },
  "resolutions": {
    "@babel/core": "^7.0.0-beta.44",
    "@babel/node": "^7.0.0-beta.44"
  },
  "scripts": {
    "test": "jest",
    "test-watch": "jest --watch --no-cache",
    "dev": "rimraf ./node_modules/.cache; rimraf ./.next/*; babel-node server.js",
    "dev-test": "node server-test.js",
    "build": "next build",
    "start": "rimraf ./node_modules/.cache; NODE_ENV=production babel-node server.js"
  },
  "repository": {
    "type": "git",
    "url": "git+ssh://git@somewhere.git"
  },
  "keywords": [
    "reactjs",
    "partridge"
  ],
  "author": "wrgwrgggge@gmail.com",
  "license": "ISC",
  "homepage": "https://somewhere/frontend#readme"
}

@detrohutt
Copy link
Owner

@elmpp Thanks! It looks like you're using the newest one. I just checked the changelog and it doesn't look like it should have affected my plugin directly. Hopefully what Logan suggested will fix it for you. I'm working on making that change now and I'll ping you here when I've published the new version.

@loganfsmyth I didn't see anything in the babel-handbook about pulling template from the params.. is that new with Babel 7? Would that be a breaking change for people using my plugin with Babel 6? Should I use the babel-template package mentioned in the handbook instead? 😕

@loganfsmyth
Copy link

I didn't see anything in the babel-handbook about pulling template from the params.. is that new with Babel 7?

Nope! That's been there for ages. The first argument includes everything you get from importing babel-core itself, along with some extra stuff. That said, if you want to avoid it to keep things minimal you could also do

function buildVariableAST(graphqlAST, importName) {
  return t.variableDeclaration("var", [
    t.variableDeclarator(t.identifier(importName), t.valueToNode(graphqlAST)),
  ]);
}

@detrohutt
Copy link
Owner

@loganfsmyth Amazing. I wish I'd have known about t.valueToNode when I was creating this plugin. It'd have saved me many hours of frustration. Thank you for all your help!

@detrohutt
Copy link
Owner

@elmpp I just published babel-plugin-inline-import-graphql-ast@2.3.8. Please try it out and let me know if that fixes your issue.

@elmpp
Copy link
Author

elmpp commented May 17, 2018

it works! Thank you very much (also to @loganfsmyth)

@elmpp elmpp closed this as completed May 17, 2018
@detrohutt
Copy link
Owner

@elmpp Awesome! Thanks for reporting back. :)

@detrohutt
Copy link
Owner

@loganfsmyth I'm working on a new feature to reduce the size of the output code and I ended up with the code below which reduces output size by about 35% but it requires runtime processing and seems unnecessarily complex.. is there a way to take advantage of the minified option of babel-generator from within a plugin? Or would the user need to set that option at a higher level?

function buildVariableAST(graphqlAST, importName) {
  const templateOptions = { placeholderPattern: /IMPORT_NAME|AST_EXPRESSION/ }
  const buildAst = template(`var IMPORT_NAME = Function(AST_EXPRESSION)()`, templateOptions)

  const minifyOptions = { compress: false, mangle: true }
  const { code } = minify(`var code=${JSON.stringify(graphqlAST)}`, minifyOptions)
  const minifiedASTString = code.replace('var code=', '').replace(';', '')

  return buildAst({
    IMPORT_NAME: t.identifier(importName),
    AST_EXPRESSION: t.stringLiteral('return (' + minifiedASTString + ')')
  })
}

@loganfsmyth
Copy link

@detrohutt The best you can do on the side of the transform itself would be

const node = t.valueToNode(graphqlAST);
node._compact = true;

which will force-enable the concise option and restrict the output to a single line with only single-space spacing. Not quite as small as the minified but should still be a good way there.

@detrohutt
Copy link
Owner

@loganfsmyth Amazing! Thanks for being so available for my questions. It's great to have such a wellspring of knowledge on call when I get stuck or just feel like I'm probably doing something sub-par. And thanks for all your great work on Babel!

@detrohutt detrohutt reopened this Jun 4, 2018
@detrohutt
Copy link
Owner

@loganfsmyth That worked beautifully. Mind if I credit you in the CHANGELOG/Release notes/Twitter announcement?

@loganfsmyth
Copy link

If you'd like, don't let me stop you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants