Giter Club home page Giter Club logo

babel-plugin-inline-import's Introduction

Babel Inline Import Build Status

Babel plugin to add the opportunity to use import with raw/literal content
It is good e.g. for importing *.graphql files into your code.

Examples

Before (without Babel-Inline-Import):

// server.js

// bad syntax highlighting, no syntax checking
const typeDefinitions = `
type Query {
  testString: String
}
schema {
  query: Query
}
`;

graphQLServer({
  schema: [typeDefinitions],
  ...
});

Now (with Babel-Inline-Import):

// /some/schema.graphql
type Query {
  testString: String
}
schema {
  query: Query
}
// server.js
import schema from '/some/schema.graphql';

graphQLServer({
  schema: [schema],
  ...
});

Note: both cases are equivalent and will result in similar code after Babel transpile them. Check How it works section for details.

Install

npm install babel-plugin-inline-import --save-dev

Use

Add a .babelrc file and write:

{
  "plugins": [
    "babel-plugin-inline-import"
  ]
}

or pass the plugin with the plugins-flag on CLI

babel-node myfile.js --plugins babel-plugin-inline-import

By default, Babel-Inline-Import is compatible with the following file extensions:

  • .raw
  • .text
  • .graphql

Customize

If you want to enable different file extensions, you can define them in your .babelrc file

{
  "plugins": [
    ["babel-plugin-inline-import", {
      "extensions": [
        ".json",
        ".sql"
      ]
    }]
  ]
}

How it works

It inserts the content of the imported file directly into the importing file, assigning it to a variable with the same identifier of the import statement, thus replacing the import statement and the file path by its resulting raw content (no parsing occurs).

Caveats

Babel does not track dependency between imported and importing files after the transformation is made. Therefore, you need to change the importing file in order to see your changes in the imported file spread. To overcome this:

  • If you are using babel-node or babel-register, you can disable babel cache (BABEL_DISABLE_CACHE=1).
  • If you are using webpack with babel-loader, you can use babel-inline-import-loader.
  • An alternative library for webpack is raw-loader. Advantage = detects changes to imported file w/o additional config or losing babel's cache. Disadvantage: maintain 2 separate configs. E.g. 1) one w/ raw-loader for webpack, and 2) another one for babel using babel-plugin-inline-import. E.g. if you use a create-react-app / CRA based React app, you may have 1) for yarn start / webpack and 2) for yarn test / babel. For CRA, craco and craco-raw-loader may help.

Also make sure that your task runner is watching for changes in the imported file as well. You can see it working here.

Motivate

If you like this project just give it a star :) I like stars.

babel-plugin-inline-import's People

Contributors

aldeed avatar amilajack avatar arunoda avatar axe312ger avatar cristian-spiescu avatar degr avatar dependabot[bot] avatar elliottsj avatar fredericheem avatar jirutka avatar mastilver avatar zvictor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

babel-plugin-inline-import's Issues

Ability to imports graphql file in graphql file

Hello

Thanks for creating this plugin :)

Can this plugin have ability to import graphql files inside the graphql file?
Like adding a additional ability for importing .gql and .graphql files.

Like:

./attachment.graphql

fragment attachmentFragment on Attachment {
  id
  url
  thumbnailUrl
}

./user.graphql

#import "./attachment.graphql"

fragment userFragment on User {
  id
  nick
  avatar {
    ...attachmentFragment
  }
}

Expected output would be like:

fragment userFragment on User {
  id
  nick
  avatar {
    ...attachmentFragment
  }
}
fragment attachmentFragment on Attachment {
  id
  url
  thumbnailUrl
}

Export doesn't work

for example, I have a file: modules/my-module/index.js, where

export { default as schema } from './schema.graphqls';

and get

 var err = new SyntaxError(message);
            ^

Of course, I can do that

import schema from './schema.graphqls';
export { schema };

but it doesn't look good

Documentation on Cache with `babel-register`

@zvictor,

Thanks for this useful plugin!

I recently ran into caching issue as well, and it took quite some search to figure out what is happening: #7 #15

Description of the problem

when used with babel-register as in node -r babel-register index.js, some how nod always load an older version of the markdown file I'm reading. Even after restarting the node process.

PR Suggestion

Can we:

  1. make the https://github.com/Quadric/babel-plugin-inline-import#caveats session more prominent in the README?
  2. and more importantly, the current explanation in the caveat session doesn't really explain what importing and imported are. I still don't know what is happening and why babel-register has problem with cached file content event after restarting the node process. Would you mind explain what is causing the problem above?

Best Regards

Mime-type warning in Firefox

I use the v3 plugin with webpack. The Firefox browser console throws a warning stating my js is loaded, but has a wrong mime-type: Het script van ‘http://localhost:3000/’ is geladen, hoewel het MIME-type ervan (‘text/html’) geen geldig JavaScript-MIME-type is.

The warning translates to The script is loaded, although its MIME-type (‘text/html’) is not a valid JavaScript-MIME-type.

The .babelrc:

{
  "presets": [ "@babel/preset-env"],
  "plugins": [
    ["babel-plugin-inline-import", {"extensions": [".html"]}]
  ]
}

The javascript:

import html from './template.html';
console.log(html);

My code works. Webkit browsers don't show this warning, Firefox does though.

Looking for maintainers!

We am looking for someone who could do just the most basic maintenance of the project.

I keep getting requests to publish new versions, but I don't even use this plugin anymore, thus it feels wrong to me to judge what should be added to it or not. 😕

Is there anyone who like to take the lead here?

Compatibility with Flow type checker

Currently, using babel-plugin-inline-import results in import errors for me:

src/file.js:4
  4: import bla from "./bla.txt";
                     ^^^^^^^^^^^ ./bla.txt. Required module not found

Is there a way to use this plugin that's compatible with Flow?

caching issue

There seems to be some sort of caching going on. It doesn't seem to realize the .graphql file has changed unless I rename the filename.

I've had this happen on 3 separate projects.

can not work with react native

hi, I've setup .babelrc like this:

{
    "presets": ["module:metro-react-native-babel-preset"],
    "plugins": [
        [
            "inline-import",
            {
                "extensions": [".md", ".text", ".txt"]
            }
        ],
        [
            "module-resolver",
            {
                "root": ["./src"],
                "alias": {}
            }
        ]
    ]
}

But cli throw error as below:

error: bundling failed: Error: Unable to resolve module `./button.spec.md` from `/Users/jess/jess/renrendai/source/rrd-react-native/storybook/stories/button.story.js`: The module `./button.spec.md` could not be found from `/Users/jess/jess/renrendai/source/rrd-react-native/storybook/stories/button.story.js`. Indeed, none of these files exist:
  * `/Users/jess/jess/renrendai/source/rrd-react-native/storybook/stories/button.spec.md(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
  * `/Users/jess/jess/renrendai/source/rrd-react-native/storybook/stories/button.spec.md/index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)`
    at ModuleResolver.resolveDependency (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:120:15)
    at ResolutionRequest.resolveDependency (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:49:18)
    at DependencyGraph.resolveDependency (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/node-haste/DependencyGraph.js:218:16)
    at Object.resolve (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/lib/transformHelpers.js:141:30)
    at dependencies.map.result (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/DeltaBundler/traverseDependencies.js:373:31)
    at Array.map (<anonymous>)
    at resolveDependencies (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/DeltaBundler/traverseDependencies.js:369:18)
    at /Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/DeltaBundler/traverseDependencies.js:188:33
    at Generator.next (<anonymous>)
    at step (/Users/jess/jess/renrendai/source/rrd-react-native/node_modules/metro/src/DeltaBundler/traverseDependencies.js:298:30)
 BUNDLE  [android, dev] ./index.js ░░░░░░░░░░░░░░░░ 0.0% (0/1), failed.

does not work when using react-native start --projectRoot

if you use react-native start --projectRoot storybook and have a local import in that folder that uses babel-plugin-inline-import, the resolved path will be wrong and the import will fail.

e.g. in file storybook/storybook.js you have this:

import schema from './schema.graphql'

this will throw

 bundling failed: Error: Path './schema.graphql' could not be found for '/path/to/project/storybook.js'

The path /path/to/project/storybook.js is suspicious, because this does not exist. it should be /path/to/project/storybook/storybook.js

so i think the resolving of files is wrong

Comment that babel-inline-import-loader relies on is not generated

I have BABEL_DISABLE_CACHE=1 set and I've tried setting cacheDirectory: false and neither option helps (as expected since the comment is missing from the output).

.babelrc contents:

{
  "presets": [
    [
      "env", {
      "targets": {
        "browsers": [
          "last 2 Chrome versions"
        ]
      },
      "modules": "umd"
    }]
  ],
  "plugins": [
    [
      "babel-plugin-inline-import", {
        "extensions": [
          ".css"
        ]
      }
    ],
    [
      "transform-incremental-dom", {
        "moduleSource": "incremental-dom"
      }
    ],
    ["transform-class-properties"]
  ],
  "env": {
    "test": {
      "plugins": [
        ["istanbul", {
          "exclude": [
            "tests/**/*"
          ]
        }]
      ]
    },
    "production": {
      "presets": ["babili"]
    }
  }
}

webpack.config.js:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './docs/index.js',
  devtool: 'inline-source-map',
  output: {
    path: __dirname + '/docs/generated',
    filename: 'docs.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          'babel-inline-import-loader',
          'babel-loader'
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'docs/template.html'
    })
  ]
}

input code:

import Component from '../../component'
import styles from './styles.css'

customElements.define('wc-button', class WcButton extends Component {
  renderCss () {
    super.renderCss()
    return (
      <style>
        {styles}
      </style>
    )
  }

  render () {
    return <button><slot /></button>
  }
})

relevant output:

  const styles = 'button {\n  background: red;\n}\n';

  customElements.define('wc-button', class WcButton extends _component2.default {
    renderCss() {
      super.renderCss();
      (0, _incrementalDom.elementOpen)('style');

      _renderArbitrary(styles);

      return (0, _incrementalDom.elementClose)('style');
    }

    render() {
      (0, _incrementalDom.elementOpen)('button');
      (0, _incrementalDom.elementVoid)('slot');
      return (0, _incrementalDom.elementClose)('button');
    }
  });

The "extensions" option doesn't work

OS: Windows 10
I'm running npm run dev from the command-line.

package.json:

{
  ...
  "scripts": {
    "dev": "nodemon ./server.js --watch ./ --exec babel-node"
  },
  ...
}

babel.rc:

{
  "presets": ["es2015"],
  "plugins": ["babel-plugin-inline-import", {
    "extensions": [".gql"]
  }]
}

Error:

...\node_modules\babel-core\lib\transformation\plugin.js:131
      throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
      ^

Error: Plugin 1 specified in "...\\.babelrc" provided an invalid property of "extensions"
    at Plugin.init (...\node_modules\babel-core\lib\transformation\plugin.js:131:13)
    at Function.normalisePlugin (...\node_modules\babel-core\lib\transformation\file\options\option-manager.js:148:12)
    at ...\node_modules\babel-core\lib\transformation\file\options\option-manager.js:180:30
    at Array.map (native)
    at Function.normalisePlugins (...\node_modules\babel-core\lib\transformation\file\options\option-manager.js:154:20)
    at OptionManager.mergeOptions (...\node_modules\babel-core\lib\transformation\file\options\option-manager.js:229:36)
    at OptionManager.init (...\node_modules\babel-core\lib\transformation\file\options\option-manager.js:374:12)
    at compile (...\node_modules\babel-register\lib\node.js:103:45)
    at loader (...\node_modules\babel-register\lib\node.js:144:14)
    at Object.require.extensions.(anonymous function) [as .js] (...\node_modules\babel-register\lib\node.js:154:7) [nodemon] app crashed - waiting for file changes before starting...

limit to some paths only

I would like to inline the json file in react-intl/local-data/*.js
Is there an option to limit babel-inline to just this folder?

"debugger" statement in build/index.js when installing from npm

Hi and thanks for this useful Babel plugin!

I am having trouble debugging my Node graphql server app because the build/index.js file in the npm installation has a debugger; statement in line 21 which is causing my debugger to stop there for every import statement I have that the plugin is configured to handle.

Can you please re-publish to npm? The debugger; statement isn't in your source code on GitHub so it seems to me it was a mistake that the last published version had it in there and you've since removed it from the source but didn't publish since?

Schema is cached after first run

Hi @zvictor,

Thank you for your work, that's a nice plugin and works great, but I think I've spotted a problem. A schema files are cached after first run and will not updated unless you remove ~/.babel.json file.

Allow direct import of file

importing a file without assigning it to a variable causes an error TypeError: Cannot read property 'local' of undefined

import './example.txt';

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.