Skip to content

Commit

Permalink
Merge pull request #1 from dora-js/create-inject
Browse files Browse the repository at this point in the history
enhance inject weinre
  • Loading branch information
soda-x committed Jul 11, 2016
2 parents bb01307 + b04c293 commit cbf750a
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 30 deletions.
2 changes: 0 additions & 2 deletions .eslintignore

This file was deleted.

3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"parser": "babel-eslint",
"extends": "eslint-config-airbnb/base",
"rules": {
"no-console": [0]
"no-console": [0],
"no-param-reassign": [0]
},
"ecmaFeatures": {
"generators": 1,
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
"dependencies": {
"coffee-script": "^1.10.0",
"internal-ip": "^1.2.0",
"webpack-core": "^0.6.8",
"weinre": "^2.0.0-pre-I0Z7U9OV"
},
"devDependencies": {
"atool-build": "0.7.x",
"atool-build": "0.7.x",
"babel-cli": "^6.10.1",
"babel-core": "^6.10.4",
"babel-eslint": "^6.1.0",
Expand Down Expand Up @@ -52,4 +53,4 @@
"package.json",
"README.md"
]
}
}
47 changes: 30 additions & 17 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { existsSync, readFileSync } from 'fs';
import { parse } from 'url';
import { join } from 'path';

import { getInjectWeinreContent } from './util';
import InjectScript from './injectScript';

const localIP = require('internal-ip')();

/**
Expand All @@ -13,7 +16,7 @@ import { run } from 'weinre';

let defaultOpts = {
httpPort: 8990,
boundHost: 'localhost',
boundHost: localIP,
verbose: false,
debug: false,
readTimeout: 5,
Expand All @@ -22,33 +25,30 @@ let defaultOpts = {
};

export default {
'middleware.before'() {
const { log, query } = this;
defaultOpts.boundHost = localIP;
defaultOpts = { ...defaultOpts, ...query };
name: 'dora-plugin-weinre',

'middleware.before'() {
const { log } = this;
run(defaultOpts);
log.info(`weinre is started, servering at http://${defaultOpts.boundHost}:${defaultOpts.httpPort}`);
},

'middleware'() {
const { cwd } = this;
const { cwd, get } = this;

const compiler = get('compiler');
if (!compiler) {
throw new Error('[error] must used together with dora-plugin-webpack');
}
return function* middleFunc(next) {
const fileName = parse(this.url).pathname;
const pathName = parse(this.url).pathname;
const fileName = pathName === '/' ? 'index.html' : pathName;
const filePath = join(cwd, fileName);
const isHTML = /\.html?$/.test(this.url.split('?')[0]);
const isHTML = /\.html?$/.test(fileName);
if (isHTML && existsSync(filePath)) {
const injectScript = `<script src='http://${defaultOpts.boundHost}:${defaultOpts.httpPort}/target/target-script-min.js#anonymous'></script>`;
const injectContent = getInjectWeinreContent(defaultOpts.boundHost, defaultOpts.httpPort);
const injectScript = `<script>${injectContent}</script>`;
let content = readFileSync(filePath, 'utf-8');
const docTypeReg = new RegExp('^\s*\<\!DOCTYPE\s*.+\>.*$', 'im');
const docType = content.match(docTypeReg);
if (docType) {
content = content.replace(docTypeReg, docType[0] + injectScript);
this.body = content;

return;
}
content = injectScript + content;
this.body = content;

Expand All @@ -57,4 +57,17 @@ export default {
yield next;
};
},

'webpack.updateConfig.finally'(webpackConfig) {
const { query } = this;

defaultOpts = { ...defaultOpts, ...query };

webpackConfig.plugins.push(new InjectScript({
boundHost: defaultOpts.boundHost,
httpPort: defaultOpts.httpPort,
}));

return webpackConfig;
},
};
33 changes: 33 additions & 0 deletions src/injectScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import ConcatSource from 'webpack-core/lib/ConcatSource';
import { getInjectWeinreContent } from './util';

export default class InjectScript {
static defaults = {
httpPort: 8990,
boundHost: 'localhost',
};

constructor(options) {
this.options = { ...InjectScript.defaults, ...options };
}

apply(compiler) {
compiler.plugin('compilation', compilation => {
const opts = this.options;
compilation.plugin('optimize-chunk-assets', (chunks, callback) => {
chunks.forEach(chunk => {
chunk.files.filter(file => /.(js)$/.test(file)).forEach(file => {
const injectContent = getInjectWeinreContent(opts.injectHost, opts.port);
compilation.assets[file] = new ConcatSource(
injectContent,
'\n',
compilation.assets[file]
);
});
});

callback();
});
});
}
}
21 changes: 21 additions & 0 deletions src/util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export function getInjectWeinreContent(host, port) {
const src = `http://${host}:${port}/target/target-script-min.js#anonymous`;
const injectContent = [
'// weinre',
'(function() {',
' if (typeof window === "undefined") { return };',
' window.onload = function() {',
' var id = "webpack-weinre-plugin-script";',
' if (document.getElementById(id)) { return; }',
' var el = document.createElement("script");',
' el.id = id;',
' el.async = true;',
` el.src = "${src}";`,
' document.body.appendChild(el);',
' }',
'}());',
'',
].join('\n');

return injectContent;
}
16 changes: 8 additions & 8 deletions test/index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import { join } from 'path';
import request from 'supertest';

const localIP = require('internal-ip')();
const port = '12345';
const port = '1234';

describe('index', () => {
describe('livereload.js', () => {
describe('weinre', () => {
const cwd = process.cwd();
before(done => {
process.chdir(join(__dirname, './fixtures/normal'));
dora({
port,
plugins: ['../../../src/index?{httpPort:8888}'],
plugins: ['dora-plugin-webpack', '../../../src/index?{httpPort:8888}'],
cwd: join(__dirname, './fixtures/normal'),
}, done);
});
Expand Down Expand Up @@ -43,7 +43,7 @@ describe('index', () => {
.expect(200)
.end((err, res) => {
if (err) return done(err);
if (res.text.indexOf(`<script src='http://${localIP}:8888/target/target-script-min.js#anonymous'></script>`) < 0) {
if (res.text.indexOf('// weinre') < 0) {
const e = new Error('/target/target-script-min.js#anonymous is not injected');

return done(e);
Expand All @@ -59,7 +59,7 @@ describe('index', () => {
.expect(200)
.end((err, res) => {
if (err) return done(err);
if (res.text.indexOf(`<script src='http://${localIP}:8888/target/target-script-min.js#anonymous'></script>`) < 0) {
if (res.text.indexOf('// weinre') < 0) {
const e = new Error('/target/target-script-min.js#anonymous is not injected');

return done(e);
Expand All @@ -69,14 +69,14 @@ describe('index', () => {
});
});

it('GET /index.js should not be handled', done => {
it('GET /index.js should be handled', done => {
request(`http://localhost:${port}`)
.get('/index.js')
.expect(200)
.end((err, res) => {
if (err) return done(err);
if (res.text.indexOf('console.log(1);') < 0) {
const e = new Error('other types of files should not be handled');
if (res.text.indexOf('// weinre') < 0) {
const e = new Error('other types of files should be handled');

return done(e);
}
Expand Down

0 comments on commit cbf750a

Please sign in to comment.