pax_global_header 0000666 0000000 0000000 00000000064 13636021350 0014511 g ustar 00root root 0000000 0000000 52 comment=0736c6b622bf5fe68f404085df216312dc25e2be
babel-plugin-preval-5.0.0/ 0000775 0000000 0000000 00000000000 13636021350 0015343 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/.all-contributorsrc 0000664 0000000 0000000 00000010721 13636021350 0021175 0 ustar 00root root 0000000 0000000 {
"projectName": "babel-plugin-preval",
"projectOwner": "kentcdodds",
"imageSize": 100,
"commit": false,
"contributorsPerLine": 7,
"repoHost": "https://github.com",
"repoType": "github",
"skipCi": false,
"files": [
"README.md"
],
"contributors": [
{
"login": "kentcdodds",
"name": "Kent C. Dodds",
"avatar_url": "https://avatars.githubusercontent.com/u/1500684?v=3",
"profile": "https://kentcdodds.com",
"contributions": [
"code",
"doc",
"infra",
"test"
]
},
{
"login": "mattphillips",
"name": "Matt Phillips",
"avatar_url": "https://avatars3.githubusercontent.com/u/5610087?v=3",
"profile": "http://mattphillips.io",
"contributions": [
"code",
"doc",
"test"
]
},
{
"login": "philipodev",
"name": "Philip Oliver",
"avatar_url": "https://avatars1.githubusercontent.com/u/28024000?v=3",
"profile": "https://twitter.com/philipodev",
"contributions": [
"bug"
]
},
{
"login": "sorin-davidoi",
"name": "Sorin Davidoi",
"avatar_url": "https://avatars2.githubusercontent.com/u/2109702?v=3",
"profile": "https://toot.cafe/@sorin",
"contributions": [
"bug",
"code",
"test"
]
},
{
"login": "infiniteluke",
"name": "Luke Herrington",
"avatar_url": "https://avatars4.githubusercontent.com/u/1127238?v=4",
"profile": "https://github.com/infiniteluke",
"contributions": [
"example"
]
},
{
"login": "luftywiranda13",
"name": "Lufty Wiranda",
"avatar_url": "https://avatars4.githubusercontent.com/u/22868432?v=4",
"profile": "http://instagram.com/luftywiranda13",
"contributions": [
"code"
]
},
{
"login": "obartra",
"name": "Oscar",
"avatar_url": "https://avatars0.githubusercontent.com/u/3877773?v=4",
"profile": "http://obartra.github.io",
"contributions": [
"code",
"test"
]
},
{
"login": "pro-nasa",
"name": "pro-nasa",
"avatar_url": "https://avatars1.githubusercontent.com/u/14310216?v=4",
"profile": "https://github.com/pro-nasa",
"contributions": [
"doc"
]
},
{
"login": "sergeybekrin",
"name": "Sergey Bekrin",
"avatar_url": "https://avatars0.githubusercontent.com/u/9248479?v=4",
"profile": "http://bekrin.me",
"contributions": []
},
{
"login": "maurobringolf",
"name": "Mauro Bringolf",
"avatar_url": "https://avatars0.githubusercontent.com/u/18613301?v=4",
"profile": "https://maurobringolf.ch",
"contributions": [
"code",
"test"
]
},
{
"login": "xjlim",
"name": "Joe Lim",
"avatar_url": "https://avatars1.githubusercontent.com/u/10875678?v=4",
"profile": "https://joelim.me",
"contributions": [
"code"
]
},
{
"login": "marzelin",
"name": "Marcin Zielinski",
"avatar_url": "https://avatars3.githubusercontent.com/u/13483453?v=4",
"profile": "https://github.com/marzelin",
"contributions": [
"code"
]
},
{
"login": "tleunen",
"name": "Tommy",
"avatar_url": "https://avatars3.githubusercontent.com/u/1972567?v=4",
"profile": "http://www.tommyleunen.com",
"contributions": [
"code"
]
},
{
"login": "PlayMa256",
"name": "Matheus Gonçalves da Silva",
"avatar_url": "https://avatars0.githubusercontent.com/u/831308?v=4",
"profile": "https://github.com/PlayMa256",
"contributions": [
"doc"
]
},
{
"login": "jdorfman",
"name": "Justin Dorfman",
"avatar_url": "https://avatars1.githubusercontent.com/u/398230?v=4",
"profile": "https://stackshare.io/jdorfman/decisions",
"contributions": [
"fundingFinding"
]
},
{
"login": "AndrewRot",
"name": "Andrew Rottier",
"avatar_url": "https://avatars2.githubusercontent.com/u/12818861?v=4",
"profile": "https://github.com/AndrewRot",
"contributions": [
"doc"
]
},
{
"login": "MichaelDeBoey",
"name": "Michaël De Boey",
"avatar_url": "https://avatars3.githubusercontent.com/u/6643991?v=4",
"profile": "https://michaeldeboey.be",
"contributions": [
"code"
]
}
]
}
babel-plugin-preval-5.0.0/.gitattributes 0000664 0000000 0000000 00000000023 13636021350 0020231 0 ustar 00root root 0000000 0000000 * text=auto eol=lf
babel-plugin-preval-5.0.0/.github/ 0000775 0000000 0000000 00000000000 13636021350 0016703 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/.github/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000001674 13636021350 0021420 0 ustar 00root root 0000000 0000000
- `babel-plugin-preval` version:
- `node` version:
- `npm` (or `yarn`) version:
Relevant code or config
```javascript
```
What you did:
What happened:
Reproduction repository:
Problem description:
Suggested solution:
babel-plugin-preval-5.0.0/.github/PULL_REQUEST_TEMPLATE.md 0000664 0000000 0000000 00000001521 13636021350 0022503 0 ustar 00root root 0000000 0000000
**What**:
**Why**:
**How**:
babel-plugin-preval-5.0.0/.gitignore 0000664 0000000 0000000 00000000205 13636021350 0017330 0 ustar 00root root 0000000 0000000 node_modules
coverage
dist
.DS_Store
# these cause more harm than good
# when working with contributors
package-lock.json
yarn.lock
babel-plugin-preval-5.0.0/.huskyrc.js 0000664 0000000 0000000 00000000056 13636021350 0017450 0 ustar 00root root 0000000 0000000 module.exports = require('kcd-scripts/husky')
babel-plugin-preval-5.0.0/.npmrc 0000664 0000000 0000000 00000000044 13636021350 0016461 0 ustar 00root root 0000000 0000000 registry=http://registry.npmjs.org/
babel-plugin-preval-5.0.0/.prettierignore 0000664 0000000 0000000 00000000033 13636021350 0020402 0 ustar 00root root 0000000 0000000 node_modules
coverage
dist
babel-plugin-preval-5.0.0/.prettierrc.js 0000664 0000000 0000000 00000000061 13636021350 0020137 0 ustar 00root root 0000000 0000000 module.exports = require('kcd-scripts/prettier')
babel-plugin-preval-5.0.0/.travis.yml 0000664 0000000 0000000 00000000457 13636021350 0017462 0 ustar 00root root 0000000 0000000 language: node_js
cache: npm
notifications:
email: false
node_js:
- 10.0.0
- 12
- node
install: npm install
script:
- npm run validate
- npx codecov@3
branches:
only:
- master
- beta
jobs:
include:
- stage: release
node_js: 12
script: kcd-scripts travis-release
babel-plugin-preval-5.0.0/CHANGELOG.md 0000664 0000000 0000000 00000000273 13636021350 0017156 0 ustar 00root root 0000000 0000000 # CHANGELOG
The changelog is automatically updated using
[semantic-release](https://github.com/semantic-release/semantic-release). You
can see it on the [releases page](../../releases).
babel-plugin-preval-5.0.0/CONTRIBUTING.md 0000664 0000000 0000000 00000003366 13636021350 0017604 0 ustar 00root root 0000000 0000000 # Contributing
Thanks for being willing to contribute!
**Working on your first Pull Request?** You can learn how from this _free_
series [How to Contribute to an Open Source Project on GitHub][egghead]
## Project setup
1. Fork and clone the repo
2. `$ npm install` to install dependencies
3. `$ npm run validate` to validate you've got it working
4. Create a branch for your PR
> Tip: Keep your `master` branch pointing at the original repository and make
> pull requests from branches on your fork. To do this, run:
>
> ```
> git remote add upstream https://github.com/kentcdodds/babel-plugin-preval
> git fetch upstream
> git branch --set-upstream-to=upstream/master master
> ```
>
> This will add the original repository as a "remote" called "upstream," Then
> fetch the git information from that remote, then set your local `master`
> branch to use the upstream master branch whenever you run `git pull`. Then you
> can make all of your pull request branches based on this `master` branch.
> Whenever you want to update your version of `master`, do a regular `git pull`.
## Committing and Pushing changes
Please make sure to run the tests before you commit your changes. You can run
`npm run test:update` which will update any snapshots that need updating. Make
sure to include those changes (if they exist) in your commit.
## Help needed
Please checkout the [the open issues][issues]
Also, please watch the repo and respond to questions/bug reports/feature
requests! Thanks!
[egghead]: https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github
[all-contributors]: https://github.com/all-contributors/all-contributors
[issues]: https://github.com/kentcdodds/babel-plugin-preval/issues
babel-plugin-preval-5.0.0/LICENSE 0000664 0000000 0000000 00000002067 13636021350 0016355 0 ustar 00root root 0000000 0000000 The MIT License (MIT)
Copyright (c) 2017 Kent C. Dodds
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
babel-plugin-preval-5.0.0/README.md 0000664 0000000 0000000 00000047067 13636021350 0016640 0 ustar 00root root 0000000 0000000
babel-plugin-preval
Pre-evaluate code at build-time
---
[![Build Status][build-badge]][build]
[![Code Coverage][coverage-badge]][coverage]
[![version][version-badge]][package]
[![downloads][downloads-badge]][npmtrends]
[![MIT License][license-badge]][license]
[](#contributors-)
[![PRs Welcome][prs-badge]][prs]
[![Code of Conduct][coc-badge]][coc]
[![Babel Macro][macros-badge]][babel-plugin-macros]
[![Examples][examples-badge]][examples]
## The problem
You need to do some dynamic stuff, but don't want to do it at runtime. Or maybe
you want to do stuff like read the filesystem to get a list of files and you
can't do that in the browser.
## This solution
This allows you to specify some code that runs in Node and whatever you
`module.exports` in there will be swapped. For example:
```js
const x = preval`module.exports = 1`
// ↓ ↓ ↓ ↓ ↓ ↓
const x = 1
```
Or, more interestingly:
```javascript
const x = preval`
const fs = require('fs')
const val = fs.readFileSync(__dirname + '/fixture1.md', 'utf8')
module.exports = {
val,
getSplit: function(splitDelimiter) {
return x.val.split(splitDelimiter)
}
}
`
// ↓ ↓ ↓ ↓ ↓ ↓
const x = {
val: '# fixture\n\nThis is some file thing...\n',
getSplit: function getSplit(splitDelimiter) {
return x.val.split(splitDelimiter)
},
}
```
There's also `preval.require('./something')` and
`import x from /* preval */ './something'` (which can both take some arguments)
or add `// @preval` comment at the top of a file.
See more below.
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Template Tag](#template-tag)
- [import comment](#import-comment)
- [preval.require](#prevalrequire)
- [preval file comment (`// @preval`)](#preval-file-comment--preval)
- [Exporting a function](#exporting-a-function)
- [Configure with Babel](#configure-with-babel)
- [Via `.babelrc` (Recommended)](#via-babelrc-recommended)
- [Via CLI](#via-cli)
- [Via Node API](#via-node-api)
- [Use with `babel-plugin-macros`](#use-with-babel-plugin-macros)
- [Examples](#examples)
- [Notes](#notes)
- [FAQ](#faq)
- [How is this different from prepack?](#how-is-this-different-from-prepack)
- [How is this different from webpack loaders?](#how-is-this-different-from-webpack-loaders)
- [Inspiration](#inspiration)
- [Related Projects](#related-projects)
- [Other Solutions](#other-solutions)
- [Issues](#issues)
- [🐛 Bugs](#-bugs)
- [💡 Feature Requests](#-feature-requests)
- [Contributors ✨](#contributors-)
- [LICENSE](#license)
## Installation
This module is distributed via [npm][npm] which is bundled with [node][node] and
should be installed as one of your project's `devDependencies`:
```
npm install --save-dev babel-plugin-preval
```
## Usage
Important notes:
1. All code run by `preval` is _not_ run in a sandboxed environment
2. All code _must_ run synchronously.
3. Code that is run by preval is not transpiled so it must run natively in the
version of node you're running. (cannot use es modules).
> You may like to watch
> [this YouTube video](https://www.youtube.com/watch?v=1queadQ0048&list=PLV5CVI1eNcJgCrPH_e6d57KRUTiDZgs0u)
> to get an idea of what preval is and how it can be used.
### Template Tag
**Before**:
```javascript
const greeting = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
```
**After** (assuming `greeting.txt` contains the text: `"Hello world!"`):
```javascript
const greeting = 'Hello world!'
```
`preval` can also handle _some_ simple dynamic values as well:
**Before**:
```javascript
const name = 'Bob Hope'
const person = preval`
const [first, last] = require('./name-splitter')(${name})
module.exports = {first, last}
`
```
**After** (assuming `./name-splitter` is a function that splits a name into
first/last):
```javascript
const name = 'Bob Hope'
const person = {first: 'Bob', last: 'Hope'}
```
### import comment
**Before**:
```javascript
import fileList from /* preval */ './get-list-of-files'
```
**After** (depending on what `./get-list-of-files does`, it might be something
like):
```javascript
const fileList = ['file1.md', 'file2.md', 'file3.md', 'file4.md']
```
You can also provide arguments which themselves are prevaled!
**Before**:
```javascript
import fileList from /* preval(3) */ './get-list-of-files'
```
**After** (assuming `./get-list-of-files` accepts an argument limiting how many
files are retrieved:
```javascript
const fileList = ['file1.md', 'file2.md', 'file3.md']
```
### preval.require
**Before**:
```javascript
const fileLastModifiedDate = preval.require('./get-last-modified-date')
```
**After**:
```javascript
const fileLastModifiedDate = '2017-07-05'
```
And you can provide _some_ simple dynamic arguments as well:
**Before**:
```javascript
const fileLastModifiedDate = preval.require(
'./get-last-modified-date',
'../../some-other-file.js',
)
```
**After**:
```javascript
const fileLastModifiedDate = '2017-07-04'
```
### preval file comment (`// @preval`)
Using the preval file comment will update a whole file to be evaluated down to
an export.
Whereas the above usages (assignment/import/require) will only preval the scope
of the assignment or file being imported.
**Before**:
```javascript
// @preval
const id = require('./path/identity')
const one = require('./path/one')
const compose = (...fns) => fns.reduce((f, g) => a => f(g(a)))
const double = a => a * 2
const square = a => a * a
module.exports = compose(square, id, double)(one)
```
**After**:
```javascript
module.exports = 4
```
## Exporting a function
If you export a function from a module that you're prevaling (whether using
`preval.require` or the import comment), then that function will be called and
whatever is returned will be the prevaled value.
It's important to know this if you want to have the prevaled value itself be a
function:
**Example**:
```js
// example-module.js
const fn = message => `The message is: ${message}`
module.exports = () => fn
```
**Usage of preval**:
```js
const theFn = preval.require('./example-module.js')
```
**Generated code**:
```js
const theFn = message => `The message is: ${message}`
```
## Configure with Babel
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["preval"]
}
```
### Via CLI
```sh
babel --plugins preval script.js
```
### Via Node API
```javascript
require('babel-core').transform('code', {
plugins: ['preval'],
})
```
## Use with `babel-plugin-macros`
Once you've
[configured `babel-plugin-macros`](https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/user.md)
you can import/require the preval macro at `babel-plugin-preval/macro`. For
example:
```javascript
import preval from 'babel-plugin-preval/macro'
const one = preval`module.exports = 1 + 2 - 1 - 1`
```
> You could also use [`preval.macro`][preval.macro] if you'd prefer to type less
> 😀
## Examples
- [Mastodon](https://github.com/tootsuite/mastodon/pull/4202) saved 40kb
(gzipped) using `babel-plugin-preval`
- [glamorous-website](https://github.com/kentcdodds/glamorous-website/pull/235)
uses [`preval.macro`][preval.macro] to determine Algolia options based on
`process.env.LOCALE`. It also uses [`preval.macro`][preval.macro] to load an
`svg` file as a string, `base64` encode it, and use it as a `background-url`
for an input element.
- [Generate documentation for React components](https://gist.github.com/souporserious/575609dc5a5d52e167dd2236079eccc0)
- [Serverless with webpack](https://github.com/geovanisouza92/serverless-preval)
build serverless functions using webpack and Babel for development and
production with preval to replace (possible sensible) content in code.
- [Read files at build time (video)](https://www.youtube.com/watch?v=NhmrbpVKgdQ&feature=youtu.be)
## Notes
If you use `babel-plugin-transform-decorators-legacy`, there is a conflict
because both plugins must be placed at the top
Wrong:
```json
{
"plugins": ["preval", "transform-decorators-legacy"]
}
```
Ok:
```json
{
"plugins": ["preval", ["transform-decorators-legacy"]]
}
```
## FAQ
### How is this different from prepack?
[`prepack`][prepack] is intended to be run on your final bundle after you've run
your webpack/etc magic on it. It does a TON of stuff, but the idea is that your
code should work with or without prepack.
`babel-plugin-preval` is intended to let you write code that would _not_ work
otherwise. Doing things like reading something from the file system are not
possible in the browser (or with prepack), but `preval` enables you to do this.
### How is this different from webpack loaders?
This plugin was inspired by webpack's [val-loader][val-loader]. The benefit of
using this over that loader (or any other loader) is that it integrates with
your existing babel pipeline. This is especially useful for the server where
you're probably not bundling your code with [`webpack`][webpack], but you may be
using babel. (If you're not using either, configuring babel for this would be
easier than configuring webpack for `val-loader`).
In addition, you can implement pretty much any webpack loader using
`babel-plugin-preval`.
If you want to learn more, check `webpack` documentations about
[`loaders`][webpack-loaders].
## Inspiration
I needed something like this for the
[glamorous website](https://github.com/kentcdodds/glamorous-website). I
live-streamed developing the whole thing. If you're interested you can find
[the recording on my youtube channel](https://www.youtube.com/watch?v=3vxov5xUai8&index=19&list=PLV5CVI1eNcJh5CTgArGVwANebCrAh2OUE)
(note, screen only recording, no audio).
I was inspired by the [val-loader][val-loader] from webpack.
## Related Projects
- [`preval.macro`][preval.macro] - nicer integration with `babel-plugin-macros`
## Other Solutions
I'm not aware of any, if you are please [make a pull request][prs] and add it
here!
## Issues
_Looking to contribute? Look for the [Good First Issue][good-first-issue]
label._
### 🐛 Bugs
Please file an issue for bugs, missing documentation, or unexpected behavior.
[**See Bugs**][bugs]
### 💡 Feature Requests
Please file an issue to suggest new features. Vote on feature requests by adding
a 👍. This helps maintainers prioritize what to work on.
[**See Feature Requests**][requests]
## Contributors ✨
Thanks goes to these people ([emoji key][emojis]):
This project follows the [all-contributors][all-contributors] specification.
Contributions of any kind welcome!
## LICENSE
MIT
[npm]: https://www.npmjs.com
[node]: https://nodejs.org
[build-badge]: https://img.shields.io/travis/kentcdodds/babel-plugin-preval.svg?style=flat-square
[build]: https://travis-ci.org/kentcdodds/babel-plugin-preval
[coverage-badge]: https://img.shields.io/codecov/c/github/kentcdodds/babel-plugin-preval.svg?style=flat-square
[coverage]: https://codecov.io/github/kentcdodds/babel-plugin-preval
[version-badge]: https://img.shields.io/npm/v/babel-plugin-preval.svg?style=flat-square
[package]: https://www.npmjs.com/package/babel-plugin-preval
[downloads-badge]: https://img.shields.io/npm/dm/babel-plugin-preval.svg?style=flat-square
[npmtrends]: http://www.npmtrends.com/babel-plugin-preval
[license-badge]: https://img.shields.io/npm/l/babel-plugin-preval.svg?style=flat-square
[license]: https://github.com/kentcdodds/babel-plugin-preval/blob/master/LICENSE
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[prs]: http://makeapullrequest.com
[coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
[coc]: https://github.com/kentcdodds/babel-plugin-preval/blob/master/other/CODE_OF_CONDUCT.md
[macros-badge]: https://img.shields.io/badge/babel--macro-%F0%9F%8E%A3-f5da55.svg?style=flat-square
[babel-plugin-macros]: https://github.com/kentcdodds/babel-plugin-macros
[examples-badge]: https://img.shields.io/badge/%F0%9F%92%A1-examples-8C8E93.svg?style=flat-square
[examples]: https://github.com/kentcdodds/babel-plugin-preval/blob/master/other/EXAMPLES.md
[emojis]: https://github.com/all-contributors/all-contributors#emoji-key
[all-contributors]: https://github.com/all-contributors/all-contributors
[bugs]: https://github.com/kentcdodds/babel-plugin-preval/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Acreated-desc+label%3Abug
[requests]: https://github.com/kentcdodds/babel-plugin-preval/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement
[good-first-issue]: https://github.com/kentcdodds/babel-plugin-preval/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement+label%3A%22good+first+issue%22
[prepack]: https://github.com/facebook/prepack
[preval.macro]: https://github.com/kentcdodds/preval.macro
[webpack]: https://webpack.js.org
[webpack-loaders]: https://webpack.js.org/concepts/loaders
[val-loader]: https://github.com/webpack-contrib/val-loader
babel-plugin-preval-5.0.0/macro.js 0000664 0000000 0000000 00000000221 13636021350 0016775 0 ustar 00root root 0000000 0000000 // this is here to make the import/require API nicer:
// import preval from 'babel-plugin-preval/macro'
module.exports = require('./dist/macro')
babel-plugin-preval-5.0.0/other/ 0000775 0000000 0000000 00000000000 13636021350 0016464 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/other/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000006241 13636021350 0021266 0 ustar 00root root 0000000 0000000 # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of
experience, nationality, personal appearance, race, religion, or sexual identity
and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, or to ban temporarily or permanently any
contributor for other behaviors that they deem inappropriate, threatening,
offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at kent+coc@doddsfamily.us. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an
incident. Further details of specific enforcement policies may be posted
separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
babel-plugin-preval-5.0.0/other/EXAMPLES.md 0000664 0000000 0000000 00000003021 13636021350 0020220 0 ustar 00root root 0000000 0000000 # Examples
## Usage with React/Next.js
### Use node's os module to get the user that ran the build and display their username.
```jsx
import React from 'react'
import preval from 'preval.macro'
const whoami = preval`
const userInfo = require('os').userInfo()
module.exports = userInfo.username
`
export default WhoAmI
function WhoAmI() {
return (
)
}
```
### Code reuse with babel-plugin-preval (Especially useful with [Next.js](https://github.com/zeit/next.js))
A small `getPosts.js` node module that loads in markdown files in a "posts"
directory.
```js
const frontMatter = require('yaml-front-matter')
const fs = require('fs')
const path = require('path')
const posts = fs
.readdirSync('./posts/')
.filter(file => path.extname(file) === '.md')
.map(file => frontMatter.loadFront(`./posts/${file}`, 'body'))
module.exports = posts || []
```
Preval the `getPosts.js` module so that posts are loaded and exported.
```js
import preval from 'preval.macro'
export default preval`module.exports = require('./getPosts')`
```
Now you can import the above posts and use a module like
[marked](https://github.com/chjj/marked) to convert your markdown into blog
posts! The underlying `getPosts.js` module can also be used required in
`next.config.js` to build the static list of routes for `next export`. See the
full example in the [Next Static](https://github.com/infiniteluke/next-static)
project.
babel-plugin-preval-5.0.0/other/MAINTAINING.md 0000664 0000000 0000000 00000006311 13636021350 0020545 0 ustar 00root root 0000000 0000000 # Maintaining
This is documentation for maintainers of this project.
## Code of Conduct
Please review, understand, and be an example of it. Violations of the code of
conduct are taken seriously, even (especially) for maintainers.
## Issues
We want to support and build the community. We do that best by helping people
learn to solve their own problems. We have an issue template and hopefully most
folks follow it. If it's not clear what the issue is, invite them to create a
minimal reproduction of what they're trying to accomplish or the bug they think
they've found.
Once it's determined that a code change is necessary, point people to
[makeapullrequest.com](http://makeapullrequest.com) and invite them to make a
pull request. If they're the one who needs the feature, they're the one who can
build it. If they need some hand holding and you have time to lend a hand,
please do so. It's an investment into another human being, and an investment
into a potential maintainer.
Remember that this is open source, so the code is not yours, it's ours. If
someone needs a change in the codebase, you don't have to make it happen
yourself. Commit as much time to the project as you want/need to. Nobody can ask
any more of you than that.
## Pull Requests
As a maintainer, you're fine to make your branches on the main repo or on your
own fork. Either way is fine.
When we receive a pull request, a travis build is kicked off automatically (see
the `.travis.yml` for what runs in the travis build). We avoid merging anything
that breaks the travis build.
Please review PRs and focus on the code rather than the individual. You never
know when this is someone's first ever PR and we want their experience to be as
positive as possible, so be uplifting and constructive.
When you merge the pull request, 99% of the time you should use the
[Squash and merge](https://help.github.com/articles/merging-a-pull-request/)
feature. This keeps our git history clean, but more importantly, this allows us
to make any necessary changes to the commit message so we release what we want
to release. See the next section on Releases for more about that.
## Release
Our releases are automatic. They happen whenever code lands into `master`. A
travis build gets kicked off and if it's successful, a tool called
[`semantic-release`](https://github.com/semantic-release/semantic-release) is
used to automatically publish a new release to npm as well as a changelog to
GitHub. It is only able to determine the version and whether a release is
necessary by the git commit messages. With this in mind, **please brush up on
[the commit message convention][commit] which drives our releases.**
> One important note about this: Please make sure that commit messages do NOT
> contain the words "BREAKING CHANGE" in them unless we want to push a major
> version. I've been burned by this more than once where someone will include
> "BREAKING CHANGE: None" and it will end up releasing a new major version. Not
> a huge deal honestly, but kind of annoying...
## Thanks!
Thank you so much for helping to maintain this project!
[commit]:
https://github.com/conventional-changelog-archived-repos/conventional-changelog-angular/blob/ed32559941719a130bb0327f886d6a32a8cbc2ba/convention.md
babel-plugin-preval-5.0.0/other/USERS.md 0000664 0000000 0000000 00000000520 13636021350 0017704 0 ustar 00root root 0000000 0000000 # Users
If you or your company uses this project, add your name to this list! Eventually
we may have a website to showcase these (wanna build it!?)
> No users have been added yet!
babel-plugin-preval-5.0.0/other/manual-releases.md 0000664 0000000 0000000 00000002441 13636021350 0022065 0 ustar 00root root 0000000 0000000 # manual-releases
This project has an automated release set up. So things are only released when
there are useful changes in the code that justify a release. But sometimes
things get messed up one way or another and we need to trigger the release
ourselves. When this happens, simply bump the number below and commit that with
the following commit message based on your needs:
**Major**
```
fix(release): manually release a major version
There was an issue with a major release, so this manual-releases.md
change is to release a new major version.
Reference: #
BREAKING CHANGE:
```
**Minor**
```
feat(release): manually release a minor version
There was an issue with a minor release, so this manual-releases.md
change is to release a new minor version.
Reference: #
```
**Patch**
```
fix(release): manually release a patch version
There was an issue with a patch release, so this manual-releases.md
change is to release a new patch version.
Reference: #
```
The number of times we've had to do a manual release is: 0
babel-plugin-preval-5.0.0/package.json 0000664 0000000 0000000 00000002621 13636021350 0017632 0 ustar 00root root 0000000 0000000 {
"name": "babel-plugin-preval",
"version": "0.0.0-semantically-released",
"description": "Pre-evaluate code at build-time",
"engines": {
"node": ">=10",
"npm": ">=6"
},
"main": "dist/index.js",
"scripts": {
"build": "kcd-scripts build",
"lint": "kcd-scripts lint",
"test": "kcd-scripts test",
"test:update": "npm test -- --updateSnapshot --coverage",
"validate": "kcd-scripts validate"
},
"files": [
"dist",
"macro.js"
],
"keywords": [
"babel",
"babel-plugin",
"eval",
"precompile",
"babel-plugin-macros"
],
"author": "Kent C. Dodds (https://kentcdodds.com)",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.9.2",
"babel-plugin-macros": "^2.8.0",
"require-from-string": "^2.0.2"
},
"devDependencies": {
"ast-pretty-print": "^2.0.1",
"babel-plugin-tester": "^8.0.1",
"kcd-scripts": "^5.5.0"
},
"eslintConfig": {
"extends": "./node_modules/kcd-scripts/eslint.js"
},
"eslintIgnore": [
"node_modules",
"coverage",
"dist"
],
"babel": {
"presets": [
"kcd-scripts/babel"
]
},
"repository": {
"type": "git",
"url": "https://github.com/kentcdodds/babel-plugin-preval"
},
"bugs": {
"url": "https://github.com/kentcdodds/babel-plugin-preval/issues"
},
"homepage": "https://github.com/kentcdodds/babel-plugin-preval#readme"
}
babel-plugin-preval-5.0.0/src/ 0000775 0000000 0000000 00000000000 13636021350 0016132 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/src/__tests__/ 0000775 0000000 0000000 00000000000 13636021350 0020070 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/src/__tests__/__snapshots__/ 0000775 0000000 0000000 00000000000 13636021350 0022706 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/src/__tests__/__snapshots__/index.js.snap 0000664 0000000 0000000 00000011762 13636021350 0025322 0 ustar 00root root 0000000 0000000 // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`preval a-bunch-of-checks: a-bunch-of-checks 1`] = `
const x = preval\`
const fs = require('fs')
const val = fs.readFileSync(require.resolve('./fixture1.md'), 'utf8')
module.exports = {
val,
getSplit: function(splitDelimiter) {
return x.val.split(splitDelimiter)
}
}
\`
↓ ↓ ↓ ↓ ↓ ↓
const x = {
val: '# fixture\\n\\nThis is some file thing...\\n',
getSplit: function(splitDelimiter) {
return x.val.split(splitDelimiter)
},
}
`;
exports[`preval absolute-path: absolute-path 1`] = `
const x = preval.require("../__tests__/fixtures/nested/absolute-path")
↓ ↓ ↓ ↓ ↓ ↓
const x =
'/src/__tests__/index.js'
`;
exports[`preval dynamic error: dynamic error 1`] = `
const x = preval\`module.exports = "\${dynamic}"\`
↓ ↓ ↓ ↓ ↓ ↓
Error: /src/__tests__/index.js: Unable to determine the value of your preval string
`;
exports[`preval export undefined: export undefined 1`] = `
// @preval
let smth = {}
module.exports = smth.UNDEFINED;
↓ ↓ ↓ ↓ ↓ ↓
// this file was prevaled
module.exports = undefined
`;
exports[`preval handles transpiled modules (uses default export): handles transpiled modules (uses default export) 1`] = `
let one = preval.require('./fixtures/es6-identity.js', 1)
↓ ↓ ↓ ↓ ↓ ↓
let one = 1
`;
exports[`preval import comment (with extras before): import comment (with extras before) 1`] = `
import x from /* this is extra stuff */ /* preval */ "./fixtures/compute-one.js"
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`preval import comment (with extras): import comment (with extras) 1`] = `
import x from /* preval */ /* this is extra stuff */ "./fixtures/compute-one.js"
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`preval import comment: import comment 1`] = `
import x from /* preval */ "./fixtures/compute-one.js"
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`preval import object arg: import object arg 1`] = `
import x from /* preval({object: "argument", withFunction: () => {}}) */ "./fixtures/identity.js"
↓ ↓ ↓ ↓ ↓ ↓
const x = {
object: 'argument',
withFunction: () => {},
}
`;
exports[`preval import required arg: import required arg 1`] = `
import x from /* preval(require("./fixtures/compute-one")) */ "./fixtures/identity"
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`preval import string arg: import string arg 1`] = `
import x from /* preval("string argument") */ "./fixtures/identity.js"
↓ ↓ ↓ ↓ ↓ ↓
const x = 'string argument'
`;
exports[`preval require functions: require functions 1`] = `
const x = preval.require("./fixtures/multiple-functions")
↓ ↓ ↓ ↓ ↓ ↓
const x = {
a: function a() {
return 'a'
},
b: function b() {
return 'b'
},
}
`;
exports[`preval require with arg but not a function: require with arg but not a function 1`] = `
const x = preval.require("./fixtures/compute-one", "should not be here...")
↓ ↓ ↓ ↓ ↓ ↓
Error: /src/__tests__/index.js: \`preval.require\`-ed module (src/__tests__/index.js) cannot accept arguments because it does not export a function. You passed the arguments: should not be here...
`;
exports[`preval require with arge: require with arge 1`] = `
const x = preval.require("./fixtures/identity", 3)
↓ ↓ ↓ ↓ ↓ ↓
const x = 3
`;
exports[`preval require with unknown arg: require with unknown arg 1`] = `
const x = preval.require("./fixtures/identity", SOME_UNKNOWN_VARIABLE)
↓ ↓ ↓ ↓ ↓ ↓
Error: /src/__tests__/index.js: preval cannot determine the value of an argument in preval.require
`;
exports[`preval simple comment: simple comment 1`] = `
// @preval
module.exports = 1 + 2 - 1 - 1
↓ ↓ ↓ ↓ ↓ ↓
// this file was prevaled
module.exports = 1
`;
exports[`preval simple function: simple function 1`] = `
const y = preval\`
module.exports = {
booyah: function() {
return "booyah"
}
}
\`
↓ ↓ ↓ ↓ ↓ ↓
const y = {
booyah: function() {
return 'booyah'
},
}
`;
exports[`preval simple number: simple number 1`] = `
const x = preval\`module.exports = 1\`
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`preval simple require: simple require 1`] = `
const x = preval.require("./fixtures/compute-one")
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`preval simple string: simple string 1`] = `
preval\`module.exports = "foo"\`
↓ ↓ ↓ ↓ ↓ ↓
'foo'
`;
exports[`preval with flow after: with flow after 1`] = `
// @preval
// @flow
module.exports = 1 + 2 - 1 - 1
↓ ↓ ↓ ↓ ↓ ↓
// this file was prevaled
// @flow
module.exports = 1
`;
exports[`preval with flow before: with flow before 1`] = `
// @flow
// @preval
module.exports = 1 + 2 - 1 - 1
↓ ↓ ↓ ↓ ↓ ↓
// @flow
// this file was prevaled
module.exports = 1
`;
babel-plugin-preval-5.0.0/src/__tests__/__snapshots__/macro.js.snap 0000664 0000000 0000000 00000002231 13636021350 0025303 0 ustar 00root root 0000000 0000000 // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`macros as function: as function 1`] = `
const myPreval = require('../macro')
const x = myPreval(\`
module.exports = require('./fixtures/identity')({sayHi: () => 'hi'})
\`)
↓ ↓ ↓ ↓ ↓ ↓
const x = {
sayHi: () => 'hi',
}
`;
exports[`macros as jsx: as jsx 1`] = `
const Preval = require('../macro')
const ui = (
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./fixtures/fixture1.md'), 'utf8')
)
↓ ↓ ↓ ↓ ↓ ↓
const ui = "# fixture\\n\\nThis is some file thing...\\n"
`;
exports[`macros as tag: as tag 1`] = `
import preval from '../macro'
const x = preval\`module.exports = require('./fixtures/compute-one')\`
↓ ↓ ↓ ↓ ↓ ↓
const x = 1
`;
exports[`macros error for other nodes: error for other nodes 1`] = `
const preval = require('../macro')
x = 3 + preval
↓ ↓ ↓ ↓ ↓ ↓
Error: /src/__tests__/macro.js: ../macro: babel-plugin-preval/macro can only be used as tagged template expression, function call or JSX element. You tried BinaryExpression.
`;
babel-plugin-preval-5.0.0/src/__tests__/fixtures/ 0000775 0000000 0000000 00000000000 13636021350 0021741 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/src/__tests__/fixtures/.babelrc 0000664 0000000 0000000 00000000140 13636021350 0023327 0 ustar 00root root 0000000 0000000 {
"presets": ["@babel/preset-env"],
"plugins": ["transform-inline-environment-variables"]
}
babel-plugin-preval-5.0.0/src/__tests__/fixtures/.eslintrc 0000664 0000000 0000000 00000000110 13636021350 0023555 0 ustar 00root root 0000000 0000000 {
"rules": {
"no-unused-vars": "off",
"no-undef": "off"
}
}
babel-plugin-preval-5.0.0/src/__tests__/fixtures/a-bunch-of-checks.js 0000664 0000000 0000000 00000000361 13636021350 0025454 0 ustar 00root root 0000000 0000000 const x = preval`
const fs = require('fs')
const val = fs.readFileSync(require.resolve('./fixture1.md'), 'utf8')
module.exports = {
val,
getSplit: function(splitDelimiter) {
return x.val.split(splitDelimiter)
}
}
`
babel-plugin-preval-5.0.0/src/__tests__/fixtures/compute-one.js 0000664 0000000 0000000 00000000033 13636021350 0024526 0 ustar 00root root 0000000 0000000 module.exports = 1 + 1 - 1
babel-plugin-preval-5.0.0/src/__tests__/fixtures/es6-identity.js 0000664 0000000 0000000 00000000433 13636021350 0024623 0 ustar 00root root 0000000 0000000 /* eslint-disable */
// codegen can't accept non-transpiled esmodules
// but it can handle transpiled esmodules
// so we're simulating a pre-transpiled module here
Object.defineProperty(exports, '__esModule', {
value: true,
})
exports.default = function(input) {
return input
}
babel-plugin-preval-5.0.0/src/__tests__/fixtures/fixture1.md 0000664 0000000 0000000 00000000046 13636021350 0024032 0 ustar 00root root 0000000 0000000 # fixture
This is some file thing...
babel-plugin-preval-5.0.0/src/__tests__/fixtures/identity.js 0000664 0000000 0000000 00000000107 13636021350 0024126 0 ustar 00root root 0000000 0000000 module.exports = acceptsArg
function acceptsArg(arg) {
return arg
}
babel-plugin-preval-5.0.0/src/__tests__/fixtures/multiple-functions.js 0000664 0000000 0000000 00000000145 13636021350 0026140 0 ustar 00root root 0000000 0000000 module.exports = {
a: function a() {
return 'a'
},
b: function b() {
return 'b'
},
}
babel-plugin-preval-5.0.0/src/__tests__/fixtures/nested/ 0000775 0000000 0000000 00000000000 13636021350 0023223 5 ustar 00root root 0000000 0000000 babel-plugin-preval-5.0.0/src/__tests__/fixtures/nested/absolute-path.js 0000664 0000000 0000000 00000000175 13636021350 0026334 0 ustar 00root root 0000000 0000000 // preval.require would either resolve an absolute path or fail to resolve this
// module at all
module.exports = __filename
babel-plugin-preval-5.0.0/src/__tests__/index.js 0000664 0000000 0000000 00000006577 13636021350 0021554 0 ustar 00root root 0000000 0000000 import path from 'path'
import pluginTester from 'babel-plugin-tester'
import plugin from '../'
const projectRoot = path.join(__dirname, '../../')
expect.addSnapshotSerializer({
print(val) {
return val.split(projectRoot).join('/')
},
test(val) {
return typeof val === 'string'
},
})
const error = code => ({code, error: true})
const noSnapshot = code => ({code, snapshot: false})
const fixture = filename => ({
fixture: require.resolve(`./fixtures/${filename}`),
})
pluginTester({
plugin,
snapshot: true,
babelOptions: {filename: __filename},
tests: {
'not preval': noSnapshot('const x = notPreval`module.exports = "nothing"`'),
'simple number': 'const x = preval`module.exports = 1`',
'simple string': 'preval`module.exports = "foo"`',
'simple function': `
const y = preval\`
module.exports = {
booyah: function() {
return "booyah"
}
}
\`
`,
'a-bunch-of-checks': fixture('a-bunch-of-checks'),
'dynamic error': error(
`const x = preval\`module.exports = "\${dynamic}"\``,
),
'import comment': 'import x from /* preval */ "./fixtures/compute-one.js"',
'import comment (with extras)':
'import x from /* preval */ /* this is extra stuff */ "./fixtures/compute-one.js"',
'import comment (with extras before)':
'import x from /* this is extra stuff */ /* preval */ "./fixtures/compute-one.js"',
'invalid comment': {
// no real changes here, but babel does weird stuff to comments like this...
code:
'import x from /* this is extra stuff */"./fixtures/compute-one.js";',
output: `
import x from /* this is extra stuff */
'./fixtures/compute-one.js'
`,
snapshot: false,
},
'import string arg':
'import x from /* preval("string argument") */ "./fixtures/identity.js"',
'import object arg':
'import x from /* preval({object: "argument", withFunction: () => {}}) */ "./fixtures/identity.js"',
'import required arg':
'import x from /* preval(require("./fixtures/compute-one")) */ "./fixtures/identity"',
'simple require': 'const x = preval.require("./fixtures/compute-one")',
'require with arge': 'const x = preval.require("./fixtures/identity", 3)',
'require functions':
'const x = preval.require("./fixtures/multiple-functions")',
'absolute-path':
'const x = preval.require("../__tests__/fixtures/nested/absolute-path")',
'require with unknown arg': error(
'const x = preval.require("./fixtures/identity", SOME_UNKNOWN_VARIABLE)',
),
'require with arg but not a function': error(
'const x = preval.require("./fixtures/compute-one", "should not be here...")',
),
'simple comment': `
// @preval
module.exports = 1 + 2 - 1 - 1
`,
'with flow before': `
// @flow
// @preval
module.exports = 1 + 2 - 1 - 1
`,
'with flow after': `
// @preval
// @flow
module.exports = 1 + 2 - 1 - 1
`,
'export undefined': `
// @preval
let smth = {}
module.exports = smth.UNDEFINED;
`,
'comment no contents': noSnapshot('// @preval'),
'comment with only comment contents': noSnapshot(`
// @preval
/* comment */
`),
'handles transpiled modules (uses default export)': `
let one = preval.require('./fixtures/es6-identity.js', 1)
`,
},
})
babel-plugin-preval-5.0.0/src/__tests__/macro.js 0000664 0000000 0000000 00000002474 13636021350 0021536 0 ustar 00root root 0000000 0000000 import path from 'path'
import pluginTester from 'babel-plugin-tester'
import plugin from 'babel-plugin-macros'
const projectRoot = path.join(__dirname, '../../')
expect.addSnapshotSerializer({
print(val) {
return val.split(projectRoot).join('/')
},
test(val) {
return typeof val === 'string'
},
})
pluginTester({
plugin,
snapshot: true,
babelOptions: {filename: __filename, parserOpts: {plugins: ['jsx']}},
tests: [
{
title: 'as tag',
code: `
import preval from '../macro'
const x = preval\`module.exports = require('./fixtures/compute-one')\`
`,
},
{
title: 'as function',
code: `
const myPreval = require('../macro')
const x = myPreval(\`
module.exports = require('./fixtures/identity')({sayHi: () => 'hi'})
\`)
`,
},
{
title: 'as jsx',
code: `
const Preval = require('../macro')
const ui = (
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./fixtures/fixture1.md'), 'utf8')
)
`,
},
{
title: 'error for other nodes',
error: true,
code: `
const preval = require('../macro')
x = 3 + preval
`,
},
],
})
babel-plugin-preval-5.0.0/src/helpers.js 0000664 0000000 0000000 00000001703 13636021350 0020133 0 ustar 00root root 0000000 0000000 const p = require('path')
const requireFromStringOfCode = require('require-from-string')
const objectToAST = require('./object-to-ast')
module.exports = {
getReplacement,
requireFromString,
}
function requireFromString({
string: stringToPreval,
fileOpts: {filename},
args = [],
}) {
let mod = requireFromStringOfCode(String(stringToPreval), filename)
mod = mod && mod.__esModule ? mod.default : mod
if (typeof mod === 'function') {
mod = mod(...args)
} else if (args.length) {
throw new Error(
`\`preval.require\`-ed module (${p.relative(
process.cwd(),
filename,
)}) cannot accept arguments because it does not export a function. You passed the arguments: ${args.join(
', ',
)}`,
)
}
return mod
}
function getReplacement({string, fileOpts, args, babel}) {
const mod = requireFromString({string, fileOpts, args, babel})
return objectToAST(mod, {babel, fileOptions: fileOpts})
}
babel-plugin-preval-5.0.0/src/index.js 0000664 0000000 0000000 00000012054 13636021350 0017601 0 ustar 00root root 0000000 0000000 const p = require('path')
const fs = require('fs')
// const printAST = require('ast-pretty-print')
const {getReplacement, requireFromString} = require('./helpers')
module.exports = prevalPlugin
function prevalPlugin(babel) {
const {types: t, template, transformFromAst} = babel
const assignmentBuilder = template('const NAME = VALUE')
return {
name: 'preval',
visitor: {
Program(path, {file: {opts: fileOpts}}) {
const firstNode = path.node.body[0] || {}
const comments = firstNode.leadingComments || []
const isPreval = comments.some(isPrevalComment)
if (!isPreval) {
return
}
comments.find(isPrevalComment).value = ' this file was prevaled'
const {code: string} = transformFromAst(
path.node,
null,
/* istanbul ignore next (babel 6 vs babel 7 check) */
/^6\./.test(babel.version)
? {}
: {
babelrc: false,
configFile: false,
},
)
const replacement = getReplacement({string, fileOpts, babel})
const moduleExports = {
...t.expressionStatement(
t.assignmentExpression(
'=',
t.memberExpression(
t.identifier('module'),
t.identifier('exports'),
),
replacement,
),
),
leadingComments: comments,
}
path.replaceWith(t.program([moduleExports]))
},
TaggedTemplateExpression(path, {file: {opts: fileOpts}}) {
const isPreval = path.node.tag.name === 'preval'
if (!isPreval) {
return
}
const string = path.get('quasi').evaluate().value
if (!string) {
throw new Error('Unable to determine the value of your preval string')
}
const replacement = getReplacement({string, fileOpts, babel})
path.replaceWith(replacement)
},
ImportDeclaration(path, {file: {opts: fileOpts}}) {
const isPreval = looksLike(path, {
node: {
source: {
leadingComments(comments) {
return comments && comments.some(isPrevalComment)
},
},
},
})
if (!isPreval) {
return
}
const prevalComment = path.node.source.leadingComments
.find(isPrevalComment)
.value.trim()
let argValues
if (prevalComment !== 'preval') {
const arg = prevalComment.replace(/preval\((.*)\)/, '$1').trim()
const argValue = requireFromString({
string: `module.exports = ${arg}`,
fileOpts,
})
argValues = [argValue]
}
const absolutePath = p.resolve(
p.dirname(fileOpts.filename),
path.node.source.value,
)
const code = fs.readFileSync(require.resolve(absolutePath))
const replacement = getReplacement({
string: code,
fileOpts,
args: argValues,
babel,
})
path.replaceWith(
assignmentBuilder({
NAME: t.identifier(path.node.specifiers[0].local.name),
VALUE: replacement,
}),
)
},
CallExpression(path, {file: {opts: fileOpts}}) {
const isPreval = looksLike(path, {
node: {
callee: {
type: 'MemberExpression',
object: {name: 'preval'},
property: {name: 'require'},
},
},
})
if (!isPreval) {
return
}
const [source, ...args] = path.get('arguments')
const argValues = args.map(a => {
const result = a.evaluate()
if (!result.confident) {
throw new Error(
'preval cannot determine the value of an argument in preval.require',
)
}
return result.value
})
const absolutePath = p.resolve(
p.dirname(fileOpts.filename),
source.node.value,
)
const code = fs.readFileSync(require.resolve(absolutePath))
const replacement = getReplacement({
string: code,
fileOpts,
args: argValues,
babel,
})
path.replaceWith(replacement)
},
},
}
}
function isPrevalComment(comment) {
const normalisedComment = comment.value
.trim()
.split(' ')[0]
.trim()
return (
normalisedComment.startsWith('preval') ||
normalisedComment.startsWith('@preval')
)
}
function looksLike(a, b) {
return (
a &&
b &&
Object.keys(b).every(bKey => {
const bVal = b[bKey]
const aVal = a[bKey]
if (typeof bVal === 'function') {
return bVal(aVal)
}
return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal)
})
)
}
function isPrimitive(val) {
// eslint-disable-next-line
return val == null || /^[sbn]/.test(typeof val)
}
/*
eslint
import/no-unassigned-import: off,
import/no-dynamic-require: off,
max-lines-per-function: off,
*/
babel-plugin-preval-5.0.0/src/macro.js 0000664 0000000 0000000 00000004221 13636021350 0017570 0 ustar 00root root 0000000 0000000 // const printAST = require('ast-pretty-print')
const {createMacro} = require('babel-plugin-macros')
const {getReplacement} = require('./helpers')
module.exports = createMacro(prevalMacros)
function prevalMacros({references, state, babel}) {
references.default.forEach(referencePath => {
if (referencePath.parentPath.type === 'TaggedTemplateExpression') {
asTag(referencePath.parentPath.get('quasi'), state, babel)
} else if (referencePath.parentPath.type === 'CallExpression') {
asFunction(referencePath.parentPath.get('arguments'), state, babel)
} else if (referencePath.parentPath.type === 'JSXOpeningElement') {
asJSX(
{
attributes: referencePath.parentPath.get('attributes'),
children: referencePath.parentPath.parentPath.get('children'),
},
state,
babel,
)
} else if (referencePath.parentPath.type === 'JSXClosingElement') {
// That's okay, we already prevaled this one on its opening element.
} else {
throw new Error(
`babel-plugin-preval/macro can only be used as tagged template expression, function call or JSX element. You tried ${referencePath.parentPath.type}.`,
)
}
})
}
function asTag(quasiPath, {file: {opts: fileOpts}}, babel) {
const string = quasiPath.parentPath.get('quasi').evaluate().value
quasiPath.parentPath.replaceWith(
getReplacement({
string,
fileOpts,
babel,
}),
)
}
function asFunction(argumentsPaths, {file: {opts: fileOpts}}, babel) {
const string = argumentsPaths[0].evaluate().value
argumentsPaths[0].parentPath.replaceWith(
getReplacement({
string,
fileOpts,
babel,
}),
)
}
// eslint-disable-next-line no-unused-vars
function asJSX({attributes, children}, {file: {opts: fileOpts}}, babel) {
// It's a shame you cannot use evaluate() with JSX
const string = children[0].node.value
children[0].replaceWith(
getReplacement({
string,
fileOpts,
babel,
}),
)
const {
parentPath: {
node: {openingElement, closingElement},
},
} = children[0]
openingElement.name.name = 'div'
closingElement.name.name = 'div'
}
babel-plugin-preval-5.0.0/src/object-to-ast.js 0000664 0000000 0000000 00000001600 13636021350 0021140 0 ustar 00root root 0000000 0000000 module.exports = objectToAST
function objectToAST(object, {babel, fileOptions}) {
const stringified = stringify(object)
const variableDeclarationNode = babel.template(`var x = ${stringified}`, {
preserveComments: true,
placeholderPattern: false,
...fileOptions.parserOpts,
sourceType: 'module',
})()
return variableDeclarationNode.declarations[0].init
}
function stringify(object) {
let str = JSON.stringify(object, stringifyReplacer)
if (str === undefined) {
str = 'undefined'
}
return str.replace(
/"__FUNCTION_START__(.*?)__FUNCTION_END__"/g,
functionReplacer,
)
function stringifyReplacer(key, value) {
if (typeof value === 'function') {
return `__FUNCTION_START__${value.toString()}__FUNCTION_END__`
}
return value
}
function functionReplacer(match, p1) {
return p1.replace(/\\"/g, '"').replace(/\\n/g, '\n')
}
}