Skip to content

Commit 04646d2

Browse files
author
Gyumeijie
committed
Init commit
0 parents  commit 04646d2

File tree

9 files changed

+352
-0
lines changed

9 files changed

+352
-0
lines changed

.gitignore

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
# Created by https://www.gitignore.io/api/macos,visualstudiocode
3+
4+
### macOS ###
5+
# General
6+
.DS_Store
7+
.AppleDouble
8+
.LSOverride
9+
10+
# Icon must end with two \r
11+
Icon
12+
13+
# Thumbnails
14+
._*
15+
16+
# Files that might appear in the root of a volume
17+
.DocumentRevisions-V100
18+
.fseventsd
19+
.Spotlight-V100
20+
.TemporaryItems
21+
.Trashes
22+
.VolumeIcon.icns
23+
.com.apple.timemachine.donotpresent
24+
25+
# Directories potentially created on remote AFP share
26+
.AppleDB
27+
.AppleDesktop
28+
Network Trash Folder
29+
Temporary Items
30+
.apdisk
31+
32+
### VisualStudioCode ###
33+
.vscode/*
34+
!.vscode/settings.json
35+
!.vscode/tasks.json
36+
!.vscode/launch.json
37+
!.vscode/extensions.json
38+
39+
node_modules/
40+
package-lock.json
41+
42+
# End of https://www.gitignore.io/api/macos,visualstudiocode

.npmignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
example/
2+
.gitignore

README.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Write to file plugin for webpack(v3)
2+
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
3+
4+
This is a simple webpack plugin for writing data to file.
5+
6+
# Features
7+
1. support creating directory recursively
8+
2. support data of function type, which allows processing data in complex situation
9+
3. support native options of underlying writeFileSync
10+
4. support protection of an exsited file
11+
12+
# Installation
13+
`npm install --save-dev write-file-webpack`
14+
15+
# Usage
16+
The data to be written can be either a simple javascript variable, or a function which returns some data.
17+
18+
```javascript
19+
const WriteToFilePlugin = require('write-file-webpack');
20+
21+
module.exports = {
22+
...
23+
plugins: [
24+
new WriteToFilePlugin({
25+
filename: 'path/to/write/file',
26+
data: 'console.log("write to file")'
27+
})
28+
]
29+
...
30+
}
31+
```
32+
33+
```javascript
34+
const WriteToFilePlugin = require('write-file-webpack');
35+
36+
module.exports = {
37+
...
38+
plugins: [
39+
new WriteToFilePlugin({
40+
filename: 'path/to/write/file',
41+
data: function () {
42+
return "console.log('write to file')"
43+
}
44+
})
45+
]
46+
...
47+
}
48+
```
49+
50+
If the `data` is provided as a `function`, we can do more operations than just simply returning the data to be written. For example, if we wanna write to a file parts of an exsited file say `package.json`, and more specifically, removing the `dependencies` and `devDependencies` items, with `write-file-webpack` we can do this:
51+
52+
```javascript
53+
const WriteToFilePlugin = require('write-file-webpack');
54+
const config = require('./package.json');
55+
56+
module.exports = {
57+
...
58+
plugins: [
59+
new WriteToFilePlugin({
60+
filename: 'path/to/write/package.json',
61+
data: function () {
62+
return JSON.stringify({
63+
...config,
64+
dependencies: undefined,
65+
devDependencies: undefined,
66+
});
67+
}
68+
})
69+
]
70+
...
71+
}
72+
```
73+
Of course, if we want to copy the whole content of a existed file, there is webpack plugin called `copy-webpack-plugin`.
74+
75+
# Support
76+
`node >= 6` and `webpack v3`
77+
78+
# Options
79+
- filename (**required**)
80+
- data (**required**)
81+
- override
82+
`<boolean> Default: true`, if set to false, no data will be written to an exsited file
83+
- encoding
84+
`<string> | <null> Default: 'utf8'`
85+
- mode
86+
`<integer> Default: 0o666`
87+
- flag
88+
`<string> Default: 'w'`
89+
90+
For more information about `encoding`, `mode`, and `flag` please refer to [node writeFile](https://nodejs.org/docs/latest-v9.x/api/fs.html#fs_fs_writefilesync_file_data_options).

example/dist/subdir/test.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
console.log('hello webpack')

example/dummyInput.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
console.log("dummy")

example/dummyOutput.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/******/ (function(modules) { // webpackBootstrap
2+
/******/ // The module cache
3+
/******/ var installedModules = {};
4+
/******/
5+
/******/ // The require function
6+
/******/ function __webpack_require__(moduleId) {
7+
/******/
8+
/******/ // Check if module is in cache
9+
/******/ if(installedModules[moduleId]) {
10+
/******/ return installedModules[moduleId].exports;
11+
/******/ }
12+
/******/ // Create a new module (and put it into the cache)
13+
/******/ var module = installedModules[moduleId] = {
14+
/******/ i: moduleId,
15+
/******/ l: false,
16+
/******/ exports: {}
17+
/******/ };
18+
/******/
19+
/******/ // Execute the module function
20+
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
21+
/******/
22+
/******/ // Flag the module as loaded
23+
/******/ module.l = true;
24+
/******/
25+
/******/ // Return the exports of the module
26+
/******/ return module.exports;
27+
/******/ }
28+
/******/
29+
/******/
30+
/******/ // expose the modules object (__webpack_modules__)
31+
/******/ __webpack_require__.m = modules;
32+
/******/
33+
/******/ // expose the module cache
34+
/******/ __webpack_require__.c = installedModules;
35+
/******/
36+
/******/ // define getter function for harmony exports
37+
/******/ __webpack_require__.d = function(exports, name, getter) {
38+
/******/ if(!__webpack_require__.o(exports, name)) {
39+
/******/ Object.defineProperty(exports, name, {
40+
/******/ configurable: false,
41+
/******/ enumerable: true,
42+
/******/ get: getter
43+
/******/ });
44+
/******/ }
45+
/******/ };
46+
/******/
47+
/******/ // getDefaultExport function for compatibility with non-harmony modules
48+
/******/ __webpack_require__.n = function(module) {
49+
/******/ var getter = module && module.__esModule ?
50+
/******/ function getDefault() { return module['default']; } :
51+
/******/ function getModuleExports() { return module; };
52+
/******/ __webpack_require__.d(getter, 'a', getter);
53+
/******/ return getter;
54+
/******/ };
55+
/******/
56+
/******/ // Object.prototype.hasOwnProperty.call
57+
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
58+
/******/
59+
/******/ // __webpack_public_path__
60+
/******/ __webpack_require__.p = "";
61+
/******/
62+
/******/ // Load entry module and return exports
63+
/******/ return __webpack_require__(__webpack_require__.s = 0);
64+
/******/ })
65+
/************************************************************************/
66+
/******/ ([
67+
/* 0 */
68+
/***/ (function(module, exports) {
69+
70+
console.log("dummy")
71+
72+
/***/ })
73+
/******/ ]);

example/webpack.config.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const path = require('path');
2+
const WriteToFilePlugin = require('../index');
3+
4+
module.exports = {
5+
entry: path.resolve(__dirname, 'dummyInput.js'),
6+
output: {
7+
filename: 'dummyOutput.js',
8+
path: path.resolve(__dirname)
9+
},
10+
plugins: [
11+
new WriteToFilePlugin({
12+
filename: path.resolve(__dirname, 'dist/subdir/test.js'),
13+
data: function () {
14+
return "console.log('hello webpack')"
15+
}
16+
})
17+
// new WriteToFilePlugin({
18+
// filename: './dist/build/test.js',
19+
// data: "console.log('hello webpack')"
20+
// })
21+
]
22+
}

index.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
var path = require('path');
2+
var fs = require('fs');
3+
4+
/*
5+
* Credits to https://stackoverflow.com/questions/31645738/how-to-create-full-path-with-nodes-fs-mkdirsync
6+
* Create directory recursively and support node < v10.12, from which version fs.mkdir support natively
7+
* `recursive` option
8+
*/
9+
var mkdir = function (targetDir) {
10+
var sep = path.sep;
11+
var initDir = path.isAbsolute(targetDir) ? sep : '';
12+
13+
return targetDir.split(sep).reduce(function (parentDir, childDir) {
14+
var curDir = path.resolve(parentDir, childDir);
15+
16+
try {
17+
fs.mkdirSync(curDir);
18+
} catch (err) {
19+
// If curDir already exists!
20+
if (err.code === 'EEXIST') {
21+
return curDir;
22+
}
23+
24+
// To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
25+
if (err.code === 'ENOENT') {
26+
// Throw the original parentDir error on curDir `ENOENT` failure.
27+
throw new Error('EACCES: permission denied, mkdir' + parentDir);
28+
}
29+
30+
var caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
31+
if (!caughtErr || caughtErr && targetDir === curDir) {
32+
// Throw if it's just the last created dir.
33+
throw err;
34+
}
35+
}
36+
37+
return curDir;
38+
}, initDir);
39+
}
40+
41+
42+
var WriteToFilePlugin = (function () {
43+
44+
function WriteToFilePlugin(options) {
45+
if (typeof options !== 'object') {
46+
throw new Error('options should be an object!');
47+
}
48+
49+
if (options.filename === undefined) {
50+
throw new Error('filename is required!');
51+
}
52+
53+
var basename = path.basename(options.filename);
54+
if ( basename === '.' || basename === '..' || basename === '') {
55+
throw new Error('illegal operation on a directory!');
56+
}
57+
58+
this.options = options;
59+
}
60+
61+
WriteToFilePlugin.prototype.apply = function(compiler) {
62+
var options = this.options;
63+
64+
compiler.plugin('done', function() {
65+
var data = options.data;
66+
67+
// Prevent accidentally overriding an existed file, which may be important.
68+
var override = (options.override === undefined || options.override) ? true : false;
69+
if (!override && fs.existsSync(options.filename)) {
70+
console.warn('The override option is set to flase, no data written to the file!');
71+
return;
72+
}
73+
74+
// Create the directory recursively if it not exists yet.
75+
var dir = path.dirname(options.filename);
76+
if (!fs.existsSync(dir)) {
77+
mkdir(dir);
78+
}
79+
80+
// Collect the options for underlying `writeFileSync`.
81+
var optionsForWriteFile = {};
82+
optionsForWriteFile.encoding = options.encoding || 'utf8';
83+
optionsForWriteFile.mode = options.mode || 0o666;
84+
optionsForWriteFile.flag = options.flag || 'w';
85+
86+
var dataToBeWritten = (typeof data === 'function') ? data() : data;
87+
fs.writeFileSync(options.filename, dataToBeWritten, optionsForWriteFile);
88+
});
89+
}
90+
91+
return WriteToFilePlugin;
92+
}());
93+
94+
module.exports = WriteToFilePlugin;

package.json

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "write-file-webpack",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"repository": {
7+
"type": "git",
8+
"url": "https://github.com/Gyumeijie/write-file-webpack.git"
9+
},
10+
"keywords": [
11+
"webpack",
12+
"webpack v3",
13+
"write",
14+
"file",
15+
"plugin",
16+
"webpack-plugin"
17+
],
18+
"scripts": {
19+
"start": "webpack --config example/webpack.config.js"
20+
},
21+
"author": "Gyumeijie",
22+
"license": "MIT",
23+
"homepage": "https://github.com/Gyumeijie/write-file-webpack#readme",
24+
"devDependencies": {
25+
"webpack": "^3.6.0"
26+
}
27+
}

0 commit comments

Comments
 (0)