├── .eslintignore
├── .gitattributes
├── test
├── src
│ ├── variables.css
│ ├── alternate.sss
│ ├── classic.sass
│ ├── index.css
│ ├── sourcesanspro.woff
│ ├── classic.scss
│ ├── index.js
│ └── logo.svg
└── webpack.config.js
├── .eslintrc.yml
├── .babelrc
├── .gitignore
├── .flowconfig
├── .editorconfig
├── src
├── getBanner.js
├── createBabelConfig.js
└── cli.js
├── appveyor.yml
├── .prettierrc.yml
├── .travis.yml
├── package.json
├── readme.md
└── license
/.eslintignore:
--------------------------------------------------------------------------------
1 | bin
2 | lib
3 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 |
--------------------------------------------------------------------------------
/test/src/variables.css:
--------------------------------------------------------------------------------
1 | $color: red;
2 |
--------------------------------------------------------------------------------
/.eslintrc.yml:
--------------------------------------------------------------------------------
1 | extends:
2 | - readable/node
3 |
--------------------------------------------------------------------------------
/test/src/alternate.sss:
--------------------------------------------------------------------------------
1 | .alternate
2 | color: blue
3 |
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "edge"
4 | ]
5 | }
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | bin/
3 | test/lib/
4 | test/dist/
5 |
--------------------------------------------------------------------------------
/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 |
3 | [include]
4 |
5 | [libs]
6 |
7 | [options]
8 |
--------------------------------------------------------------------------------
/test/src/classic.sass:
--------------------------------------------------------------------------------
1 | .classic
2 | color: orange
3 | font-weight: bold
4 |
--------------------------------------------------------------------------------
/test/src/index.css:
--------------------------------------------------------------------------------
1 | @import "variables.css";
2 |
3 | .root{
4 | color: $color;
5 | }
6 |
--------------------------------------------------------------------------------
/test/src/sourcesanspro.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sebastian-software/prepublish/HEAD/test/src/sourcesanspro.woff
--------------------------------------------------------------------------------
/test/src/classic.scss:
--------------------------------------------------------------------------------
1 | $color: green;
2 |
3 | .classic {
4 | color: $color;
5 | font-weight: light;
6 | }
7 |
8 | .font {
9 | src: url("./sourcesanspro.woff") format("woff");
10 | }
11 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | end_of_line = lf
7 | charset = utf-8
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
--------------------------------------------------------------------------------
/src/getBanner.js:
--------------------------------------------------------------------------------
1 | export default function getBanner(pkg) {
2 | let banner = `/*! ${pkg.name} v${pkg.version}`
3 |
4 | if (pkg.author) {
5 | if (typeof pkg.author === "object") {
6 | banner += ` by ${pkg.author.name} <${pkg.author.email}>`
7 | } else if (typeof pkg.author === "string") {
8 | banner += ` by ${pkg.author}`
9 | }
10 | }
11 |
12 | banner += ` */`
13 |
14 | return banner
15 | }
16 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 | clone_depth: 10
2 |
3 | environment:
4 | matrix:
5 | - nodejs_version: 6
6 | - nodejs_version: 8
7 | - nodejs_version: 10
8 |
9 | platform:
10 | - x64
11 |
12 | matrix:
13 | fast_finish: true
14 |
15 | version: "{build}"
16 | build: off
17 | deploy: off
18 |
19 | install:
20 | - ps: Install-Product node $env:nodejs_version $env:platform
21 | - npm install
22 |
23 | test_script:
24 | - npm test
25 |
26 | cache:
27 | # global npm cache
28 | - '%APPDATA%\npm-cache'
29 |
30 | notifications:
31 | - provider: Slack
32 | incoming_webhook:
33 | secure: 42qYgf76P/QjYb5QJ18gFFJ67iTlXc1QzEva9BFofwh5KzpF/QJ/pvRark1i3aux6uwL53zdDKTjXfy8Ozpqqk9DhnU5M1oA96bQYWOnmZU=
34 |
--------------------------------------------------------------------------------
/.prettierrc.yml:
--------------------------------------------------------------------------------
1 | # Generally, we allow slightly longer lines (110 for code, 140 for comments),
2 | # but we limit this to a value that leads to better results when using auto formatting.
3 | printWidth: 90
4 |
5 | # Use two spaces for tabs
6 | tabWidth: 2
7 |
8 | # Unify with convention used in JSX, HTML and CSS to use double quotes
9 | singleQuote: false
10 |
11 | # Don't use semicolons where they are not required
12 | semi: false
13 |
14 | # Don't do noisy trailing commas
15 | trailingComma: none
16 |
17 | # More space is better for readability
18 | bracketSpacing: true
19 |
20 | # Put the > of a multi-line JSX element at the end of the last line
21 | jsxBracketSameLine: false
22 |
23 | # Include parentheses around a sole arrow function parameter.
24 | arrowParens: always
25 |
--------------------------------------------------------------------------------
/test/webpack.config.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable filenames/match-regex */
2 | /* eslint-disable import/no-commonjs */
3 | var path = require("path")
4 |
5 | module.exports = {
6 | context: path.resolve(__dirname, "lib"),
7 | entry: "./node.es5.esm.js",
8 | target: "node",
9 | devtool: "source-map",
10 | stats: "errors-only",
11 | output: {
12 | path: path.resolve(__dirname, "dist"),
13 | filename: "bundle.js",
14 | libraryTarget: "commonjs2"
15 | },
16 | module: {
17 | rules: [{
18 | test: /\.(svg|woff)$/,
19 | use: {
20 | loader: "file-loader",
21 | options: {
22 | name: "[name].[ext]"
23 | }
24 | }
25 | },
26 | {
27 | test: /\.(css|sss|scss|sass)$/,
28 | use: [ 'style-loader', 'css-loader' ]
29 | }]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 |
3 | node_js:
4 | - 6
5 | - 8
6 | - 10
7 |
8 | matrix:
9 | fast_finish: true
10 |
11 | notifications:
12 | email: false
13 | slack:
14 | secure: rbUUN+ID+aOWbUNcvo6dDvhV0Ka1pvFi9Cz8cB9SQcrtGDE+9Swd6DVPQmDAB5U4r1s1f9AUz5isDnC7b2K72r3vOlutlLBQ1Q2lP/6qzidrFLyNJvkcMSUziNX+Q8snvzF+lojq7jno0YhGfR4CLpoj5oJ0O4xc5gEbpfIfILcbs4svFcg9y5KqbDudRCMdWPz4YOfbZ2eVo2S4YNmooxNAotkbA6kaazArG6ClGwUE7QFoVdpLI6eKlGIn0m8pzwkzHArkauwkKak2prseWy4QKA2hVwMcuATX1slG9dtZ7NEFCUgXMS9zrz3GhcqwCBjOTKKX8FjM+gFkXM24E9QgEdRoNp8uAQTmssASGEBoM6foEq+x2nTkADwDCywz4ImTEpUqGv13oQRvLbLA0P57I5SREz2ONbBTA6mwAAeV0dmZiy1c5OmyzJ6nDw0qZBbPIWIvYoTwuIRcThCiltbhZ0+Bg389gfmJfJIY3hDo8KuCTPfbdlZznZh2I22sHOAj+PnktK8PY4az+MrAOMGMtd2QQO3i8WSrW3jfsYbAOLVG4DvWdjfL+noqrU5QHEIQ7wy93s0JICERzLc+ZJJ4rRgz3iM899aIMLmvu0RvGIVRfqtDYeLzpYqiQwFND+83HuswQKfBlLRhqOZSoUqBXgxJbHSy59VxrBhXfSc=
15 |
16 | cache:
17 | directories:
18 | - $HOME/.npm
19 |
--------------------------------------------------------------------------------
/src/createBabelConfig.js:
--------------------------------------------------------------------------------
1 | import babel from "rollup-plugin-babel"
2 | import presetEdge from "babel-preset-edge"
3 |
4 | /* eslint-disable max-params */
5 | export function createHelper({
6 | mode = "classic",
7 | minified = false,
8 | presets = [],
9 | plugins = []
10 | }) {
11 | const additionalPlugins = plugins.concat()
12 | const additionalPresets = presets.concat()
13 |
14 | let selectedPreset
15 | if (mode === "modern") {
16 | selectedPreset = [
17 | presetEdge,
18 | {
19 | target: "modern",
20 | compression: minified
21 | }
22 | ]
23 | } else if (mode === "es2015") {
24 | selectedPreset = [
25 | presetEdge,
26 | {
27 | target: "es2015",
28 | compression: minified
29 | }
30 | ]
31 | } else if (mode === "binary") {
32 | selectedPreset = [
33 | presetEdge,
34 | {
35 | target: "node",
36 | compression: minified,
37 | modules: false
38 | }
39 | ]
40 | } else {
41 | selectedPreset = [
42 | presetEdge,
43 | {
44 | target: "library",
45 | compression: minified
46 | }
47 | ]
48 | }
49 |
50 | return babel({
51 | // Don't try to find .babelrc because we want to force this configuration.
52 | babelrc: false,
53 |
54 | // Use runtime helpers as implemented by edge preset
55 | runtimeHelpers: true,
56 |
57 | // Do not transpile external code
58 | // https://github.com/rollup/rollup-plugin-babel/issues/48#issuecomment-211025960
59 | exclude: [ "node_modules/**", "**/*.json" ],
60 |
61 | presets: [
62 | selectedPreset,
63 |
64 | // All manually or minification related presets
65 | ...additionalPresets
66 | ],
67 |
68 | plugins: [
69 | // All manually or minification related plugins
70 | ...additionalPlugins
71 | ]
72 | })
73 | }
74 |
75 | export default function createBabelConfig(options) {
76 | return {
77 | es5: createHelper({ ...options, mode: "es5" }),
78 | es2015: createHelper({ ...options, mode: "es2015" }),
79 | modern: createHelper({ ...options, mode: "modern" }),
80 | binary: createHelper({ ...options, mode: "binary" })
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "prepublish",
3 | "version": "2.2.0",
4 | "description": "Simplifies the prepare step (bundling, transpiling, rebasing) during publishing NPM packages.",
5 | "keywords": [
6 | "npm",
7 | "publish",
8 | "prepublish",
9 | "prepare",
10 | "release",
11 | "library",
12 | "api",
13 | "tooling",
14 | "rollup",
15 | "babel",
16 | "rebase"
17 | ],
18 | "engines": {
19 | "node": ">=6.0.0",
20 | "npm": ">=5.0.0",
21 | "yarn": ">=1.0.0"
22 | },
23 | "bin": {
24 | "prepublish": "./bin/prepublish"
25 | },
26 | "files": [
27 | "bin"
28 | ],
29 | "author": {
30 | "name": "Sebastian Werner",
31 | "email": "s.werner@sebastian-software.de",
32 | "url": "http://sebastian-software.de/werner"
33 | },
34 | "license": "Apache-2.0",
35 | "main": "lib/index.js",
36 | "scripts": {
37 | "release": "git push && release-it --github.release --npm.publish --non-interactive",
38 | "release:minor": "git push && release-it --github.release --npm.publish --non-interactive --increment minor",
39 | "release:major": "git push && release-it --github.release --npm.publish --non-interactive --increment major",
40 | "test": "rimraf test/lib test/dist && npm run prepare && node ./bin/prepublish --input-node test/src/index.js --output-folder test/lib && webpack --hide-modules --config test/webpack.config.js",
41 | "prepare": "rimraf bin && cross-env EDGE_ENV=node babel-node src/cli.js"
42 | },
43 | "repository": {
44 | "type": "git",
45 | "url": "git+https://github.com/sebastian-software/prepublish.git"
46 | },
47 | "dependencies": {
48 | "@babel/runtime": "^7.0.0",
49 | "app-root-dir": "^1.0.2",
50 | "async": "^2.6.1",
51 | "babel-preset-edge": "^4.13.1",
52 | "chalk": "^2.4.1",
53 | "core-js": "^2.5.7",
54 | "file-exists": "^5.0.1",
55 | "fs-extra": "^7.0.0",
56 | "loader-utils": "^1.1.0",
57 | "lodash": "^4.17.11",
58 | "meow": "^5.0.0",
59 | "rollup": "^0.66.0",
60 | "rollup-plugin-babel": "^4.0.3",
61 | "rollup-plugin-commonjs": "^9.1.8",
62 | "rollup-plugin-executable": "^1.3.0",
63 | "rollup-plugin-json": "^3.1.0",
64 | "rollup-plugin-node-resolve": "^3.4.0",
65 | "rollup-plugin-rebase": "^2.0.4",
66 | "rollup-plugin-replace": "^2.0.0",
67 | "rollup-plugin-yaml": "^1.1.0"
68 | },
69 | "devDependencies": {
70 | "@babel/core": "^7.1.0",
71 | "@babel/node": "^7.0.0",
72 | "babel-core": "^7.0.0-bridge.0",
73 | "babel-jest": "^23.6.0",
74 | "cross-env": "^5.2.0",
75 | "css-loader": "^1.0.0",
76 | "eslint": "^5.6.0",
77 | "eslint-config-readable": "^2.2.0",
78 | "file-loader": "^2.0.0",
79 | "flow-bin": "^0.81.0",
80 | "prettier": "^1.14.2",
81 | "rimraf": "^2.6.2",
82 | "style-loader": "^0.23.0",
83 | "webpack": "^4.19.1",
84 | "webpack-cli": "^3.1.0"
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/test/src/index.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-magic-numbers */
2 | /* eslint-disable func-style */
3 | /* eslint-disable no-empty-function */
4 | /* eslint-disable lodash/prefer-noop */
5 |
6 | import { camelCase } from "lodash"
7 | console.log("CherryPick Import Lodash:", camelCase("hello world") === "helloWorld")
8 |
9 | import classes1 from "./index.css"
10 | console.log("Classes from CSS:", classes1)
11 |
12 | import classes2 from "./alternate.sss"
13 | console.log("Classes from SSS:", classes2)
14 |
15 | import classes3 from "./classic.sass"
16 | console.log("Classes from Sass:", classes3)
17 |
18 | import classes4 from "./classic.scss"
19 | console.log("Classes from SCSS:", classes4)
20 |
21 | import url from "./logo.svg"
22 | console.log("Logo URL:", url)
23 |
24 | console.log("Package", process.env.NAME, process.env.VERSION)
25 | console.log("Target", process.env.TARGET)
26 |
27 | console.log("ES2016 Enabled:", 2 ** 2 === 4)
28 |
29 | new Promise((resolve, reject) => {
30 | resolve("resolved")
31 | }).then((first) => {
32 | console.log("Promise:", first)
33 | })
34 |
35 | const CONSTANT = 123
36 | console.log("Constant:", CONSTANT)
37 |
38 | var myArray = [ 1, 2, 3 ]
39 | console.log("Supports Array.includes?:", myArray.includes && myArray.includes(2))
40 |
41 | var someArrayProducer = () => [ 4, 5 ]
42 | var mergedArray = [ 1, 2, 3, ...someArrayProducer(), 6 ]
43 | console.log("Supports Array merging:", mergedArray.length === 6)
44 |
45 | var mySet = new Set(myArray)
46 | console.log("Supports Set:", mySet.add(4));
47 |
48 | (function(supportsDefault = true) {
49 | console.log("Supports default parameters:", supportsDefault)
50 | })()
51 |
52 | /* eslint-disable no-shadow */
53 | let testVariable = "outer"
54 | {
55 | let testVariable = "inner"
56 | console.log("X Value from inner scope:", testVariable)
57 | }
58 | console.log("X Value from outer scope:", testVariable)
59 |
60 | var source = { first: 1, second: 2 }
61 | var destructed = { third: 3, ...source }
62 | console.log("Destructed:", destructed)
63 |
64 | class MyClass {
65 | constructor() {
66 | console.log("Called constructor")
67 | this.helper()
68 | }
69 |
70 | helper() {
71 | console.log("Called helper")
72 | }
73 | }
74 |
75 | async function returnLate() {
76 | await new Promise((resolve, reject) => {
77 | setTimeout(resolve, 300)
78 | })
79 | }
80 | console.log("Test Async:", returnLate() instanceof Promise)
81 |
82 | console.log("Initialized class:", new MyClass())
83 |
84 | var ReactTest = function() {}
85 |
86 | var React = {
87 | createElement(TestClass) {
88 | return new TestClass()
89 | }
90 | }
91 |
92 | console.log("React Enabled:", Hello instanceof ReactTest)
93 |
94 | // This is currently not supported by Rollup and throws a syntax error
95 | // https://github.com/rollup/rollup/issues/1325
96 | // It's currently stage3 not yet stage4. See also:
97 | // https://tc39.github.io/proposal-dynamic-import/
98 | console.log("Dynamic Import returns Promise:", import("lodash/isArray") instanceof Promise)
99 |
--------------------------------------------------------------------------------
/test/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # *Prepublish* [![Sponsored by][sponsor-img]][sponsor] [![Version][npm-version-img]][npm] [![Downloads][npm-downloads-img]][npm] [![Build Status Unix][travis-img]][travis] [![Build Status Windows][appveyor-img]][appveyor] [![Dependencies][deps-img]][deps]
2 |
3 | *Prepublish* is a solution for simplifying pre-publishing typical JavaScript projects for publishing to NPM.
4 |
5 | [sponsor]: https://www.sebastian-software.de
6 | [deps]: https://david-dm.org/sebastian-software/prepublish
7 | [npm]: https://www.npmjs.com/package/prepublish
8 | [travis]: https://travis-ci.org/sebastian-software/prepublish
9 | [appveyor]: https://ci.appveyor.com/project/swernerx/prepublish/branch/master
10 |
11 | [sponsor-img]: https://badgen.net/badge/Sponsored%20by/Sebastian%20Software/692446
12 | [deps-img]: https://badgen.net/david/dep/sebastian-software/prepublish
13 | [npm-downloads-img]: https://badgen.net/npm/dm/prepublish
14 | [npm-version-img]: https://badgen.net/npm/v/prepublish
15 | [travis-img]: https://badgen.net/travis/sebastian-software/prepublish?label=unix%20build
16 | [appveyor-img]: https://badgen.net/appveyor/ci/swernerx/prepublish?label=windows%20build
17 |
18 |
19 | ## Transpilers
20 |
21 | *Prepublish* relies on the [Babel Preset Edge](https://www.npmjs.com/package/babel-preset-edge) for producing forward-looking optimistic code for your code base.
22 |
23 |
24 | ## Output Targets
25 |
26 | *Prepublish* produces exports of your sources depending on the entries of your packages `package.json`. It supports
27 | building for *CommonJS* and well as with ES Modules (ESM). Just add the relevant entries to
28 | the configuration.
29 |
30 | - CommonJS Output: `main`
31 | - ESM Output: `module`
32 |
33 | Basic Example:
34 |
35 | ```json
36 | {
37 | "name": "mypackage",
38 | "main": "lib/main.cjs.js",
39 | "module": "lib/main.esm.js"
40 | }
41 | ```
42 |
43 | To offer separate NodeJS and Browser builds use one of the following keys for the browser bundle: `browser` or `web`. These bundles are always exported as ES Modules (ESM) as we have the assumption that they are bundled by another tool like Webpack or Rollup before usage.
44 |
45 | Example:
46 |
47 | ```json
48 | {
49 | "name": "mypackage",
50 | "main": "lib/main.cjs.js",
51 | "module": "lib/main.esm.js",
52 | "browser": "lib/main.browser.js"
53 | }
54 | ```
55 |
56 |
57 | ## Input Entries
58 |
59 | You might wonder how to produce a browser bundle from a different input. This is actually pretty easy. Your package just have to follow this convention.
60 |
61 | The files are looked up for an order. The first match is being used.
62 |
63 | ### Entries for NodeJS targets
64 |
65 | - `src/node/public.js`
66 | - `src/node/export.js`
67 | - `src/node.js`
68 | - `src/server/public.js`
69 | - `src/server/export.js`
70 | - `src/server.js`
71 | - `src/server.js`
72 | - `src/public.js`
73 | - `src/export.js`
74 | - `src/index.js`
75 |
76 | ### Sources for the Browser targets
77 |
78 | - `src/web/public.js`
79 | - `src/web/export.js`
80 | - `src/web.js`
81 | - `src/browser/public.js`
82 | - `src/browser/export.js`
83 | - `src/browser.js`
84 | - `src/client/public.js`
85 | - `src/client/export.js`
86 | - `src/client.js`
87 |
88 | ### Sources for binary targets
89 |
90 | - `src/cli.js`
91 | - `src/binary.js`
92 | - `src/script.js`
93 |
94 |
95 | ## Targetting ES2015
96 |
97 | You are able to export modules for either ES5 compatible environments or for more modern platforms, too.
98 |
99 | Note: To use these non-standard bundle outputs requires some tweaks on the bundling phase of the application, too (e.g. in Webpack). This is because we are using non-standardized configuration keys in package.json. Typically just append either `:es2015` or `:modern` to your normal targets:
100 |
101 | - CommonJS Output for NodeJS with ES2015 kept intact: `main:es2015`
102 | - ES Modules Output for NodeJS with ES2015 kept intact: `module:es2015`
103 | - Browser Output as ES Modules with ES2015 kept intact: `browser:es2015`
104 |
105 | While `es2015` is exactly a requirement for the client to have full ES2015 support, `modern` is even more modern adding things from ES2017 to the list like `async`/`await`. Modern is regularly updated inside our [Babel Preset](https://github.com/sebastian-software/babel-preset-edge). It is by no way a never changing stable target.
106 |
107 | Example Configuration:
108 |
109 | ```json
110 | {
111 | "name": "mypackage",
112 | "main": "lib/main-cjs.js",
113 | "module": "lib/main-esm.js",
114 | "browser": "lib/main-browser.js",
115 | "main:es2015": "lib/main.cjs.es2015.js",
116 | "module:es2015": "lib/main.esm.es2015.js",
117 | "browser:es2015": "lib/main.browser.es2015.js"
118 | }
119 | ```
120 |
121 | To make sense of all these new modules it would help to produce two different outputs. One for classic browsers and one for modern browsers. ES2015 enabled features are [rapidly catching up in performance](https://kpdecker.github.io/six-speed/). Some features are pretty hard to rework for older browsers like Generators, Async/Await, or even Block Scope. Therefor we think there is no need for sending ES2015-capable clients the fully transpiled code down the wire. Keep in mind that you have to implement some basic client detection to send one or the other file to the matching client.
122 |
123 | BTW: The modern builds [make a lot of sense during development](https://medium.com/@gajus/dont-use-babel-transpilers-when-debugging-an-application-890ee528a5b3) as it results in shorter transpiler runtimes.
124 |
125 |
126 | ## Binary Output
127 |
128 | Additionally `prepublish` is capable in generating for binary targets.
129 |
130 | This generates a `mypackage` binary which is generated from the matching source file.
131 |
132 | Binaries are generated from one of these source files:
133 |
134 | - `src/cli.js`
135 | - `src/binary.js`
136 | - `src/script.js`
137 |
138 | Example Configuration:
139 |
140 | ```json
141 | {
142 | "name": "mypackage",
143 | "bin": {
144 | "mypackage": "bin/mypackage"
145 | }
146 | }
147 | ```
148 |
149 | Prepublish automatically choses the matching NodeJS version from your `engines` configuration:
150 |
151 | ```json
152 | "engines": {
153 | "node": ">=6.0.0",
154 | "npm": ">=5.0.0",
155 | "yarn": ">=1.0.0"
156 | }
157 | ```
158 |
159 | inside your `package.json`. This example configuration targets any version of NodeJS matching at least the v6 capabilities.
160 |
161 |
162 |
163 |
164 | ## Related Content
165 |
166 | - [Setting up multi-platform npm packages](http://2ality.com/2017/04/setting-up-multi-platform-packages.html)
167 |
168 |
169 |
170 | ## Installation
171 |
172 | ### NPM
173 |
174 | ```console
175 | $ npm install --save-dev prepublish
176 | ```
177 |
178 | ### Yarn
179 |
180 | ```console
181 | $ yarn add --dev prepublish
182 | ```
183 |
184 |
185 |
186 | ## Usage
187 |
188 | *Prepublish* comes with a binary which can be called from within your `scripts` section in the `package.json` file.
189 |
190 | ```json
191 | "scripts": {
192 | "prepare": "prepublish"
193 | }
194 | ```
195 |
196 | There is also some amount of parameters you can use if the auto detection of your library does not work out correctly.
197 |
198 | ```
199 | Usage
200 | $ prepublish
201 |
202 | Options
203 | --entry-node Entry file for NodeJS target [default = auto]
204 | --entry-web Entry file for Browser target [default = auto]
205 | --entry-binary Entry file for Binary target [default = auto]
206 |
207 | --output-folder Configure the output folder [default = auto]
208 |
209 | -x, --minified Enabled minification of output files
210 | -m, --sourcemap Create a source map file during processing
211 |
212 | --target-modern Binaries should target Node v8 LTS instead of Node v6 LTS.
213 |
214 | -v, --verbose Verbose output mode [default = false]
215 | -q, --quiet Quiet output mode [default = false]
216 | ```
217 |
218 |
219 | ## License
220 |
221 | [Apache License; Version 2.0, January 2004](http://www.apache.org/licenses/LICENSE-2.0)
222 |
223 | ## Copyright
224 |
225 |
226 |
227 | Copyright 2016-2018 [Sebastian Software GmbH](http://www.sebastian-software.de)
228 |
--------------------------------------------------------------------------------
/src/cli.js:
--------------------------------------------------------------------------------
1 | import { resolve, relative, isAbsolute, dirname } from "path"
2 | import { eachOfSeries } from "async"
3 | import { camelCase } from "lodash"
4 | import fileExists from "file-exists"
5 | import meow from "meow"
6 | import chalk from "chalk"
7 | import { get as getRoot } from "app-root-dir"
8 |
9 | import { rollup } from "rollup"
10 | import rebase from "rollup-plugin-rebase"
11 | import nodeResolve from "rollup-plugin-node-resolve"
12 | import cjsPlugin from "rollup-plugin-commonjs"
13 | import jsonPlugin from "rollup-plugin-json"
14 | import yamlPlugin from "rollup-plugin-yaml"
15 | import replacePlugin from "rollup-plugin-replace"
16 | import executablePlugin from "rollup-plugin-executable"
17 |
18 | import createBabelConfig from "./createBabelConfig"
19 | import getBanner from "./getBanner"
20 |
21 | const ROOT = getRoot()
22 | const PKG_CONFIG = require(resolve(ROOT, "package.json"))
23 |
24 | let cache
25 |
26 | /* eslint-disable no-console */
27 |
28 | const command = meow(
29 | `
30 | Usage
31 | $ prepublish
32 |
33 | Options
34 | --input-node Input file for NodeJS target [default = auto]
35 | --input-web Input file for Browser target [default = auto]
36 | --input-binary Input file for Binary target [default = auto]
37 |
38 | --output-folder Configure the output folder [default = auto]
39 |
40 | -x, --minified Enabled minification of output files
41 | -m, --sourcemap Create a source map file during processing
42 |
43 | -v, --verbose Verbose output mode [default = false]
44 | -q, --quiet Quiet output mode [default = false]
45 | `,
46 | {
47 | flags: {
48 | inputNode: {
49 | default: null
50 | },
51 |
52 | inputWeb: {
53 | default: null
54 | },
55 |
56 | inputBinary: {
57 | default: null
58 | },
59 |
60 | outputFolder: {
61 | default: null
62 | },
63 |
64 | minified: {
65 | default: false,
66 | alias: "x"
67 | },
68 |
69 | sourcemap: {
70 | default: true,
71 | alias: "m"
72 | },
73 |
74 | verbose: {
75 | default: false,
76 | alias: "v"
77 | },
78 |
79 | quiet: {
80 | default: false,
81 | alias: "q"
82 | }
83 | }
84 | }
85 | )
86 |
87 | const verbose = command.flags.verbose
88 | const quiet = command.flags.quiet
89 |
90 | if (verbose) {
91 | console.log("Flags:", command.flags)
92 | }
93 |
94 | // Handle special case to generate a binary file based on config in package.json
95 | const binaryConfig = PKG_CONFIG.bin
96 | let binaryOutput = null
97 | if (binaryConfig) {
98 | for (const name in binaryConfig) {
99 | binaryOutput = binaryConfig[name]
100 | break
101 | }
102 | }
103 |
104 | /* eslint-disable dot-notation */
105 | const outputFileMatrix = {
106 | // NodeJS es5 Target
107 | "node-es5-cjs": PKG_CONFIG["main"] || null,
108 | "node-es5-esm": PKG_CONFIG["module"] || PKG_CONFIG["jsnext:main"] || null,
109 |
110 | // NodeJS ES2015 Target
111 | "node-es2015-cjs": PKG_CONFIG["main:es2015"] || null,
112 | "node-es2015-esm": PKG_CONFIG["es2015"] || PKG_CONFIG["module:es2015"] || null,
113 |
114 | // NodeJS Modern Target
115 | "node-modern-cjs": PKG_CONFIG["main:modern"] || null,
116 | "node-modern-esm": PKG_CONFIG["module:modern"] || null,
117 |
118 | // Browser es5 Target
119 | "web-es5-esm": PKG_CONFIG["web"] || PKG_CONFIG["browser"] || null,
120 |
121 | // Browser ES2015 Target
122 | "web-es2015-esm": PKG_CONFIG["web:es2015"] || PKG_CONFIG["browser:es2015"] || null,
123 |
124 | // Browser Modern Target
125 | "web-modern-esm": PKG_CONFIG["web:modern"] || PKG_CONFIG["browser:modern"] || null,
126 |
127 | // Binary Target
128 | "binary-binary-cjs": binaryOutput || null
129 | }
130 |
131 | const outputFolder = command.flags.outputFolder
132 | if (outputFolder) {
133 | outputFileMatrix["node-es5-cjs"] = `${outputFolder}/node.es5.cjs.js`
134 | outputFileMatrix["node-es5-esm"] = `${outputFolder}/node.es5.esm.js`
135 |
136 | outputFileMatrix["node-es2015-cjs"] = `${outputFolder}/node.es2015.cjs.js`
137 | outputFileMatrix["node-es2015-esm"] = `${outputFolder}/node.es2015.esm.js`
138 |
139 | outputFileMatrix["node-modern-cjs"] = `${outputFolder}/node.modern.cjs.js`
140 | outputFileMatrix["node-modern-esm"] = `${outputFolder}/node.modern.esm.js`
141 |
142 | outputFileMatrix["web-es5-esm"] = `${outputFolder}/web.es5.esm.js`
143 | outputFileMatrix["web-es2015-esm"] = `${outputFolder}/web.es2015.esm.js`
144 | outputFileMatrix["web-modern-esm"] = `${outputFolder}/web.modern.esm.js`
145 | }
146 |
147 | const name = PKG_CONFIG.name || camelCase(PKG_CONFIG.name)
148 | const banner = getBanner(PKG_CONFIG)
149 | const targets = {}
150 | const formats = [ "esm", "cjs" ]
151 |
152 | if (command.flags.inputNode) {
153 | targets.node = [ command.flags.inputNode ]
154 | } else {
155 | targets.node = [
156 | "src/node/public.js",
157 | "src/node/export.js",
158 | "src/node.js",
159 |
160 | "src/server/public.js",
161 | "src/server/export.js",
162 | "src/server.js",
163 |
164 | "src/server.js",
165 | "src/public.js",
166 | "src/export.js",
167 | "src/index.js"
168 | ]
169 | }
170 |
171 | if (command.flags.inputWeb) {
172 | targets.web = [ command.flags.inputWeb ]
173 | } else {
174 | targets.web = [
175 | "src/web/public.js",
176 | "src/web/export.js",
177 | "src/web.js",
178 |
179 | "src/browser/public.js",
180 | "src/browser/export.js",
181 | "src/browser.js",
182 |
183 | "src/client/public.js",
184 | "src/client/export.js",
185 | "src/client.js"
186 | ]
187 | }
188 |
189 | if (command.flags.inputBinary) {
190 | targets.binary = [ command.flags.inputBinary ]
191 | } else {
192 | targets.binary = [ "src/cli.js", "src/binary.js", "src/script.js" ]
193 | }
194 |
195 | /* eslint-disable max-params */
196 | try {
197 | eachOfSeries(targets, (envInputs, targetId, envCallback) => {
198 | const input = lookupBest(envInputs)
199 | if (input) {
200 | if (!quiet) {
201 | console.log(`Using input ${chalk.blue(input)} for target ${chalk.blue(targetId)}`)
202 | }
203 |
204 | eachOfSeries(
205 | formats,
206 | (format, formatIndex, formatCallback) => {
207 | const configs = createBabelConfig({
208 | minified: command.flags.minified,
209 | presets: [],
210 | plugins: []
211 | })
212 |
213 | eachOfSeries(
214 | configs,
215 | (currentTranspiler, transpilerId, variantCallback) => {
216 | const outputFile = outputFileMatrix[`${targetId}-${transpilerId}-${format}`]
217 | if (outputFile) {
218 | return bundleTo({
219 | input,
220 | targetId,
221 | transpilerId,
222 | currentTranspiler,
223 | format,
224 | outputFile,
225 | variantCallback
226 | })
227 | } else {
228 | return variantCallback(null)
229 | }
230 | },
231 | formatCallback
232 | )
233 | },
234 | envCallback
235 | )
236 | } else {
237 | envCallback(null)
238 | }
239 | })
240 | } catch (error) {
241 | /* eslint-disable no-process-exit */
242 | console.error(error)
243 | process.exit(1)
244 | }
245 |
246 | function lookupBest(candidates) {
247 | const filtered = candidates.filter(fileExists.sync)
248 | return filtered[0]
249 | }
250 |
251 | function isRelative(dependency) {
252 | return (/^\./).exec(dependency)
253 | }
254 |
255 | function bundleTo({
256 | input,
257 | targetId,
258 | transpilerId,
259 | currentTranspiler,
260 | format,
261 | outputFile,
262 | variantCallback
263 | }) {
264 | if (!quiet) {
265 | /* eslint-disable max-len */
266 | console.log(
267 | `${chalk.green(">>> Bundling")} ${chalk.magenta(PKG_CONFIG.name)}-${chalk.magenta(
268 | PKG_CONFIG.version
269 | )} as ${chalk.blue(transpilerId)} defined as ${chalk.blue(format)} to ${chalk.green(
270 | outputFile
271 | )}...`
272 | )
273 | }
274 |
275 | const prefix = "process.env."
276 | const variables = {
277 | [`${prefix}NAME`]: JSON.stringify(PKG_CONFIG.name),
278 | [`${prefix}VERSION`]: JSON.stringify(PKG_CONFIG.version),
279 | [`${prefix}TARGET`]: JSON.stringify(targetId)
280 | }
281 |
282 | const rebasePlugin = rebase({ verbose })
283 | return rollup({
284 | input,
285 | cache,
286 | onwarn: (error) => {
287 | console.warn(chalk.red(` - ${error.message}`))
288 | },
289 | external(dependency) {
290 | // Very simple externalization:
291 | // We exclude all files from NodeJS resolve basically which are not relative to current file.
292 | // We also bundle absolute paths, these are just an intermediate step in rollup resolving files and
293 | // as we do not support resolving from node_modules (we never bundle these) we only hit this code
294 | // path for originally local dependencies.
295 | return !(dependency === input || isRelative(dependency) || isAbsolute(dependency))
296 | },
297 | plugins: [
298 | rebasePlugin,
299 | replacePlugin(variables),
300 | cjsPlugin({
301 | include: "node_modules/**"
302 | }),
303 | yamlPlugin(),
304 | jsonPlugin(),
305 | currentTranspiler,
306 | transpilerId === "binary" ? executablePlugin() : null
307 | ].filter(Boolean)
308 | })
309 | .then((bundle) =>
310 | bundle.write({
311 | format,
312 | name,
313 | banner: transpilerId === "binary" ? `#!/usr/bin/env node\n\n${banner}` : banner,
314 | sourcemap: command.flags.sourcemap,
315 | file: outputFile
316 | })
317 | )
318 | .then(() => variantCallback(null))
319 | .catch((error) => {
320 | console.error(error)
321 | variantCallback(`Error during bundling ${format}: ${error}`)
322 | })
323 | }
324 |
--------------------------------------------------------------------------------
/license:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2016-2017 Sebastian Software GmbH
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------