Skip to content

Commit

Permalink
update service-worker creation process & tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Diablohu committed Jul 9, 2019
1 parent 9320845 commit 72e88c2
Show file tree
Hide file tree
Showing 11 changed files with 200 additions and 58 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

核心

- **错误修正**
- 修正:SPA `index.html` 中没有加载 `service-worker`
- 更新依赖包
- patch
- `@babel/plugin-proposal-object-rest-spread` -> _7.5.2_
Expand Down
9 changes: 7 additions & 2 deletions packages/koot/React/inject/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,19 @@ module.exports = ({
typeof process.env.KOOT_PWA_AUTO_REGISTER === 'string'
? JSON.parse(process.env.KOOT_PWA_AUTO_REGISTER)
: false;
if (pwaAuto && typeof injectCache.pathnameSW === 'string') {
if (
pwaAuto &&
(process.env.WEBPACK_BUILD_TYPE === 'spa' ||
typeof injectCache.pathnameSW === 'string')
) {
r += `<script id="__koot-pwa-register-sw" type="text/javascript">`;
if (isProd) {
r +=
`if ('serviceWorker' in navigator) {` +
`window.addEventListener('load', function() {` +
// + `navigator.serviceWorker.register("${injectCache.pathnameSW}?koot=${process.env.KOOT_VERSION}",`
`navigator.serviceWorker.register("${injectCache.pathnameSW}?koot=0.8",` +
`navigator.serviceWorker.register("${injectCache.pathnameSW ||
JSON.parse(process.env.KOOT_PWA_PATHNAME)}?koot=0.8",` +
`{scope: '/'}` +
`)` +
`.catch(err => {console.log('👩‍💻 Service Worker SUPPORTED. ERROR', err)})` +
Expand Down
4 changes: 2 additions & 2 deletions packages/koot/ReactApp/server/middlewares/isomorphic/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,15 @@ const middlewareIsomorphic = (options = {}) => {
entrypoints.set(thisLocaleId, chunkmap[l]['.entrypoints']);
filemap.set(thisLocaleId, chunkmap[l]['.files']);
templateInjectCache.set(thisLocaleId, {
pathnameSW: getSWPathname(thisLocaleId)
pathnameSW: getSWPathname(chunkmap[l])
});
// styleMap.set(thisLocaleId, {})
}
} else {
entrypoints.set('', chunkmap['.entrypoints']);
filemap.set('', chunkmap['.files']);
templateInjectCache.set('', {
pathnameSW: getSWPathname()
pathnameSW: getSWPathname(chunkmap)
});
// styleMap.set('', {})
}
Expand Down
14 changes: 8 additions & 6 deletions packages/koot/ReactSPA/inject.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
const validateInject = require('../React/validate-inject')
const validateInject = require('../React/validate-inject');

module.exports = (options = {}) => {
const {
injectCache,
localeId,
filemap,
entrypoints,
needInjectCritical,
compilation,
} = options
compilation
} = options;

return validateInject({
injectCache,
localeId,

filemap,
Expand All @@ -22,6 +24,6 @@ module.exports = (options = {}) => {
stylesHtml: '',
reduxHtml: '',

needInjectCritical,
})
}
needInjectCritical
});
};
24 changes: 10 additions & 14 deletions packages/koot/core/pwa/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,11 @@ const parsePattern = pattern => {
});

// 修改 .public-chunkmap.json,添加 service-worker 文件信息
chunkmapCurrent['service-worker'] = [
`${
chunkmapCurrent['.public']
? chunkmapCurrent['.public'].replace(/\/$/, '')
: 'public'
}${pathnameSW}`
];
const inChunkmap =
(chunkmapCurrent['.public']
? chunkmapCurrent['.public'].replace(/\/$/, '')
: '') + pathnameSW;
chunkmapCurrent['service-worker'] = [inChunkmap.replace(/^\//, '')];

await fs.writeFile(
pathnameChunkmap,
Expand All @@ -212,13 +210,11 @@ const parsePattern = pattern => {
});

// 修改 .public-chunkmap.json,添加 service-worker 文件信息
chunkmapFull['service-worker'] = [
`${
chunkmapFull['.public']
? chunkmapFull['.public'].replace(/\/$/, '')
: 'public'
}${pathname}`
];
const inChunkmap =
(chunkmapFull['.public']
? chunkmapFull['.public'].replace(/\/$/, '')
: '') + pathname;
chunkmapFull['service-worker'] = [inChunkmap.replace(/^\//, '')];

await fs.writeFile(
pathnameChunkmap,
Expand Down
39 changes: 25 additions & 14 deletions packages/koot/utils/get-sw-pathname.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,38 @@
const getPublic = require('./get-public-dir');

/**
* 获取 service-worker 文件名
* @param {String} [localeId] 如果提供,则会返回 [NAME].[localeId].js
* @returns {String}
*/
module.exports = (localeId) => {
module.exports = localeId => {
if (typeof process.env.KOOT_PWA_PATHNAME !== 'string') return '';

if (typeof process.env.KOOT_PWA_PATHNAME !== 'string')
return ''
// 如果 localeId 是对象,表示 chunkmap
if (typeof localeId === 'object') {
const { 'service-worker': sw = [] } = localeId;
if (sw.length) {
const file = sw[0];
const { '.public': p } = localeId;
const regex = new RegExp(`^${p}`);
const P = getPublic();
if (regex.test(file)) return P + file.replace(regex, '');
return P + file.replace(/^public\//, '');
}
return '';
}

const i18nType = JSON.parse(process.env.KOOT_I18N)
? JSON.parse(process.env.KOOT_I18N_TYPE)
: undefined

const pwaPathname = JSON.parse(process.env.KOOT_PWA_PATHNAME)
: undefined;

if (i18nType !== 'default')
return pwaPathname
const pwaPathname = JSON.parse(process.env.KOOT_PWA_PATHNAME);

if (!localeId)
return pwaPathname
if (i18nType !== 'default') return pwaPathname;

const chunks = pwaPathname.split('.')
chunks.splice(chunks.length - 1, 0, localeId)
return chunks.join('.')
if (!localeId) return pwaPathname;

}
const chunks = pwaPathname.split('.');
chunks.splice(chunks.length - 1, 0, localeId);
return chunks.join('.');
};
25 changes: 20 additions & 5 deletions test/cases/react-base/need-in-order.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const addCommand = require('../../libs/add-command-to-package-json');
const terminate = require('../../libs/terminate-process');
const waitForPort = require('../../libs/get-port-from-child-process');
const testHtmlRenderedByKoot = require('../../general-tests/html/rendered-by-koot');
const testFilesFromChunkmap = require('../../general-tests/bundle/check-files-from-chunkmap');

//

Expand Down Expand Up @@ -173,6 +174,8 @@ const doTest = async (port, settings = {}) => {
await puppeteerTestInjectScripts(page);
await testRequestHidden404(origin, browser);

// TODO: 在设置了 sw 时有 sw 注册且没有报错

// 测试: 没有失败的请求
if (failedResponse.length) {
console.log(
Expand Down Expand Up @@ -231,6 +234,11 @@ describe('测试: React 同构项目', () => {
test(`ENV: prod`, async () => {
await beforeTest(dir);

const configFile = `koot.config.js`;
const dist = path.resolve(dir, 'dist');
if (fs.existsSync(dist)) fs.emptyDirSync(dist);
else fs.removeSync(dist);

const customEnv = {
aaaaa: '' + Math.floor(Math.random() * 10000),
bbbbb: 'a1b2c3'
Expand All @@ -253,7 +261,7 @@ describe('测试: React 同构项目', () => {
const errors = [];

await waitForPort(child);
const port = require(path.resolve(dir, 'koot.config.js')).port;
const port = require(path.resolve(dir, configFile)).port;
child.stderr.on('data', err => {
errors.push(err);
});
Expand All @@ -262,19 +270,24 @@ describe('测试: React 同构项目', () => {

// server-side 打包结果不应出现静态资源目录
expect(
fs.existsSync(path.resolve(dir, 'dist/server/index.js'))
fs.existsSync(path.resolve(dist, 'server/index.js'))
).toBe(true);
expect(
fs.existsSync(path.resolve(dir, 'dist/server/assets'))
).toBe(false);
expect(fs.existsSync(path.resolve(dist, 'server/assets'))).toBe(
false
);

await testFilesFromChunkmap(dist);
await doTest(port, {
customEnv
});
await doTest(port, {
enableJavascript: false,
customEnv
});

if (fs.existsSync(dist)) fs.emptyDirSync(dist);
else fs.removeSync(dist);

await terminate(child.pid);
await afterTest(dir, 'ENV: prod');
});
Expand Down Expand Up @@ -364,6 +377,8 @@ describe('测试: React 同构项目', () => {
)
).toBe(true);

await testFilesFromChunkmap(dist);

await fs.remove(dist);
await afterTest(dir, '[config] bundleVersionsKeep: false');
});
Expand Down
62 changes: 47 additions & 15 deletions test/cases/react-isomorphic/need-in-order.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ const sleep = require('../../../packages/koot/utils/sleep');
const addCommand = require('../../libs/add-command-to-package-json');
const terminate = require('../../libs/terminate-process');
const waitForPort = require('../../libs/get-port-from-child-process');
const checkForChunkmap = require('../../libs/check-for-chunkmap');
const filterState = require('../../../packages/koot/libs/filter-state');
const testHtmlRenderedByKoot = require('../../general-tests/html/rendered-by-koot');
const testFilesFromChunkmap = require('../../general-tests/bundle/check-files-from-chunkmap');

//

Expand Down Expand Up @@ -702,6 +704,8 @@ const doTest = async (port, settings = {}) => {

// TODO: 测试: 同一个通配路由,访问另一个URL,检查同构结果 (connect component 是否可用)

// TODO: 在设置了 sw 时有 sw 注册且没有报错

// 其他公用测试
await puppeteerTestInjectScripts(page);
await testRequestHidden404(origin, browser);
Expand All @@ -725,6 +729,35 @@ const doTest = async (port, settings = {}) => {
return;
};

/**
* 测试代码分割
* @async
* @param {String} dist
*/
const testCodeSplitting = async dist => {
const check = chunkmap => {
const { '.files': files } = chunkmap;
const { 'client.js': client, 'PageHome.js': home } = files;

expect(
fs
.readFileSync(path.resolve(dist, client))
.includes('!:!:! KOOT TEST ROUTES CONFIG !:!:!')
).toBe(true);
expect(
fs
.readFileSync(path.resolve(dist, client))
.includes('!:!:! KOOT TEST VIEW: WELCOME PAGE !:!:!')
).toBe(false);
expect(
fs
.readFileSync(path.resolve(dist, home))
.includes('!:!:! KOOT TEST VIEW: WELCOME PAGE !:!:!')
).toBe(true);
};
await checkForChunkmap(dist, check);
};

/**
* 测试项目开始前
* @async
Expand Down Expand Up @@ -778,6 +811,12 @@ describe('测试: React 同构项目', () => {
await beforeTest(dir);
await emptyDist(path.resolve(dir, 'dist'));

const configFile = `koot.config.js`;
const dist = path.resolve(
dir,
require(path.resolve(dir, configFile)).dist
);

const commandName = `${commandTestBuild}-isomorphic-build`;
const command = `koot-build --env prod --koot-test`;
await addCommand(commandName, command, dir);
Expand All @@ -795,23 +834,10 @@ describe('测试: React 同构项目', () => {
expect(typeof stderr).toBe('string');
expect(stderr).toBe('');

await testFilesFromChunkmap(dist);
await testCodeSplitting(dist);
await afterTest(dir, '[prod] 使用 koot-build 命令进行打包');
});
test(`[prod] 打包结果文件正确性测试`, async () => {
await beforeTest(dir);

// TODO: 依据 chunkmap,判断硬盘里是否有所有的文件,可考虑做成公用的生产环境打包结果测试

// TODO: 检查 client.js,应该没有拆分出去的代码特征
// '!:!:! KOOT TEST ROUTES CONFIG !:!:!'

// TODO: 检查特定的拆分出去的代码,应该有特征
// '!:!:! KOOT TEST VIEW: WELCOME PAGE !:!:!'
// '!:!:! KOOT TEST VIEW: EXTEND PAGE | TEST 2 !:!:!'

expect(' ').toBe('');
await afterTest(dir, '[prod] 打包结果文件正确性测试');
});
test(`[prod] 使用 koot-start (--no-build) 命令启动服务器并访问`, async () => {
await beforeTest(dir);

Expand Down Expand Up @@ -1016,6 +1042,8 @@ describe('测试: React 同构项目', () => {

expect(errors.length).toBe(0);

await testFilesFromChunkmap(dist);
await testCodeSplitting(dist);
await doTest(port, {
kootConfig: require(path.resolve(dir, configFile)),
i18nUseRouter: true
Expand Down Expand Up @@ -1098,6 +1126,8 @@ describe('测试: React 同构项目', () => {

expect(errors.length).toBe(0);

await testFilesFromChunkmap(dist);
await testCodeSplitting(dist);
await doTest(port, {
kootConfig: require(path.resolve(dir, configFile))
});
Expand Down Expand Up @@ -1179,6 +1209,8 @@ describe('测试: React 同构项目', () => {

expect(errors.length).toBe(0);

await testFilesFromChunkmap(dist);
await testCodeSplitting(dist);
await doTest(port, {
kootConfig: require(path.resolve(dir, configFile))
});
Expand Down
5 changes: 5 additions & 0 deletions test/cases/react-spa/need-in-order.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const {
const terminate = require('../../libs/terminate-process');
const waitForPort = require('../../libs/get-port-from-child-process');
const testHtmlRenderedByKoot = require('../../general-tests/html/rendered-by-koot');
const testFilesFromChunkmap = require('../../general-tests/bundle/check-files-from-chunkmap');
const { requestHidden404: testRequestHidden404 } = require('../puppeteer-test');

//
Expand Down Expand Up @@ -183,6 +184,8 @@ describe('测试: React SPA 项目', () => {
testFileFromFilelist(chunkNameExtractCss + '.css');
testFileFromFilelist(chunkNameExtractCssForImport + '.css');

await testFilesFromChunkmap(dist);

// TODO: 测试: 有 extract.all.[*].css
});

Expand Down Expand Up @@ -257,6 +260,8 @@ describe('测试: React SPA 项目', () => {
errors.push(e);
});

// TODO: 在设置了 sw 时有 sw 注册且没有报错

await context.close();
await browser.close();

Expand Down
Loading

0 comments on commit 72e88c2

Please sign in to comment.