Reputation: 9721
I'm writing a bookmarklet. I need to prepend "javascript:"
to the compiled, minified JavaScript. I'm looking for a way to accomplish this using an NPM package.json
script.
{
"scripts": {
"oar:transpile-typescript": "tsc --target es6 --lib dom,es6 ./OarBookmarklet/Oar.ts",
"oar:minify-javascript": "jsmin -o ./OarBookmarklet/oar.min.js ./OarBookmarklet/oar.js",
"oar:prepend-javascript": "[??? prepend `javascript:` to minified JavaScript ???]",
"oar": "run-s oar:transpile-typescript oar:minify-javascript oar:prepend-javascript",
"build": "run-s oar"
}
}
Upvotes: 1
Views: 3737
Reputation: 24952
For a cross-platform solution utilize node.js and it's builtin fs.readFileSync(...)
and fs.writeFileSync(...)
. This way it doesn't matter which shell your npm script runs in (sh
, cmd.exe
, bash
, bash.exe
, pwsh
, ...
)
To achieve this consider either of the following two solutions - they're essentially the same just different methods of application.
Create the following script, lets save it as prepend.js in the root of the project directory, i.e. at the same level as where package.json resides.
prepend.js
const fs = require('fs');
const filepath = './OarBookmarklet/oar.min.js';
const data = fs.readFileSync(filepath);
fs.writeFileSync(filepath, 'javascript:' + data);
package.json
Define the oar:prepend-javascript
npm script in package.json as follows::
"scripts": {
...
"oar:prepend-javascript": "node prepend",
...
},
Note: Above node.js invokes the script and performs the required task. If you choose to save prepend.js in a different directory than the aforementioned then ensure you define the correct path to it, i.e. "oar:prepend-javascript": "node ./some/other/path/to/prepend.js"
Alternatively, you can inline the content of prepend.js in your npm script, therefore negating the use of a separate .js
file.
package.json
Define the oar:prepend-javascript
script in package.json as follows:
"scripts": {
...
"oar:prepend-javascript": "node -e \"const fs = require('fs'); const fp = './OarBookmarklet/oar.min.js'; const d = fs.readFileSync(fp); fs.writeFileSync(fp, 'javascript:' + d);\""
...
},
Note: Here the nodejs command line option -e
is utilized to evaluate the inline JavaScript.
Upvotes: 2
Reputation: 5808
If this is running on something Unix-like then:
(printf 'javascript:' ; cat ./OarBookmarklet/oar.min.js) > ./OarBookmarklet/oar.bm.min.js
should do the job.
Edit in response to OP's comment:
My execution environment is Windows, ...
In that case you should be able to use:
(set /p junk="javascript:" <nul & type ./OarBookmarklet/oar.min.js) > ./OarBookmarklet/oar.bm.min.js
The set /p ... <nul
weirdness is a way to get some text sent to stdout without a newline being appended to it.
Upvotes: 1