init omi-snap
This commit is contained in:
parent
60758dd45e
commit
4bb6c759ac
|
@ -0,0 +1,68 @@
|
|||
## Develop
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
## Release
|
||||
|
||||
```bash
|
||||
npm build
|
||||
```
|
||||
|
||||
## Eslint + Prettier
|
||||
|
||||
``` bash
|
||||
npm run fix
|
||||
```
|
||||
|
||||
## Directory description
|
||||
|
||||
```
|
||||
├─ config
|
||||
├─ public
|
||||
├─ scripts
|
||||
├─ src
|
||||
│ ├─ assets
|
||||
│ ├─ elements //Store all custom elements
|
||||
│ ├─ store //Store all this store of pages
|
||||
│ ├─ admin.js //Entry js of compiler,will build to admin.html
|
||||
│ └─ index.js //Entry js of compiler,will build to index.html
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
About compiled website URL:
|
||||
|
||||
Such as in windows:
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"start": "node scripts/start.js",
|
||||
"_build": "node scripts/build.js",
|
||||
"build":"set PUBLIC_URL=https://fe.wxpay.oa.com/dv&& npm run _build"
|
||||
}
|
||||
```
|
||||
|
||||
In mac os:
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"start": "node scripts/start.js",
|
||||
"_build": "node scripts/build.js",
|
||||
"build":"PUBLIC_URL=https://fe.wxpay.oa.com/dv npm run _build",
|
||||
"fix": "eslint src --fix"
|
||||
},
|
||||
```
|
||||
|
||||
If you only want to use relative addresses:
|
||||
|
||||
```
|
||||
"build":"set PUBLIC_URL=.&& npm run _build" //windows
|
||||
"build":"PUBLIC_URL=. npm run _build", //mac os
|
||||
```
|
||||
|
||||
## Docs
|
||||
|
||||
Cli's auto-created project scaffolding is based on a single-page create-react-app to be converted into a multi-page one, with configuration issues to see [create-react-app user guide](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md)
|
|
@ -0,0 +1 @@
|
|||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="./manifest.json"><link rel="shortcut icon" href="./favicon.ico"><title>Omi</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="./static/js/index.47322829.js"></script></body></html>
|
|
@ -0,0 +1 @@
|
|||
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="./manifest.json"><link rel="shortcut icon" href="./favicon.ico"><title>Omi</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="./static/js/admin.ba1e34fd.js"></script></body></html>
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"admin.js": "./static/js/admin.ba1e34fd.js",
|
||||
"admin.js.map": "./static/js/admin.ba1e34fd.js.map",
|
||||
"index.js": "./static/js/index.47322829.js",
|
||||
"index.js.map": "./static/js/index.47322829.js.map",
|
||||
"admin.html": "./admin.html",
|
||||
"index.html": "./index.html",
|
||||
"static/media/logo.svg": "./static/media/logo.841c6daa.svg"
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 66 KiB |
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"short_name": "Omi App",
|
||||
"name": "Omi Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": "./index.html",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
"use strict";var precacheConfig=[["./admin.html","8d2e6b9e61a3de7fc90c95fb4c99f075"],["./index.html","9e25766135d2c4f67f4ad2e376703d6b"],["./static/js/admin.ba1e34fd.js","84b37a29f205d94ddaf8e8ff7d531dd0"],["./static/js/index.47322829.js","f3ee2d4a1d7585c732136e2b1f12c17a"],["./static/media/logo.841c6daa.svg","841c6daa3ef512379cd1b5e12fcf7a45"]],cacheName="sw-precache-v3-sw-precache-webpack-plugin-"+(self.registration?self.registration.scope:""),ignoreUrlParametersMatching=[/^utm_/],addDirectoryIndex=function(e,t){var n=new URL(e);return"/"===n.pathname.slice(-1)&&(n.pathname+=t),n.toString()},cleanResponse=function(e){return e.redirected?("body"in e?Promise.resolve(e.body):e.blob()).then(function(t){return new Response(t,{headers:e.headers,status:e.status,statusText:e.statusText})}):Promise.resolve(e)},createCacheKey=function(e,t,n,r){var a=new URL(e);return r&&a.pathname.match(r)||(a.search+=(a.search?"&":"")+encodeURIComponent(t)+"="+encodeURIComponent(n)),a.toString()},isPathWhitelisted=function(e,t){if(0===e.length)return!0;var n=new URL(t).pathname;return e.some(function(e){return n.match(e)})},stripIgnoredUrlParameters=function(e,t){var n=new URL(e);return n.hash="",n.search=n.search.slice(1).split("&").map(function(e){return e.split("=")}).filter(function(e){return t.every(function(t){return!t.test(e[0])})}).map(function(e){return e.join("=")}).join("&"),n.toString()},hashParamName="_sw-precache",urlsToCacheKeys=new Map(precacheConfig.map(function(e){var t=e[0],n=e[1],r=new URL(t,self.location),a=createCacheKey(r,hashParamName,n,/\.\w{8}\./);return[r.toString(),a]}));function setOfCachedUrls(e){return e.keys().then(function(e){return e.map(function(e){return e.url})}).then(function(e){return new Set(e)})}self.addEventListener("install",function(e){e.waitUntil(caches.open(cacheName).then(function(e){return setOfCachedUrls(e).then(function(t){return Promise.all(Array.from(urlsToCacheKeys.values()).map(function(n){if(!t.has(n)){var r=new Request(n,{credentials:"same-origin"});return fetch(r).then(function(t){if(!t.ok)throw new Error("Request for "+n+" returned a response with status "+t.status);return cleanResponse(t).then(function(t){return e.put(n,t)})})}}))})}).then(function(){return self.skipWaiting()}))}),self.addEventListener("activate",function(e){var t=new Set(urlsToCacheKeys.values());e.waitUntil(caches.open(cacheName).then(function(e){return e.keys().then(function(n){return Promise.all(n.map(function(n){if(!t.has(n.url))return e.delete(n)}))})}).then(function(){return self.clients.claim()}))}),self.addEventListener("fetch",function(e){if("GET"===e.request.method){var t,n=stripIgnoredUrlParameters(e.request.url,ignoreUrlParametersMatching);(t=urlsToCacheKeys.has(n))||(n=addDirectoryIndex(n,"index.html"),t=urlsToCacheKeys.has(n));!t&&"navigate"===e.request.mode&&isPathWhitelisted(["^(?!\\/__).*"],e.request.url)&&(n=new URL("./index.html",self.location).toString(),t=urlsToCacheKeys.has(n)),t&&e.respondWith(caches.open(cacheName).then(function(e){return e.match(urlsToCacheKeys.get(n)).then(function(e){if(e)return e;throw Error("The cached response that was expected is missing.")})}).catch(function(t){return console.warn('Couldn\'t serve response for "%s" from cache: %O',e.request.url,t),fetch(e.request)}))}});
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,23 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="529px" height="529px" viewBox="0 0 529 529" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>OMI</title>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-1">
|
||||
<stop stop-color="#FFD4DE" offset="0%"></stop>
|
||||
<stop stop-color="#D0021B" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-2">
|
||||
<stop stop-color="#00375E" offset="0%"></stop>
|
||||
<stop stop-color="#9ECAFD" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-3">
|
||||
<stop stop-color="#B4EC51" offset="0%"></stop>
|
||||
<stop stop-color="#429321" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g id="OMI" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<path d="M360.461194,392.400665 L331.766299,363.852923 C362.137315,342.610697 382,307.374938 382,267.5 C382,242.280821 374.054892,218.917322 360.531177,199.776002 L264.653589,295.653589 L249.205844,280.205844 L249.063708,280.34798 L168.478308,199.762579 C154.948823,218.906399 147,242.274926 147,267.5 C147,307.374938 166.862685,342.610697 197.233701,363.852923 L168.538806,392.400665 C131.116001,363.605836 107,318.369215 107,267.5 C107,216.869975 130.889745,171.819699 168.011797,143.006609 L222.432893,197.148622 L264.511454,239.227182 L311.034034,192.704602 L360.988203,143.006609 C398.110255,171.819699 422,216.869975 422,267.5 C422,318.369215 397.883999,363.605836 360.461194,392.400665 Z" id="M" fill="url(#linearGradient-1)" fill-rule="nonzero"></path>
|
||||
<path d="M264.5,472 C149.900914,472 57,379.099086 57,264.5 C57,149.900914 149.900914,57 264.5,57 C379.099086,57 472,149.900914 472,264.5 C472,379.099086 379.099086,472 264.5,472 Z M263.5,436 C357.112265,436 433,360.112265 433,266.5 C433,172.887735 357.112265,97 263.5,97 C169.887735,97 94,172.887735 94,266.5 C94,360.112265 169.887735,436 263.5,436 Z" id="O" fill="url(#linearGradient-2)" fill-rule="nonzero"></path>
|
||||
<circle id="I-Dot" fill="url(#linearGradient-3)" fill-rule="nonzero" cx="319" cy="142" r="20"></circle>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 2.3 KiB |
|
@ -0,0 +1,28 @@
|
|||
let fs = require('fs'),
|
||||
fileList = [];
|
||||
|
||||
|
||||
if (typeof String.prototype.endsWith != 'function') {
|
||||
String.prototype.endsWith = function (suffix) {
|
||||
return this.indexOf(suffix, this.length - suffix.length) !== -1;
|
||||
};
|
||||
}
|
||||
|
||||
function walk(path) {
|
||||
let dirList = fs.readdirSync(path);
|
||||
dirList.forEach(function (item) {
|
||||
if (!fs.statSync(path + '/' + item).isDirectory()) {
|
||||
if (item.endsWith('\.js')) {
|
||||
fileList.push(item.substr(0, item.length - 3));
|
||||
}
|
||||
} else {
|
||||
//walk(path + '/' + item);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
walk('./src');
|
||||
|
||||
|
||||
|
||||
module.exports = fileList;
|
|
@ -0,0 +1,93 @@
|
|||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const paths = require('./paths');
|
||||
|
||||
// Make sure that including paths.js after env.js will read .env variables.
|
||||
delete require.cache[require.resolve('./paths')];
|
||||
|
||||
const NODE_ENV = process.env.NODE_ENV;
|
||||
if (!NODE_ENV) {
|
||||
throw new Error(
|
||||
'The NODE_ENV environment variable is required but was not specified.'
|
||||
);
|
||||
}
|
||||
|
||||
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
|
||||
var dotenvFiles = [
|
||||
`${paths.dotenv}.${NODE_ENV}.local`,
|
||||
`${paths.dotenv}.${NODE_ENV}`,
|
||||
// Don't include `.env.local` for `test` environment
|
||||
// since normally you expect tests to produce the same
|
||||
// results for everyone
|
||||
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
|
||||
paths.dotenv,
|
||||
].filter(Boolean);
|
||||
|
||||
// Load environment variables from .env* files. Suppress warnings using silent
|
||||
// if this file is missing. dotenv will never modify any environment variables
|
||||
// that have already been set. Variable expansion is supported in .env files.
|
||||
// https://github.com/motdotla/dotenv
|
||||
// https://github.com/motdotla/dotenv-expand
|
||||
dotenvFiles.forEach(dotenvFile => {
|
||||
if (fs.existsSync(dotenvFile)) {
|
||||
require('dotenv-expand')(
|
||||
require('dotenv').config({
|
||||
path: dotenvFile,
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// We support resolving modules according to `NODE_PATH`.
|
||||
// This lets you use absolute paths in imports inside large monorepos:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253.
|
||||
// It works similar to `NODE_PATH` in Node itself:
|
||||
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
|
||||
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
|
||||
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
|
||||
// We also resolve them to make sure all tools using them work consistently.
|
||||
const appDirectory = fs.realpathSync(process.cwd());
|
||||
process.env.NODE_PATH = (process.env.NODE_PATH || '')
|
||||
.split(path.delimiter)
|
||||
.filter(folder => folder && !path.isAbsolute(folder))
|
||||
.map(folder => path.resolve(appDirectory, folder))
|
||||
.join(path.delimiter);
|
||||
|
||||
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
|
||||
// injected into the application via DefinePlugin in Webpack configuration.
|
||||
const REACT_APP = /^REACT_APP_/i;
|
||||
|
||||
function getClientEnvironment(publicUrl) {
|
||||
const raw = Object.keys(process.env)
|
||||
.filter(key => REACT_APP.test(key))
|
||||
.reduce(
|
||||
(env, key) => {
|
||||
env[key] = process.env[key];
|
||||
return env;
|
||||
},
|
||||
{
|
||||
// Useful for determining whether we’re running in production mode.
|
||||
// Most importantly, it switches React into the correct mode.
|
||||
NODE_ENV: process.env.NODE_ENV || 'development',
|
||||
// Useful for resolving the correct path to static assets in `public`.
|
||||
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
|
||||
// This should only be used as an escape hatch. Normally you would put
|
||||
// images into the `src` and `import` them in code to get their paths.
|
||||
PUBLIC_URL: publicUrl,
|
||||
}
|
||||
);
|
||||
// Stringify all values so we can feed into Webpack DefinePlugin
|
||||
const stringified = {
|
||||
'process.env': Object.keys(raw).reduce((env, key) => {
|
||||
env[key] = JSON.stringify(raw[key]);
|
||||
return env;
|
||||
}, {}),
|
||||
};
|
||||
|
||||
return { raw, stringified };
|
||||
}
|
||||
|
||||
module.exports = getClientEnvironment;
|
|
@ -0,0 +1,14 @@
|
|||
'use strict';
|
||||
|
||||
// This is a custom Jest transformer turning style imports into empty objects.
|
||||
// http://facebook.github.io/jest/docs/en/webpack.html
|
||||
|
||||
module.exports = {
|
||||
process() {
|
||||
return 'module.exports = {};';
|
||||
},
|
||||
getCacheKey() {
|
||||
// The output is always the same.
|
||||
return 'cssTransform';
|
||||
},
|
||||
};
|
|
@ -0,0 +1,12 @@
|
|||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
// This is a custom Jest transformer turning file imports into filenames.
|
||||
// http://facebook.github.io/jest/docs/en/webpack.html
|
||||
|
||||
module.exports = {
|
||||
process(src, filename) {
|
||||
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
|
||||
},
|
||||
};
|
|
@ -0,0 +1,55 @@
|
|||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const url = require('url');
|
||||
|
||||
// Make sure any symlinks in the project folder are resolved:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/637
|
||||
const appDirectory = fs.realpathSync(process.cwd());
|
||||
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
|
||||
|
||||
const envPublicUrl = process.env.PUBLIC_URL;
|
||||
|
||||
function ensureSlash(path, needsSlash) {
|
||||
const hasSlash = path.endsWith('/');
|
||||
if (hasSlash && !needsSlash) {
|
||||
return path.substr(path, path.length - 1);
|
||||
} else if (!hasSlash && needsSlash) {
|
||||
return `${path}/`;
|
||||
} else {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
const getPublicUrl = appPackageJson =>
|
||||
envPublicUrl || require(appPackageJson).homepage;
|
||||
|
||||
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
|
||||
// "public path" at which the app is served.
|
||||
// Webpack needs to know it to put the right <script> hrefs into HTML even in
|
||||
// single-page apps that may serve index.html for nested URLs like /todos/42.
|
||||
// We can't use a relative path in HTML because we don't want to load something
|
||||
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
|
||||
function getServedPath(appPackageJson) {
|
||||
const publicUrl = getPublicUrl(appPackageJson);
|
||||
const servedUrl =
|
||||
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
|
||||
return ensureSlash(servedUrl, true);
|
||||
}
|
||||
|
||||
// config after eject: we're in ./config/
|
||||
module.exports = {
|
||||
dotenv: resolveApp('.env'),
|
||||
appBuild: resolveApp('build'),
|
||||
appPublic: resolveApp('public'),
|
||||
appHtml: resolveApp('public/index.html'),
|
||||
appIndexJs: resolveApp('src/index.js'),
|
||||
appPackageJson: resolveApp('package.json'),
|
||||
appSrc: resolveApp('src'),
|
||||
yarnLockFile: resolveApp('yarn.lock'),
|
||||
testsSetup: resolveApp('src/setupTests.js'),
|
||||
appNodeModules: resolveApp('node_modules'),
|
||||
publicUrl: getPublicUrl(resolveApp('package.json')),
|
||||
servedPath: getServedPath(resolveApp('package.json')),
|
||||
};
|
|
@ -0,0 +1,22 @@
|
|||
'use strict';
|
||||
|
||||
if (typeof Promise === 'undefined') {
|
||||
// Rejection tracking prevents a common issue where React gets into an
|
||||
// inconsistent state due to an error, but it gets swallowed by a Promise,
|
||||
// and the user has no idea what causes React's erratic future behavior.
|
||||
require('promise/lib/rejection-tracking').enable();
|
||||
window.Promise = require('promise/lib/es6-extensions.js');
|
||||
}
|
||||
|
||||
// fetch() polyfill for making API calls.
|
||||
require('whatwg-fetch');
|
||||
|
||||
// Object.assign() is commonly used with React.
|
||||
// It will use the native implementation if it's present and isn't buggy.
|
||||
Object.assign = require('object-assign');
|
||||
|
||||
// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
|
||||
// We don't polyfill it in the browser--this is user's responsibility.
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
require('raf').polyfill(global);
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
node_modules
|
||||
yarn-error.log
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2017 stereobooster
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,824 @@
|
|||
const crawl = require("./src/puppeteer_utils.js").crawl;
|
||||
const http = require("http");
|
||||
const express = require("express");
|
||||
const serveStatic = require("serve-static");
|
||||
const fallback = require("express-history-api-fallback");
|
||||
const path = require("path");
|
||||
const nativeFs = require("fs");
|
||||
const mkdirp = require("mkdirp");
|
||||
const minify = require("html-minifier").minify;
|
||||
const url = require("url");
|
||||
const minimalcss = require("minimalcss");
|
||||
const CleanCSS = require("clean-css");
|
||||
const twentyKb = 20 * 1024;
|
||||
|
||||
const defaultOptions = {
|
||||
//# stable configurations
|
||||
port: 45678,
|
||||
source: "build",
|
||||
destination: null,
|
||||
concurrency: 4,
|
||||
include: ["/"],
|
||||
userAgent: "ReactSnap",
|
||||
// 4 params below will be refactored to one: `puppeteer: {}`
|
||||
// https://github.com/stereobooster/react-snap/issues/120
|
||||
headless: true,
|
||||
puppeteer: {
|
||||
cache: true
|
||||
},
|
||||
puppeteerArgs: [],
|
||||
puppeteerExecutablePath: undefined,
|
||||
puppeteerIgnoreHTTPSErrors: false,
|
||||
publicPath: "/",
|
||||
minifyCss: {},
|
||||
minifyHtml: {
|
||||
collapseBooleanAttributes: true,
|
||||
collapseWhitespace: true,
|
||||
decodeEntities: true,
|
||||
keepClosingSlash: true,
|
||||
sortAttributes: true,
|
||||
sortClassName: false
|
||||
},
|
||||
// mobile first approach
|
||||
viewport: {
|
||||
width: 480,
|
||||
height: 850
|
||||
},
|
||||
sourceMaps: true,
|
||||
//# workarounds
|
||||
// using CRA1 for compatibility with previous version will be changed to false in v2
|
||||
fixWebpackChunksIssue: "CRA1",
|
||||
removeBlobs: true,
|
||||
fixInsertRule: true,
|
||||
skipThirdPartyRequests: false,
|
||||
cacheAjaxRequests: false,
|
||||
http2PushManifest: false,
|
||||
// may use some glob solution in the future, if required
|
||||
// works when http2PushManifest: true
|
||||
ignoreForPreload: ["service-worker.js"],
|
||||
//# unstable configurations
|
||||
preconnectThirdParty: true,
|
||||
// Experimental. This config stands for two strategies inline and critical.
|
||||
// TODO: inline strategy can contain errors, like, confuse relative urls
|
||||
inlineCss: false,
|
||||
//# feature creeps to generate screenshots
|
||||
saveAs: "html",
|
||||
crawl: true,
|
||||
waitFor: false,
|
||||
externalServer: false,
|
||||
//# even more workarounds
|
||||
removeStyleTags: false,
|
||||
preloadImages: false,
|
||||
// add async true to script tags
|
||||
asyncScriptTags: false,
|
||||
//# another feature creep
|
||||
// tribute to Netflix Server Side Only React https://twitter.com/NetflixUIE/status/923374215041912833
|
||||
// but this will also remove code which registers service worker
|
||||
removeScriptTags: false
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {{source: ?string, destination: ?string, include: ?Array<string>, sourceMaps: ?boolean, skipThirdPartyRequests: ?boolean }} userOptions
|
||||
* @return {*}
|
||||
*/
|
||||
const defaults = userOptions => {
|
||||
const options = {
|
||||
...defaultOptions,
|
||||
...userOptions
|
||||
};
|
||||
options.destination = options.destination || options.source;
|
||||
|
||||
let exit = false;
|
||||
if (!options.include || !options.include.length) {
|
||||
console.log("🔥 include option should be an non-empty array");
|
||||
exit = true;
|
||||
}
|
||||
if (options.preloadResources) {
|
||||
console.log(
|
||||
"🔥 preloadResources option deprecated. Use preloadImages or cacheAjaxRequests"
|
||||
);
|
||||
exit = true;
|
||||
}
|
||||
if (options.minifyOptions) {
|
||||
console.log("🔥 minifyOptions option renamed to minifyHtml");
|
||||
options.minifyHtml = options.minifyOptions;
|
||||
}
|
||||
if (options.asyncJs) {
|
||||
console.log("🔥 asyncJs option renamed to asyncScriptTags");
|
||||
options.asyncScriptTags = options.asyncJs;
|
||||
}
|
||||
if (options.fixWebpackChunksIssue === true) {
|
||||
console.log(
|
||||
"🔥 fixWebpackChunksIssue - behaviour changed, valid options are CRA1, CRA2, false"
|
||||
);
|
||||
options.fixWebpackChunksIssue = "CRA1";
|
||||
}
|
||||
if (
|
||||
options.saveAs !== "html" &&
|
||||
options.saveAs !== "png" &&
|
||||
options.saveAs !== "jpeg"
|
||||
) {
|
||||
console.log("🔥 saveAs supported values are html, png, and jpeg");
|
||||
exit = true;
|
||||
}
|
||||
if (exit) throw new Error();
|
||||
if (options.minifyHtml && !options.minifyHtml.minifyCSS) {
|
||||
options.minifyHtml.minifyCSS = options.minifyCss;
|
||||
}
|
||||
|
||||
if (!options.publicPath.startsWith("/")) {
|
||||
options.publicPath = `/${options.publicPath}`;
|
||||
}
|
||||
options.publicPath = options.publicPath.replace(/\/$/, "");
|
||||
|
||||
options.include = options.include.map(
|
||||
include => options.publicPath + include
|
||||
);
|
||||
return options;
|
||||
};
|
||||
|
||||
const normalizePath = path => (path === "/" ? "/" : path.replace(/\/$/, ""));
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {{page: Page, basePath: string}} opt
|
||||
*/
|
||||
const preloadResources = opt => {
|
||||
const {
|
||||
page,
|
||||
basePath,
|
||||
preloadImages,
|
||||
cacheAjaxRequests,
|
||||
preconnectThirdParty,
|
||||
http2PushManifest,
|
||||
ignoreForPreload
|
||||
} = opt;
|
||||
const ajaxCache = {};
|
||||
const http2PushManifestItems = [];
|
||||
const uniqueResources = new Set();
|
||||
page.on("response", async response => {
|
||||
const responseUrl = response.url();
|
||||
if (/^data:|blob:/i.test(responseUrl)) return;
|
||||
const ct = response.headers()["content-type"] || "";
|
||||
const route = responseUrl.replace(basePath, "");
|
||||
if (/^http:\/\/localhost/i.test(responseUrl)) {
|
||||
if (uniqueResources.has(responseUrl)) return;
|
||||
if (preloadImages && /\.(png|jpg|jpeg|webp|gif|svg)$/.test(responseUrl)) {
|
||||
if (http2PushManifest) {
|
||||
http2PushManifestItems.push({
|
||||
link: route,
|
||||
as: "image"
|
||||
});
|
||||
} else {
|
||||
await page.evaluate(route => {
|
||||
const linkTag = document.createElement("link");
|
||||
linkTag.setAttribute("rel", "preload");
|
||||
linkTag.setAttribute("as", "image");
|
||||
linkTag.setAttribute("href", route);
|
||||
document.body.appendChild(linkTag);
|
||||
}, route);
|
||||
}
|
||||
} else if (cacheAjaxRequests && ct.includes("json")) {
|
||||
const json = await response.json();
|
||||
ajaxCache[route] = json;
|
||||
} else if (http2PushManifest && /\.(js)$/.test(responseUrl)) {
|
||||
const fileName = url
|
||||
.parse(responseUrl)
|
||||
.pathname.split("/")
|
||||
.pop();
|
||||
if (!ignoreForPreload.includes(fileName)) {
|
||||
http2PushManifestItems.push({
|
||||
link: route,
|
||||
as: "script"
|
||||
});
|
||||
}
|
||||
} else if (http2PushManifest && /\.(css)$/.test(responseUrl)) {
|
||||
const fileName = url
|
||||
.parse(responseUrl)
|
||||
.pathname.split("/")
|
||||
.pop();
|
||||
if (!ignoreForPreload.includes(fileName)) {
|
||||
http2PushManifestItems.push({
|
||||
link: route,
|
||||
as: "style"
|
||||
});
|
||||
}
|
||||
}
|
||||
uniqueResources.add(responseUrl);
|
||||
} else if (preconnectThirdParty) {
|
||||
const urlObj = url.parse(responseUrl);
|
||||
const domain = `${urlObj.protocol}//${urlObj.host}`;
|
||||
if (uniqueResources.has(domain)) return;
|
||||
uniqueResources.add(domain);
|
||||
await page.evaluate(route => {
|
||||
const linkTag = document.createElement("link");
|
||||
linkTag.setAttribute("rel", "preconnect");
|
||||
linkTag.setAttribute("href", route);
|
||||
document.head.appendChild(linkTag);
|
||||
}, domain);
|
||||
}
|
||||
});
|
||||
return { ajaxCache, http2PushManifestItems };
|
||||
};
|
||||
|
||||
const removeStyleTags = ({ page }) =>
|
||||
page.evaluate(() => {
|
||||
Array.from(document.querySelectorAll("style")).forEach(ell => {
|
||||
ell.parentElement && ell.parentElement.removeChild(ell);
|
||||
});
|
||||
});
|
||||
|
||||
const removeScriptTags = ({ page }) =>
|
||||
page.evaluate(() => {
|
||||
Array.from(document.querySelectorAll("script")).forEach(ell => {
|
||||
ell.parentElement && ell.parentElement.removeChild(ell);
|
||||
});
|
||||
});
|
||||
|
||||
const preloadPolyfill = nativeFs.readFileSync(
|
||||
`${__dirname}/vendor/preload_polyfill.min.js`,
|
||||
"utf8"
|
||||
);
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {{page: Page}} opt
|
||||
* @return Promise
|
||||
*/
|
||||
const removeBlobs = async opt => {
|
||||
const { page } = opt;
|
||||
return page.evaluate(() => {
|
||||
const stylesheets = Array.from(
|
||||
document.querySelectorAll("link[rel=stylesheet]")
|
||||
);
|
||||
stylesheets.forEach(link => {
|
||||
if (link.href && link.href.startsWith("blob:")) {
|
||||
link.parentNode && link.parentNode.removeChild(link);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {{page: Page, pageUrl: string, options: {skipThirdPartyRequests: boolean, userAgent: string}, basePath: string, browser: Browser}} opt
|
||||
* @return {Promise}
|
||||
*/
|
||||
const inlineCss = async opt => {
|
||||
const { page, pageUrl, options, basePath, browser } = opt;
|
||||
|
||||
const minimalcssResult = await minimalcss.minimize({
|
||||
urls: [pageUrl],
|
||||
skippable: request =>
|
||||
options.skipThirdPartyRequests && !request.url().startsWith(basePath),
|
||||
browser: browser,
|
||||
userAgent: options.userAgent
|
||||
});
|
||||
const criticalCss = minimalcssResult.finalCss;
|
||||
const criticalCssSize = Buffer.byteLength(criticalCss, "utf8");
|
||||
|
||||
const result = await page.evaluate(async () => {
|
||||
const stylesheets = Array.from(
|
||||
document.querySelectorAll("link[rel=stylesheet]")
|
||||
);
|
||||
const cssArray = await Promise.all(
|
||||
stylesheets.map(async link => {
|
||||
const response = await fetch(link.href);
|
||||
return response.text();
|
||||
})
|
||||
);
|
||||
return {
|
||||
cssFiles: stylesheets.map(link => link.href),
|
||||
allCss: cssArray.join("")
|
||||
};
|
||||
});
|
||||
const allCss = new CleanCSS(options.minifyCss).minify(result.allCss).styles;
|
||||
const allCssSize = Buffer.byteLength(allCss, "utf8");
|
||||
|
||||
let cssStrategy, cssSize;
|
||||
if (criticalCssSize * 2 >= allCssSize) {
|
||||
cssStrategy = "inline";
|
||||
cssSize = allCssSize;
|
||||
} else {
|
||||
cssStrategy = "critical";
|
||||
cssSize = criticalCssSize;
|
||||
}
|
||||
|
||||
if (cssSize > twentyKb)
|
||||
console.log(
|
||||
`⚠️ warning: inlining CSS more than 20kb (${cssSize /
|
||||
1024}kb, ${cssStrategy})`
|
||||
);
|
||||
|
||||
if (cssStrategy === "critical") {
|
||||
await page.evaluate(
|
||||
(criticalCss, preloadPolyfill) => {
|
||||
const head = document.head || document.getElementsByTagName("head")[0],
|
||||
style = document.createElement("style");
|
||||
style.type = "text/css";
|
||||
style.appendChild(document.createTextNode(criticalCss));
|
||||
head.appendChild(style);
|
||||
const noscriptTag = document.createElement("noscript");
|
||||
document.head.appendChild(noscriptTag);
|
||||
|
||||
const stylesheets = Array.from(
|
||||
document.querySelectorAll("link[rel=stylesheet]")
|
||||
);
|
||||
stylesheets.forEach(link => {
|
||||
noscriptTag.appendChild(link.cloneNode(false));
|
||||
link.setAttribute("rel", "preload");
|
||||
link.setAttribute("as", "style");
|
||||
link.setAttribute("react-snap-onload", "this.rel='stylesheet'");
|
||||
document.head.appendChild(link);
|
||||
});
|
||||
|
||||
const scriptTag = document.createElement("script");
|
||||
scriptTag.type = "text/javascript";
|
||||
scriptTag.text = preloadPolyfill;
|
||||
// scriptTag.id = "preloadPolyfill";
|
||||
document.body.appendChild(scriptTag);
|
||||
},
|
||||
criticalCss,
|
||||
preloadPolyfill
|
||||
);
|
||||
} else {
|
||||
await page.evaluate(allCss => {
|
||||
if (!allCss) return;
|
||||
|
||||
const head = document.head || document.getElementsByTagName("head")[0],
|
||||
style = document.createElement("style");
|
||||
style.type = "text/css";
|
||||
style.appendChild(document.createTextNode(allCss));
|
||||
|
||||
if (!head) throw new Error("No <head> element found in document");
|
||||
|
||||
head.appendChild(style);
|
||||
|
||||
const stylesheets = Array.from(
|
||||
document.querySelectorAll("link[rel=stylesheet]")
|
||||
);
|
||||
stylesheets.forEach(link => {
|
||||
link.parentNode && link.parentNode.removeChild(link);
|
||||
});
|
||||
}, allCss);
|
||||
}
|
||||
return {
|
||||
cssFiles: cssStrategy === "inline" ? result.cssFiles : []
|
||||
};
|
||||
};
|
||||
|
||||
const asyncScriptTags = ({ page }) => {
|
||||
return page.evaluate(() => {
|
||||
Array.from(document.querySelectorAll("script[src]")).forEach(x => {
|
||||
x.setAttribute("async", "true");
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const fixWebpackChunksIssue1 = ({
|
||||
page,
|
||||
basePath,
|
||||
http2PushManifest,
|
||||
inlineCss
|
||||
}) => {
|
||||
return page.evaluate(
|
||||
(basePath, http2PushManifest, inlineCss) => {
|
||||
const localScripts = Array.from(document.scripts).filter(
|
||||
x => x.src && x.src.startsWith(basePath)
|
||||
);
|
||||
// CRA v1|v2.alpha
|
||||
const mainRegexp = /main\.[\w]{8}.js|main\.[\w]{8}\.chunk\.js/;
|
||||
const mainScript = localScripts.find(x => mainRegexp.test(x.src));
|
||||
const firstStyle = document.querySelector("style");
|
||||
|
||||
if (!mainScript) return;
|
||||
|
||||
const chunkRegexp = /(\w+)\.[\w]{8}(\.chunk)?\.js/g;
|
||||
const chunkScripts = localScripts.filter(x => {
|
||||
const matched = chunkRegexp.exec(x.src);
|
||||
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
|
||||
chunkRegexp.lastIndex = 0;
|
||||
return matched && matched[1] !== "main" && matched[1] !== "vendors";
|
||||
});
|
||||
|
||||
const mainScripts = localScripts.filter(x => {
|
||||
const matched = chunkRegexp.exec(x.src);
|
||||
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
|
||||
chunkRegexp.lastIndex = 0;
|
||||
return matched && (matched[1] === "main" || matched[1] === "vendors");
|
||||
});
|
||||
|
||||
const createLink = x => {
|
||||
if (http2PushManifest) return;
|
||||
const linkTag = document.createElement("link");
|
||||
linkTag.setAttribute("rel", "preload");
|
||||
linkTag.setAttribute("as", "script");
|
||||
linkTag.setAttribute("href", x.src.replace(basePath, ""));
|
||||
if (inlineCss) {
|
||||
firstStyle.parentNode.insertBefore(linkTag, firstStyle);
|
||||
} else {
|
||||
document.head.appendChild(linkTag);
|
||||
}
|
||||
};
|
||||
|
||||
mainScripts.map(x => createLink(x));
|
||||
for (let i = chunkScripts.length - 1; i >= 0; --i) {
|
||||
const x = chunkScripts[i];
|
||||
if (x.parentElement && mainScript.parentNode) {
|
||||
x.parentElement.removeChild(x);
|
||||
createLink(x);
|
||||
}
|
||||
}
|
||||
},
|
||||
basePath,
|
||||
http2PushManifest,
|
||||
inlineCss
|
||||
);
|
||||
};
|
||||
|
||||
const fixWebpackChunksIssue2 = ({
|
||||
page,
|
||||
basePath,
|
||||
http2PushManifest,
|
||||
inlineCss
|
||||
}) => {
|
||||
return page.evaluate(
|
||||
(basePath, http2PushManifest, inlineCss) => {
|
||||
const localScripts = Array.from(document.scripts).filter(
|
||||
x => x.src && x.src.startsWith(basePath)
|
||||
);
|
||||
// CRA v2
|
||||
const mainRegexp = /main\.[\w]{8}\.chunk\.js/;
|
||||
const mainScript = localScripts.find(x => mainRegexp.test(x.src));
|
||||
const firstStyle = document.querySelector("style");
|
||||
|
||||
if (!mainScript) return;
|
||||
|
||||
const chunkRegexp = /(\w+)\.[\w]{8}\.chunk\.js/g;
|
||||
|
||||
const headScripts = Array.from(document.querySelectorAll("head script"))
|
||||
.filter(x => x.src && x.src.startsWith(basePath))
|
||||
.filter(x => {
|
||||
const matched = chunkRegexp.exec(x.src);
|
||||
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
|
||||
chunkRegexp.lastIndex = 0;
|
||||
return matched;
|
||||
});
|
||||
|
||||
const chunkScripts = localScripts.filter(x => {
|
||||
const matched = chunkRegexp.exec(x.src);
|
||||
// we need to reset state of RegExp https://stackoverflow.com/a/11477448
|
||||
chunkRegexp.lastIndex = 0;
|
||||
return matched;
|
||||
});
|
||||
|
||||
const createLink = x => {
|
||||
if (http2PushManifest) return;
|
||||
const linkTag = document.createElement("link");
|
||||
linkTag.setAttribute("rel", "preload");
|
||||
linkTag.setAttribute("as", "script");
|
||||
linkTag.setAttribute("href", x.src.replace(basePath, ""));
|
||||
if (inlineCss) {
|
||||
firstStyle.parentNode.insertBefore(linkTag, firstStyle);
|
||||
} else {
|
||||
document.head.appendChild(linkTag);
|
||||
}
|
||||
};
|
||||
|
||||
for (let i = headScripts.length; i <= chunkScripts.length - 1; i++) {
|
||||
const x = chunkScripts[i];
|
||||
if (x.parentElement && mainScript.parentNode) {
|
||||
createLink(x);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = headScripts.length - 1; i >= 0; --i) {
|
||||
const x = headScripts[i];
|
||||
if (x.parentElement && mainScript.parentNode) {
|
||||
x.parentElement.removeChild(x);
|
||||
createLink(x);
|
||||
}
|
||||
}
|
||||
},
|
||||
basePath,
|
||||
http2PushManifest,
|
||||
inlineCss
|
||||
);
|
||||
};
|
||||
|
||||
const fixInsertRule = ({ page }) => {
|
||||
return page.evaluate(() => {
|
||||
Array.from(document.querySelectorAll("style")).forEach(style => {
|
||||
if (style.innerHTML === "") {
|
||||
style.innerHTML = Array.from(style.sheet.rules)
|
||||
.map(rule => rule.cssText)
|
||||
.join("");
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const fixFormFields = ({ page }) => {
|
||||
return page.evaluate(() => {
|
||||
Array.from(document.querySelectorAll("[type=radio]")).forEach(element => {
|
||||
if (element.checked) {
|
||||
element.setAttribute("checked", "checked");
|
||||
} else {
|
||||
element.removeAttribute("checked");
|
||||
}
|
||||
});
|
||||
Array.from(document.querySelectorAll("[type=checkbox]")).forEach(
|
||||
element => {
|
||||
if (element.checked) {
|
||||
element.setAttribute("checked", "checked");
|
||||
} else {
|
||||
element.removeAttribute("checked");
|
||||
}
|
||||
}
|
||||
);
|
||||
Array.from(document.querySelectorAll("option")).forEach(element => {
|
||||
if (element.selected) {
|
||||
element.setAttribute("selected", "selected");
|
||||
} else {
|
||||
element.removeAttribute("selected");
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const saveAsHtml = async ({ page, filePath, options, route, fs }) => {
|
||||
let content = await page.content();
|
||||
content = content.replace(/react-snap-onload/g, "onload");
|
||||
const title = await page.title();
|
||||
const minifiedContent = options.minifyHtml
|
||||
? minify(content, options.minifyHtml)
|
||||
: content;
|
||||
filePath = filePath.replace(/\//g, path.sep);
|
||||
if (route.endsWith(".html")) {
|
||||
if (route.endsWith("/404.html") && !title.includes("404"))
|
||||
console.log('⚠️ warning: 404 page title does not contain "404" string');
|
||||
mkdirp.sync(path.dirname(filePath));
|
||||
fs.writeFileSync(filePath, minifiedContent);
|
||||
} else {
|
||||
if (title.includes("404"))
|
||||
console.log(`⚠️ warning: page not found ${route}`);
|
||||
mkdirp.sync(filePath);
|
||||
fs.writeFileSync(path.join(filePath, "index.html"), minifiedContent);
|
||||
}
|
||||
};
|
||||
|
||||
const saveAsPng = ({ page, filePath, options, route }) => {
|
||||
mkdirp.sync(path.dirname(filePath));
|
||||
let screenshotPath;
|
||||
if (route.endsWith(".html")) {
|
||||
screenshotPath = filePath.replace(/\.html$/, ".png");
|
||||
} else if (route === "/") {
|
||||
screenshotPath = `${filePath}index.png`;
|
||||
} else {
|
||||
screenshotPath = `${filePath.replace(/\/$/, "")}.png`;
|
||||
}
|
||||
return page.screenshot({ path: screenshotPath });
|
||||
};
|
||||
|
||||
const saveAsJpeg = ({ page, filePath, options, route }) => {
|
||||
mkdirp.sync(path.dirname(filePath));
|
||||
let screenshotPath;
|
||||
if (route.endsWith(".html")) {
|
||||
screenshotPath = filePath.replace(/\.html$/, ".jpeg");
|
||||
} else if (route === "/") {
|
||||
screenshotPath = `${filePath}index.jpeg`;
|
||||
} else {
|
||||
screenshotPath = `${filePath.replace(/\/$/, "")}.jpeg`;
|
||||
}
|
||||
return page.screenshot({ path: screenshotPath });
|
||||
};
|
||||
|
||||
const run = async (userOptions, { fs } = { fs: nativeFs }) => {
|
||||
let options;
|
||||
try {
|
||||
options = defaults(userOptions);
|
||||
} catch (e) {
|
||||
return Promise.reject(e.message);
|
||||
}
|
||||
|
||||
const sourceDir = path.normalize(`${process.cwd()}/${options.source}`);
|
||||
const destinationDir = path.normalize(
|
||||
`${process.cwd()}/${options.destination}`
|
||||
);
|
||||
const startServer = options => {
|
||||
const app = express()
|
||||
.use(options.publicPath, serveStatic(sourceDir))
|
||||
.use(fallback("200.html", { root: sourceDir }));
|
||||
const server = http.createServer(app);
|
||||
server.listen(options.port);
|
||||
return server;
|
||||
};
|
||||
|
||||
if (
|
||||
destinationDir === sourceDir &&
|
||||
options.saveAs === "html" &&
|
||||
fs.existsSync(path.join(sourceDir, "200.html"))
|
||||
) {
|
||||
console.log(
|
||||
`🔥 200.html is present in the sourceDir (${sourceDir}). You can not run react-snap twice - this will break the build`
|
||||
);
|
||||
return Promise.reject("");
|
||||
}
|
||||
|
||||
fs.createReadStream(path.join(sourceDir, "index.html")).pipe(
|
||||
fs.createWriteStream(path.join(sourceDir, "200.html"))
|
||||
);
|
||||
|
||||
if (destinationDir !== sourceDir && options.saveAs === "html") {
|
||||
mkdirp.sync(destinationDir);
|
||||
fs.createReadStream(path.join(sourceDir, "index.html")).pipe(
|
||||
fs.createWriteStream(path.join(destinationDir, "200.html"))
|
||||
);
|
||||
}
|
||||
|
||||
const server = options.externalServer ? null : startServer(options);
|
||||
|
||||
const basePath = `http://localhost:${options.port}`;
|
||||
const publicPath = options.publicPath;
|
||||
const ajaxCache = {};
|
||||
const { http2PushManifest } = options;
|
||||
const http2PushManifestItems = {};
|
||||
|
||||
await crawl({
|
||||
options,
|
||||
basePath,
|
||||
publicPath,
|
||||
sourceDir,
|
||||
beforeFetch: async ({ page, route }) => {
|
||||
const {
|
||||
preloadImages,
|
||||
cacheAjaxRequests,
|
||||
preconnectThirdParty
|
||||
} = options;
|
||||
if (
|
||||
preloadImages ||
|
||||
cacheAjaxRequests ||
|
||||
preconnectThirdParty ||
|
||||
http2PushManifest
|
||||
) {
|
||||
const { ajaxCache: ac, http2PushManifestItems: hpm } = preloadResources(
|
||||
{
|
||||
page,
|
||||
basePath,
|
||||
preloadImages,
|
||||
cacheAjaxRequests,
|
||||
preconnectThirdParty,
|
||||
http2PushManifest,
|
||||
ignoreForPreload: options.ignoreForPreload
|
||||
}
|
||||
);
|
||||
ajaxCache[route] = ac;
|
||||
http2PushManifestItems[route] = hpm;
|
||||
}
|
||||
},
|
||||
afterFetch: async ({ page, route, browser, addToQueue }) => {
|
||||
const pageUrl = `${basePath}${route}`;
|
||||
if (options.removeStyleTags) await removeStyleTags({ page });
|
||||
if (options.removeScriptTags) await removeScriptTags({ page });
|
||||
if (options.removeBlobs) await removeBlobs({ page });
|
||||
if (options.inlineCss) {
|
||||
const { cssFiles } = await inlineCss({
|
||||
page,
|
||||
pageUrl,
|
||||
options,
|
||||
basePath,
|
||||
browser
|
||||
});
|
||||
|
||||
if (http2PushManifest) {
|
||||
const filesToRemove = cssFiles
|
||||
.filter(file => file.startsWith(basePath))
|
||||
.map(file => file.replace(basePath, ""));
|
||||
|
||||
for (let i = http2PushManifestItems[route].length - 1; i >= 0; i--) {
|
||||
const x = http2PushManifestItems[route][i];
|
||||
filesToRemove.forEach(fileToRemove => {
|
||||
if (x.link.startsWith(fileToRemove)) {
|
||||
http2PushManifestItems[route].splice(i, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (options.fixWebpackChunksIssue === "CRA2") {
|
||||
await fixWebpackChunksIssue2({
|
||||
page,
|
||||
basePath,
|
||||
http2PushManifest,
|
||||
inlineCss: options.inlineCss
|
||||
});
|
||||
} else if (options.fixWebpackChunksIssue === "CRA1") {
|
||||
await fixWebpackChunksIssue1({
|
||||
page,
|
||||
basePath,
|
||||
http2PushManifest,
|
||||
inlineCss: options.inlineCss
|
||||
});
|
||||
}
|
||||
if (options.asyncScriptTags) await asyncScriptTags({ page });
|
||||
|
||||
await page.evaluate(ajaxCache => {
|
||||
const snapEscape = (() => {
|
||||
const UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
|
||||
// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
|
||||
// Unicode char counterparts which are safe to use in JavaScript strings.
|
||||
const ESCAPED_CHARS = {
|
||||
"<": "\\u003C",
|
||||
">": "\\u003E",
|
||||
"/": "\\u002F",
|
||||
"\u2028": "\\u2028",
|
||||
"\u2029": "\\u2029"
|
||||
};
|
||||
const escapeUnsafeChars = unsafeChar => ESCAPED_CHARS[unsafeChar];
|
||||
return str => str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
|
||||
})();
|
||||
// TODO: as of now it only prevents XSS attack,
|
||||
// but can stringify only basic data types
|
||||
// e.g. Date, Set, Map, NaN won't be handled right
|
||||
const snapStringify = obj => snapEscape(JSON.stringify(obj));
|
||||
|
||||
let scriptTagText = "";
|
||||
if (ajaxCache && Object.keys(ajaxCache).length > 0) {
|
||||
scriptTagText += `window.snapStore=${snapEscape(
|
||||
JSON.stringify(ajaxCache)
|
||||
)};`;
|
||||
}
|
||||
let state;
|
||||
if (
|
||||
window.snapSaveState &&
|
||||
(state = window.snapSaveState()) &&
|
||||
Object.keys(state).length !== 0
|
||||
) {
|
||||
scriptTagText += Object.keys(state)
|
||||
.map(key => `window["${key}"]=${snapStringify(state[key])};`)
|
||||
.join("");
|
||||
}
|
||||
if (scriptTagText !== "") {
|
||||
const scriptTag = document.createElement("script");
|
||||
scriptTag.type = "text/javascript";
|
||||
scriptTag.text = scriptTagText;
|
||||
const firstScript = Array.from(document.scripts)[0];
|
||||
firstScript.parentNode.insertBefore(scriptTag, firstScript);
|
||||
}
|
||||
}, ajaxCache[route]);
|
||||
delete ajaxCache[route];
|
||||
if (options.fixInsertRule) await fixInsertRule({ page });
|
||||
await fixFormFields({ page });
|
||||
|
||||
let routePath = route.replace(publicPath, "");
|
||||
let filePath = path.join(destinationDir, routePath);
|
||||
if (options.saveAs === "html") {
|
||||
await saveAsHtml({ page, filePath, options, route, fs });
|
||||
let newRoute = await page.evaluate(() => location.toString());
|
||||
newPath = normalizePath(
|
||||
newRoute.replace(publicPath, "").replace(basePath, "")
|
||||
);
|
||||
routePath = normalizePath(routePath);
|
||||
if (routePath !== newPath) {
|
||||
console.log(newPath)
|
||||
console.log(`💬 in browser redirect (${newPath})`);
|
||||
addToQueue(newRoute);
|
||||
}
|
||||
} else if (options.saveAs === "png") {
|
||||
await saveAsPng({ page, filePath, options, route, fs });
|
||||
} else if (options.saveAs === "jpeg") {
|
||||
await saveAsJpeg({ page, filePath, options, route, fs });
|
||||
}
|
||||
},
|
||||
onEnd: () => {
|
||||
if (server) server.close();
|
||||
if (http2PushManifest) {
|
||||
const manifest = Object.keys(http2PushManifestItems).reduce(
|
||||
(accumulator, key) => {
|
||||
if (http2PushManifestItems[key].length !== 0)
|
||||
accumulator.push({
|
||||
source: key,
|
||||
headers: [
|
||||
{
|
||||
key: "Link",
|
||||
value: http2PushManifestItems[key]
|
||||
.map(x => `<${x.link}>;rel=preload;as=${x.as}`)
|
||||
.join(",")
|
||||
}
|
||||
]
|
||||
});
|
||||
return accumulator;
|
||||
},
|
||||
[]
|
||||
);
|
||||
fs.writeFileSync(
|
||||
`${destinationDir}/http2-push-manifest.json`,
|
||||
JSON.stringify(manifest)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
exports.defaultOptions = defaultOptions;
|
||||
exports.run = run;
|
|
@ -0,0 +1,35 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
const url = require("url");
|
||||
const { run } = require("./index.js");
|
||||
const {
|
||||
reactSnap,
|
||||
homepage,
|
||||
devDependencies,
|
||||
dependencies
|
||||
} = require(`${process.cwd()}/package.json`);
|
||||
|
||||
const publicUrl = process.env.PUBLIC_URL || homepage;
|
||||
|
||||
const reactScriptsVersion = parseInt(
|
||||
(devDependencies && devDependencies["react-scripts"])
|
||||
|| (dependencies && dependencies["react-scripts"])
|
||||
);
|
||||
let fixWebpackChunksIssue;
|
||||
switch (reactScriptsVersion) {
|
||||
case 1:
|
||||
fixWebpackChunksIssue = "CRA1";
|
||||
break;
|
||||
case 2:
|
||||
fixWebpackChunksIssue = "CRA2";
|
||||
break;
|
||||
}
|
||||
|
||||
run({
|
||||
publicPath: publicUrl ? url.parse(publicUrl).pathname : "/",
|
||||
fixWebpackChunksIssue,
|
||||
...reactSnap
|
||||
}).catch(error => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
|
@ -0,0 +1,287 @@
|
|||
const puppeteer = require("puppeteer");
|
||||
const _ = require("highland");
|
||||
const url = require("url");
|
||||
const mapStackTrace = require("sourcemapped-stacktrace-node").default;
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
const { createTracker, augmentTimeoutError } = require("./tracker");
|
||||
|
||||
const errorToString = jsHandle =>
|
||||
jsHandle.executionContext().evaluate(e => e.toString(), jsHandle);
|
||||
|
||||
const objectToJson = jsHandle => jsHandle.jsonValue();
|
||||
|
||||
/**
|
||||
* @param {{page: Page, options: {skipThirdPartyRequests: true}, basePath: string }} opt
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
const skipThirdPartyRequests = async opt => {
|
||||
const { page, options, basePath } = opt;
|
||||
if (!options.skipThirdPartyRequests) return;
|
||||
await page.setRequestInterception(true);
|
||||
page.on("request", request => {
|
||||
if (request.url().startsWith(basePath)) {
|
||||
request.continue();
|
||||
} else {
|
||||
request.abort();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {{page: Page, options: {sourceMaps: boolean}, route: string, onError: ?function }} opt
|
||||
* @return {void}
|
||||
*/
|
||||
const enableLogging = opt => {
|
||||
const { page, options, route, onError, sourcemapStore } = opt;
|
||||
page.on("console", msg => {
|
||||
const text = msg.text();
|
||||
if (text === "JSHandle@object") {
|
||||
Promise.all(msg.args().map(objectToJson)).then(args =>
|
||||
console.log(`💬 console.log at ${route}:`, ...args)
|
||||
);
|
||||
} else if (text === "JSHandle@error") {
|
||||
Promise.all(msg.args().map(errorToString)).then(args =>
|
||||
console.log(`💬 console.log at ${route}:`, ...args)
|
||||
);
|
||||
} else {
|
||||
console.log(`️️️💬 console.log at ${route}:`, text);
|
||||
}
|
||||
});
|
||||
page.on("error", msg => {
|
||||
console.log(`🔥 error at ${route}:`, msg);
|
||||
onError && onError();
|
||||
});
|
||||
page.on("pageerror", e => {
|
||||
if (options.sourceMaps) {
|
||||
mapStackTrace(e.stack || e.message, {
|
||||
isChromeOrEdge: true,
|
||||
store: sourcemapStore || {}
|
||||
})
|
||||
.then(result => {
|
||||
// TODO: refactor mapStackTrace: return array not a string, return first row too
|
||||
const stackRows = result.split("\n");
|
||||
const puppeteerLine =
|
||||
stackRows.findIndex(x => x.includes("puppeteer")) ||
|
||||
stackRows.length - 1;
|
||||
|
||||
console.log(
|
||||
`🔥 pageerror at ${route}: ${(e.stack || e.message).split(
|
||||
"\n"
|
||||
)[0] + "\n"}${stackRows.slice(0, puppeteerLine).join("\n")}`
|
||||
);
|
||||
})
|
||||
.catch(e2 => {
|
||||
console.log(`🔥 pageerror at ${route}:`, e);
|
||||
console.log(
|
||||
`️️️⚠️ warning at ${route} (error in source maps):`,
|
||||
e2.message
|
||||
);
|
||||
});
|
||||
} else {
|
||||
console.log(`🔥 pageerror at ${route}:`, e);
|
||||
}
|
||||
onError && onError();
|
||||
});
|
||||
page.on("response", response => {
|
||||
if (response.status() >= 400) {
|
||||
let route = "";
|
||||
try {
|
||||
route = response._request
|
||||
.headers()
|
||||
.referer.replace(`http://localhost:${options.port}`, "");
|
||||
} catch (e) {}
|
||||
console.log(
|
||||
`️️️⚠️ warning at ${route}: got ${response.status()} HTTP code for ${response.url()}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// page.on("requestfailed", msg =>
|
||||
// console.log(`️️️⚠️ ${route} requestfailed:`, msg)
|
||||
// );
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {{page: Page}} opt
|
||||
* @return {Promise<Array<string>>}
|
||||
*/
|
||||
const getLinks = async opt => {
|
||||
const { page } = opt;
|
||||
const anchors = await page.evaluate(() =>
|
||||
Array.from(document.querySelectorAll("a")).map(anchor => {
|
||||
if (anchor.href.baseVal) {
|
||||
const a = document.createElement("a");
|
||||
a.href = anchor.href.baseVal;
|
||||
return a.href;
|
||||
}
|
||||
return anchor.href;
|
||||
})
|
||||
);
|
||||
|
||||
const iframes = await page.evaluate(() =>
|
||||
Array.from(document.querySelectorAll("iframe")).map(iframe => iframe.src)
|
||||
);
|
||||
return anchors.concat(iframes);
|
||||
};
|
||||
|
||||
/**
|
||||
* can not use null as default for function because of TS error https://github.com/Microsoft/TypeScript/issues/14889
|
||||
*
|
||||
* @param {{options: *, basePath: string, beforeFetch: ?(function({ page: Page, route: string }):Promise), afterFetch: ?(function({ page: Page, browser: Browser, route: string }):Promise), onEnd: ?(function():void)}} opt
|
||||
* @return {Promise}
|
||||
*/
|
||||
const crawl = async opt => {
|
||||
const {
|
||||
options,
|
||||
basePath,
|
||||
beforeFetch,
|
||||
afterFetch,
|
||||
onEnd,
|
||||
publicPath,
|
||||
sourceDir
|
||||
} = opt;
|
||||
let shuttingDown = false;
|
||||
let streamClosed = false;
|
||||
|
||||
const onSigint = () => {
|
||||
if (shuttingDown) {
|
||||
process.exit(1);
|
||||
} else {
|
||||
shuttingDown = true;
|
||||
console.log(
|
||||
"\nGracefully shutting down. To exit immediately, press ^C again"
|
||||
);
|
||||
}
|
||||
};
|
||||
process.on("SIGINT", onSigint);
|
||||
|
||||
const onUnhandledRejection = error => {
|
||||
console.log("🔥 UnhandledPromiseRejectionWarning", error);
|
||||
shuttingDown = true;
|
||||
};
|
||||
process.on("unhandledRejection", onUnhandledRejection);
|
||||
|
||||
const queue = _();
|
||||
let enqued = 0;
|
||||
let processed = 0;
|
||||
// use Set instead
|
||||
const uniqueUrls = new Set();
|
||||
const sourcemapStore = {};
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @returns {void}
|
||||
*/
|
||||
const addToQueue = newUrl => {
|
||||
const { hostname, search, hash } = url.parse(newUrl);
|
||||
newUrl = newUrl.replace(`${search || ""}${hash || ""}`, "");
|
||||
if (hostname === "localhost" && !uniqueUrls.has(newUrl) && !streamClosed) {
|
||||
uniqueUrls.add(newUrl);
|
||||
enqued++;
|
||||
queue.write(newUrl);
|
||||
if (enqued == 2 && options.crawl) {
|
||||
addToQueue(`${basePath}${publicPath}/404.html`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const browser = await puppeteer.launch({
|
||||
headless: options.headless,
|
||||
args: options.puppeteerArgs,
|
||||
executablePath: options.puppeteerExecutablePath,
|
||||
ignoreHTTPSErrors: options.puppeteerIgnoreHTTPSErrors,
|
||||
handleSIGINT: false
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} pageUrl
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
const fetchPage = async pageUrl => {
|
||||
const route = pageUrl.replace(basePath, "");
|
||||
|
||||
let skipExistingFile = false;
|
||||
const routePath = route.replace(/\//g, path.sep);
|
||||
const { ext } = path.parse(routePath);
|
||||
if (ext !== ".html" && ext !== "") {
|
||||
const filePath = path.join(sourceDir, routePath);
|
||||
skipExistingFile = fs.existsSync(filePath);
|
||||
}
|
||||
|
||||
if (!shuttingDown && !skipExistingFile) {
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page._client.send("ServiceWorker.disable");
|
||||
await page.setCacheEnabled(options.puppeteer.cache);
|
||||
if (options.viewport) await page.setViewport(options.viewport);
|
||||
if (options.skipThirdPartyRequests)
|
||||
await skipThirdPartyRequests({ page, options, basePath });
|
||||
enableLogging({
|
||||
page,
|
||||
options,
|
||||
route,
|
||||
onError: () => {
|
||||
shuttingDown = true;
|
||||
},
|
||||
sourcemapStore
|
||||
});
|
||||
beforeFetch && beforeFetch({ page, route });
|
||||
await page.setUserAgent(options.userAgent);
|
||||
const tracker = createTracker(page);
|
||||
try {
|
||||
await page.goto(pageUrl, { waitUntil: "networkidle0" });
|
||||
} catch (e) {
|
||||
e.message = augmentTimeoutError(e.message, tracker);
|
||||
throw e;
|
||||
} finally {
|
||||
tracker.dispose();
|
||||
}
|
||||
if (options.waitFor) await page.waitFor(options.waitFor);
|
||||
if (options.crawl) {
|
||||
const links = await getLinks({ page });
|
||||
links.forEach(addToQueue);
|
||||
}
|
||||
afterFetch && (await afterFetch({ page, route, browser, addToQueue }));
|
||||
await page.close();
|
||||
console.log(`✅ crawled ${processed + 1} out of ${enqued} (${route})`);
|
||||
} catch (e) {
|
||||
if (!shuttingDown) {
|
||||
console.log(`🔥 error at ${route}`, e);
|
||||
}
|
||||
shuttingDown = true;
|
||||
}
|
||||
} else {
|
||||
// this message creates a lot of noise
|
||||
// console.log(`🚧 skipping (${processed + 1}/${enqued}) ${route}`);
|
||||
}
|
||||
processed++;
|
||||
if (enqued === processed) {
|
||||
streamClosed = true;
|
||||
queue.end();
|
||||
}
|
||||
return pageUrl;
|
||||
};
|
||||
|
||||
if (options.include) {
|
||||
options.include.map(x => addToQueue(`${basePath}${x}`));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
queue
|
||||
.map(x => _(fetchPage(x)))
|
||||
.mergeWithLimit(options.concurrency)
|
||||
.toArray(async () => {
|
||||
process.removeListener("SIGINT", onSigint);
|
||||
process.removeListener("unhandledRejection", onUnhandledRejection);
|
||||
await browser.close();
|
||||
onEnd && onEnd();
|
||||
if (shuttingDown) return reject("");
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
exports.skipThirdPartyRequests = skipThirdPartyRequests;
|
||||
exports.enableLogging = enableLogging;
|
||||
exports.getLinks = getLinks;
|
||||
exports.crawl = crawl;
|
|
@ -0,0 +1,46 @@
|
|||
/**
|
||||
* Sets up event listeners on the Browser.Page instance to maintain a set
|
||||
* of URLs that have started but never finished or failed.
|
||||
*
|
||||
* @param {Object} page
|
||||
* @return Object
|
||||
*/
|
||||
const createTracker = page => {
|
||||
const requests = new Set();
|
||||
const onStarted = request => requests.add(request);
|
||||
const onFinished = request => requests.delete(request);
|
||||
page.on("request", onStarted);
|
||||
page.on("requestfinished", onFinished);
|
||||
page.on("requestfailed", onFinished);
|
||||
return {
|
||||
urls: () => Array.from(requests).map(r => r.url()),
|
||||
dispose: () => {
|
||||
page.removeListener("request", onStarted);
|
||||
page.removeListener("requestfinished", onFinished);
|
||||
page.removeListener("requestfailed", onFinished);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds information about timed out URLs if given message is about Timeout.
|
||||
*
|
||||
* @param {string} message error message
|
||||
* @param {Object} tracker ConnectionTracker
|
||||
* @returns {string}
|
||||
*/
|
||||
const augmentTimeoutError = (message, tracker) => {
|
||||
if (message.startsWith("Navigation Timeout Exceeded")) {
|
||||
const urls = tracker.urls();
|
||||
if (urls.length > 1) {
|
||||
message += `\nTracked URLs that have not finished: ${urls.join(", ")}`;
|
||||
} else if (urls.length > 0) {
|
||||
message += `\nFor ${urls[0]}`;
|
||||
} else {
|
||||
message += `\nBut there are no pending connections`;
|
||||
}
|
||||
}
|
||||
return message;
|
||||
};
|
||||
|
||||
module.exports = { createTracker, augmentTimeoutError };
|
|
@ -0,0 +1,4 @@
|
|||
/*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
|
||||
!function(e){"use strict";var n=function(n,t,o){function i(e){if(a.body)return e();setTimeout(function(){i(e)})}function r(){l.addEventListener&&l.removeEventListener("load",r),l.media=o||"all"}var d,a=e.document,l=a.createElement("link");if(t)d=t;else{var f=(a.body||a.getElementsByTagName("head")[0]).childNodes;d=f[f.length-1]}var s=a.styleSheets;l.rel="stylesheet",l.href=n,l.media="only x",i(function(){d.parentNode.insertBefore(l,t?d:d.nextSibling)});var u=function(e){for(var n=l.href,t=s.length;t--;)if(s[t].href===n)return e();setTimeout(function(){u(e)})};return l.addEventListener&&l.addEventListener("load",r),l.onloadcssdefined=u,u(r),l};"undefined"!=typeof exports?exports.loadCSS=n:e.loadCSS=n}("undefined"!=typeof global?global:this);
|
||||
/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
|
||||
!function(t){if(t.loadCSS){var e=loadCSS.relpreload={};if(e.support=function(){try{return t.document.createElement("link").relList.supports("preload")}catch(t){return!1}},e.poly=function(){for(var e=t.document.getElementsByTagName("link"),r=0;r<e.length;r++){var n=e[r];"preload"===n.rel&&"style"===n.getAttribute("as")&&(t.loadCSS(n.href,n,n.getAttribute("media")),n.rel=null)}},!e.support()){e.poly();var r=t.setInterval(e.poly,300);t.addEventListener&&t.addEventListener("load",function(){e.poly(),t.clearInterval(r)}),t.attachEvent&&t.attachEvent("onload",function(){t.clearInterval(r)})}}}(this);
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,298 @@
|
|||
'use strict';
|
||||
|
||||
const autoprefixer = require('autoprefixer');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
|
||||
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
|
||||
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
|
||||
const eslintFormatter = require('react-dev-utils/eslintFormatter');
|
||||
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
|
||||
const getClientEnvironment = require('./env');
|
||||
const paths = require('./paths');
|
||||
const fileList = require('./entry');
|
||||
|
||||
const pjson = require('../package.json');
|
||||
|
||||
let entry = {};
|
||||
let htmlWebpackPlugins = [];
|
||||
|
||||
fileList.forEach(function (item) {
|
||||
entry[item] = [
|
||||
require.resolve('./polyfills'),
|
||||
require.resolve('react-dev-utils/webpackHotDevClient'),
|
||||
paths.appSrc + '/' + item + '.js',
|
||||
];
|
||||
|
||||
htmlWebpackPlugins.push(
|
||||
new HtmlWebpackPlugin({
|
||||
inject: true,
|
||||
chunks: [item],
|
||||
template: paths.appHtml,
|
||||
filename: item + '.html'
|
||||
}));
|
||||
});
|
||||
|
||||
// Webpack uses `publicPath` to determine where the app is being served from.
|
||||
// In development, we always serve from the root. This makes config easier.
|
||||
const publicPath = '/';
|
||||
// `publicUrl` is just like `publicPath`, but we will provide it to our app
|
||||
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
|
||||
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
|
||||
const publicUrl = '';
|
||||
// Get environment variables to inject into our app.
|
||||
const env = getClientEnvironment(publicUrl);
|
||||
|
||||
// This is the development configuration.
|
||||
// It is focused on developer experience and fast rebuilds.
|
||||
// The production configuration is different and lives in a separate file.
|
||||
module.exports = {
|
||||
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
|
||||
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
|
||||
devtool: 'cheap-module-source-map',
|
||||
// These are the "entry points" to our application.
|
||||
// This means they will be the "root" imports that are included in JS bundle.
|
||||
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
|
||||
entry: entry,
|
||||
output: {
|
||||
// Add /* filename */ comments to generated require()s in the output.
|
||||
pathinfo: true,
|
||||
path: paths.appBuild,
|
||||
// This does not produce a real file. It's just the virtual path that is
|
||||
// served by WebpackDevServer in development. This is the JS bundle
|
||||
// containing code from all our entry points, and the Webpack runtime.
|
||||
filename: 'static/js/[name].bundle.js',
|
||||
// There are also additional JS chunk files if you use code splitting.
|
||||
chunkFilename: 'static/js/[name].chunk.js',
|
||||
// This is the URL that app is served from. We use "/" in development.
|
||||
publicPath: publicPath,
|
||||
// Point sourcemap entries to original disk location (format as URL on Windows)
|
||||
devtoolModuleFilenameTemplate: info =>
|
||||
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
|
||||
},
|
||||
resolve: {
|
||||
// This allows you to set a fallback for where Webpack should look for modules.
|
||||
// We placed these paths second because we want `node_modules` to "win"
|
||||
// if there are any conflicts. This matches Node resolution mechanism.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253
|
||||
modules: ['node_modules', paths.appNodeModules].concat(
|
||||
// It is guaranteed to exist because we tweak it in `env.js`
|
||||
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
|
||||
),
|
||||
// These are the reasonable defaults supported by the Node ecosystem.
|
||||
// We also include JSX as a common component filename extension to support
|
||||
// some tools, although we do not recommend using it, see:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/290
|
||||
// `web` extension prefixes have been added for better support
|
||||
// for React Native Web.
|
||||
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
|
||||
alias: pjson.alias,
|
||||
plugins: [
|
||||
// Prevents users from importing files from outside of src/ (or node_modules/).
|
||||
// This often causes confusion because we only process files within src/ with babel.
|
||||
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
|
||||
// please link the files into your node_modules/ and let module-resolution kick in.
|
||||
// Make sure your source files are compiled, as they will not be processed in any way.
|
||||
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
|
||||
],
|
||||
},
|
||||
module: {
|
||||
strictExportPresence: true,
|
||||
rules: [
|
||||
// TODO: Disable require.ensure as it's not a standard language feature.
|
||||
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
|
||||
// { parser: { requireEnsure: false } },
|
||||
|
||||
// First, run the linter.
|
||||
// It's important to do this before Babel processes the JS.
|
||||
// {
|
||||
// test: /\.(js|jsx|mjs)$/,
|
||||
// enforce: 'pre',
|
||||
// use: [
|
||||
// {
|
||||
// options: {
|
||||
// formatter: eslintFormatter,
|
||||
// eslintPath: require.resolve('eslint'),
|
||||
|
||||
// },
|
||||
// loader: require.resolve('eslint-loader'),
|
||||
// },
|
||||
// ],
|
||||
// include: paths.appSrc,
|
||||
// },
|
||||
{
|
||||
// "oneOf" will traverse all following loaders until one will
|
||||
// match the requirements. When no loader matches it will fall
|
||||
// back to the "file" loader at the end of the loader list.
|
||||
oneOf: [
|
||||
// "url" loader works like "file" loader except that it embeds assets
|
||||
// smaller than specified limit in bytes as data URLs to avoid requests.
|
||||
// A missing `test` is equivalent to a match.
|
||||
{
|
||||
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
|
||||
loader: require.resolve('url-loader'),
|
||||
options: {
|
||||
limit: 10000,
|
||||
name: 'static/media/[name].[hash:8].[ext]',
|
||||
},
|
||||
},
|
||||
// Process JS with Babel.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
//include: paths.appSrc,
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
[
|
||||
"@babel/preset-react",
|
||||
{
|
||||
"pragma": "Omi.h"
|
||||
}
|
||||
]
|
||||
],
|
||||
"plugins": [
|
||||
"@babel/plugin-proposal-class-properties",
|
||||
[
|
||||
"@babel/plugin-proposal-decorators",
|
||||
{
|
||||
"legacy": true
|
||||
}
|
||||
],
|
||||
"@babel/plugin-proposal-function-bind",
|
||||
"@babel/plugin-proposal-object-rest-spread",
|
||||
"@babel/plugin-syntax-dynamic-import"
|
||||
],
|
||||
// This is a feature of `babel-loader` for webpack (not Babel itself).
|
||||
// It enables caching results in ./node_modules/.cache/babel-loader/
|
||||
// directory for faster rebuilds.
|
||||
cacheDirectory: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /[\\|\/]_[\S]*\.css$/,
|
||||
use: [
|
||||
'to-string-loader',
|
||||
'css-loader'
|
||||
]
|
||||
},
|
||||
// "postcss" loader applies autoprefixer to our CSS.
|
||||
// "css" loader resolves paths in CSS and adds assets as dependencies.
|
||||
// "style" loader turns CSS into JS modules that inject <style> tags.
|
||||
// In production, we use a plugin to extract that CSS to a file, but
|
||||
// in development "style" loader enables hot editing of CSS.
|
||||
{
|
||||
test: /\.css$/,
|
||||
use: [
|
||||
require.resolve('style-loader'),
|
||||
{
|
||||
loader: require.resolve('css-loader'),
|
||||
options: {
|
||||
importLoaders: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
loader: require.resolve('postcss-loader'),
|
||||
options: {
|
||||
// Necessary for external CSS imports to work
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2677
|
||||
ident: 'postcss',
|
||||
plugins: () => [
|
||||
require('postcss-flexbugs-fixes'),
|
||||
autoprefixer({
|
||||
browsers: [
|
||||
'>1%',
|
||||
'last 4 versions',
|
||||
'Firefox ESR',
|
||||
'not ie < 9', // React doesn't support IE8 anyway
|
||||
],
|
||||
flexbox: 'no-2009',
|
||||
}),
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
// "file" loader makes sure those assets get served by WebpackDevServer.
|
||||
// When you `import` an asset, you get its (virtual) filename.
|
||||
// In production, they would get copied to the `build` folder.
|
||||
// This loader doesn't use a "test" so it will catch all modules
|
||||
// that fall through the other loaders.
|
||||
{
|
||||
// Exclude `js` files to keep "css" loader working as it injects
|
||||
// its runtime that would otherwise processed through "file" loader.
|
||||
// Also exclude `html` and `json` extensions so they get processed
|
||||
// by webpacks internal loaders.
|
||||
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
|
||||
loader: require.resolve('file-loader'),
|
||||
options: {
|
||||
name: 'static/media/[name].[hash:8].[ext]',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
// ** STOP ** Are you adding a new loader?
|
||||
// Make sure to add the new loader(s) before the "file" loader.
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
// Makes some environment variables available in index.html.
|
||||
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
|
||||
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// In development, this will be an empty string.
|
||||
|
||||
...htmlWebpackPlugins,
|
||||
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
|
||||
// Generates an `index.html` file with the <script> injected.
|
||||
// new HtmlWebpackPlugin({
|
||||
// inject: true,
|
||||
// chunks:["index"],
|
||||
// template: paths.appHtml,
|
||||
// }),
|
||||
// new HtmlWebpackPlugin({
|
||||
// inject: true,
|
||||
// chunks:["admin"],
|
||||
// template:paths.appHtml,
|
||||
// filename:'admin.html'
|
||||
// }),
|
||||
// Add module names to factory functions so they appear in browser profiler.
|
||||
new webpack.NamedModulesPlugin(),
|
||||
// Makes some environment variables available to the JS code, for example:
|
||||
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
|
||||
new webpack.DefinePlugin(env.stringified),
|
||||
// This is necessary to emit hot updates (currently CSS only):
|
||||
new webpack.HotModuleReplacementPlugin(),
|
||||
// Watcher doesn't work well if you mistype casing in a path so we use
|
||||
// a plugin that prints an error when you attempt to do this.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/240
|
||||
new CaseSensitivePathsPlugin(),
|
||||
// If you require a missing module and then `npm install` it, you still have
|
||||
// to restart the development server for Webpack to discover it. This plugin
|
||||
// makes the discovery automatic so you don't have to restart.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/186
|
||||
//new WatchMissingNodeModulesPlugin(paths.appNodeModules),
|
||||
// Moment.js is an extremely popular library that bundles large locale files
|
||||
// by default due to how Webpack interprets its code. This is a practical
|
||||
// solution that requires the user to opt into importing specific locales.
|
||||
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
|
||||
// You can remove this if you don't use Moment.js:
|
||||
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
|
||||
],
|
||||
// Some libraries import Node modules but don't use them in the browser.
|
||||
// Tell Webpack to provide empty mocks for them so importing them works.
|
||||
node: {
|
||||
dgram: 'empty',
|
||||
fs: 'empty',
|
||||
net: 'empty',
|
||||
tls: 'empty',
|
||||
child_process: 'empty',
|
||||
},
|
||||
// Turn off performance hints during development because we don't do any
|
||||
// splitting or minification in interest of speed. These warnings become
|
||||
// cumbersome.
|
||||
performance: {
|
||||
hints: false,
|
||||
},
|
||||
mode: 'development'
|
||||
};
|
|
@ -0,0 +1,353 @@
|
|||
'use strict';
|
||||
|
||||
const autoprefixer = require('autoprefixer');
|
||||
const path = require('path');
|
||||
const webpack = require('webpack');
|
||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||
const ExtractTextPlugin = require('extract-text-webpack-plugin');
|
||||
const miniCssExtractPlugin = require('mini-css-extract-plugin');
|
||||
const ManifestPlugin = require('webpack-manifest-plugin');
|
||||
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
|
||||
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
|
||||
const eslintFormatter = require('react-dev-utils/eslintFormatter');
|
||||
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
|
||||
const paths = require('./paths');
|
||||
const getClientEnvironment = require('./env');
|
||||
const fileList = require('./entry');
|
||||
const pjson = require('../package.json');
|
||||
|
||||
let entry = {};
|
||||
let htmlWebpackPlugins = [];
|
||||
|
||||
fileList.forEach(function (item) {
|
||||
entry[item] = [
|
||||
require.resolve('./polyfills'),
|
||||
paths.appSrc + '/' + item + '.js',
|
||||
];
|
||||
|
||||
htmlWebpackPlugins.push(
|
||||
new HtmlWebpackPlugin({
|
||||
inject: true,
|
||||
chunks:[item],
|
||||
template: paths.appHtml,
|
||||
filename: item + '.html',
|
||||
minify: {
|
||||
removeComments: true,
|
||||
collapseWhitespace: true,
|
||||
removeRedundantAttributes: true,
|
||||
useShortDoctype: true,
|
||||
removeEmptyAttributes: true,
|
||||
removeStyleLinkTypeAttributes: true,
|
||||
keepClosingSlash: true,
|
||||
minifyJS: true,
|
||||
minifyCSS: true,
|
||||
minifyURLs: true,
|
||||
},
|
||||
}))
|
||||
});
|
||||
|
||||
// Webpack uses `publicPath` to determine where the app is being served from.
|
||||
// It requires a trailing slash, or the file assets will get an incorrect path.
|
||||
const publicPath = paths.servedPath;
|
||||
// Some apps do not use client-side routing with pushState.
|
||||
// For these, "homepage" can be set to "." to enable relative asset paths.
|
||||
const shouldUseRelativeAssetPaths = publicPath === './';
|
||||
// Source maps are resource heavy and can cause out of memory issue for large source files.
|
||||
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
|
||||
// `publicUrl` is just like `publicPath`, but we will provide it to our app
|
||||
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
|
||||
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
|
||||
const publicUrl = publicPath.slice(0, -1);
|
||||
// Get environment variables to inject into our app.
|
||||
const env = getClientEnvironment(publicUrl);
|
||||
|
||||
// Assert this just to be safe.
|
||||
// Development builds of React are slow and not intended for production.
|
||||
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
|
||||
throw new Error('Production builds must have NODE_ENV=production.');
|
||||
}
|
||||
|
||||
// Note: defined here because it will be used more than once.
|
||||
const cssFilename = 'static/css/[name].[contenthash:8].css';
|
||||
|
||||
// ExtractTextPlugin expects the build output to be flat.
|
||||
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
|
||||
// However, our output is structured with css, js and media folders.
|
||||
// To have this structure working with relative paths, we have to use custom options.
|
||||
const extractTextPluginOptions = shouldUseRelativeAssetPaths
|
||||
? // Making sure that the publicPath goes back to to build folder.
|
||||
{ publicPath: Array(cssFilename.split('/').length).join('../') }
|
||||
: {};
|
||||
|
||||
// This is the production configuration.
|
||||
// It compiles slowly and is focused on producing a fast and minimal bundle.
|
||||
// The development configuration is different and lives in a separate file.
|
||||
module.exports = {
|
||||
// Don't attempt to continue if there are any errors.
|
||||
bail: true,
|
||||
// We generate sourcemaps in production. This is slow but gives good results.
|
||||
// You can exclude the *.map files from the build during deployment.
|
||||
devtool: shouldUseSourceMap ? 'source-map' : false,
|
||||
// In production, we only want to load the polyfills and the app code.
|
||||
entry: entry,
|
||||
output: {
|
||||
// The build folder.
|
||||
path: paths.appBuild,
|
||||
// Generated JS file names (with nested folders).
|
||||
// There will be one main bundle, and one file per asynchronous chunk.
|
||||
// We don't currently advertise code splitting but Webpack supports it.
|
||||
filename: 'static/js/[name].[chunkhash:8].js',
|
||||
chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
|
||||
// We inferred the "public path" (such as / or /my-project) from homepage.
|
||||
publicPath: publicPath,
|
||||
// Point sourcemap entries to original disk location (format as URL on Windows)
|
||||
devtoolModuleFilenameTemplate: info =>
|
||||
path
|
||||
.relative(paths.appSrc, info.absoluteResourcePath)
|
||||
.replace(/\\/g, '/'),
|
||||
},
|
||||
resolve: {
|
||||
// This allows you to set a fallback for where Webpack should look for modules.
|
||||
// We placed these paths second because we want `node_modules` to "win"
|
||||
// if there are any conflicts. This matches Node resolution mechanism.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/253
|
||||
modules: ['node_modules', paths.appNodeModules].concat(
|
||||
// It is guaranteed to exist because we tweak it in `env.js`
|
||||
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
|
||||
),
|
||||
// These are the reasonable defaults supported by the Node ecosystem.
|
||||
// We also include JSX as a common component filename extension to support
|
||||
// some tools, although we do not recommend using it, see:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/290
|
||||
// `web` extension prefixes have been added for better support
|
||||
// for React Native Web.
|
||||
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
|
||||
alias: pjson.alias,
|
||||
plugins: [
|
||||
// Prevents users from importing files from outside of src/ (or node_modules/).
|
||||
// This often causes confusion because we only process files within src/ with babel.
|
||||
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
|
||||
// please link the files into your node_modules/ and let module-resolution kick in.
|
||||
// Make sure your source files are compiled, as they will not be processed in any way.
|
||||
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
|
||||
],
|
||||
},
|
||||
module: {
|
||||
strictExportPresence: true,
|
||||
rules: [
|
||||
// TODO: Disable require.ensure as it's not a standard language feature.
|
||||
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
|
||||
// { parser: { requireEnsure: false } },
|
||||
|
||||
// First, run the linter.
|
||||
// It's important to do this before Babel processes the JS.
|
||||
// {
|
||||
// test: /\.(js|jsx|mjs)$/,
|
||||
// enforce: 'pre',
|
||||
// use: [
|
||||
// {
|
||||
// options: {
|
||||
// formatter: eslintFormatter,
|
||||
// eslintPath: require.resolve('eslint'),
|
||||
|
||||
// },
|
||||
// loader: require.resolve('eslint-loader'),
|
||||
// },
|
||||
// ],
|
||||
// include: paths.appSrc,
|
||||
// },
|
||||
{
|
||||
// "oneOf" will traverse all following loaders until one will
|
||||
// match the requirements. When no loader matches it will fall
|
||||
// back to the "file" loader at the end of the loader list.
|
||||
oneOf: [
|
||||
// "url" loader works just like "file" loader but it also embeds
|
||||
// assets smaller than specified size as data URLs to avoid requests.
|
||||
{
|
||||
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
|
||||
loader: require.resolve('url-loader'),
|
||||
options: {
|
||||
limit: 10000,
|
||||
name: 'static/media/[name].[hash:8].[ext]',
|
||||
},
|
||||
},
|
||||
// Process JS with Babel.
|
||||
{
|
||||
test: /\.(js|jsx|mjs)$/,
|
||||
//include: paths.appSrc,
|
||||
loader: require.resolve('babel-loader'),
|
||||
options: {
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
[
|
||||
"@babel/preset-react",
|
||||
{
|
||||
"pragma": "Omi.h"
|
||||
}
|
||||
]
|
||||
],
|
||||
"plugins": [
|
||||
"@babel/plugin-proposal-class-properties",
|
||||
[
|
||||
"@babel/plugin-proposal-decorators",
|
||||
{
|
||||
"legacy": true
|
||||
}
|
||||
],
|
||||
"@babel/plugin-proposal-function-bind",
|
||||
"@babel/plugin-proposal-object-rest-spread",
|
||||
"@babel/plugin-syntax-dynamic-import"
|
||||
],
|
||||
compact: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
test: /[\\|\/]_[\S]*\.css$/,
|
||||
use: [
|
||||
'to-string-loader',
|
||||
'css-loader'
|
||||
]
|
||||
},
|
||||
// The notation here is somewhat confusing.
|
||||
// "postcss" loader applies autoprefixer to our CSS.
|
||||
// "css" loader resolves paths in CSS and adds assets as dependencies.
|
||||
// "style" loader normally turns CSS into JS modules injecting <style>,
|
||||
// but unlike in development configuration, we do something different.
|
||||
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
|
||||
// (second argument), then grabs the result CSS and puts it into a
|
||||
// separate file in our build process. This way we actually ship
|
||||
// a single CSS file in production instead of JS code injecting <style>
|
||||
// tags. If you use code splitting, however, any async bundles will still
|
||||
// use the "style" loader inside the async code so CSS from them won't be
|
||||
// in the main CSS file.
|
||||
{
|
||||
test: /\.css$/,
|
||||
use: [
|
||||
'style-loader',
|
||||
'css-loader'
|
||||
]
|
||||
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
|
||||
},
|
||||
// "file" loader makes sure assets end up in the `build` folder.
|
||||
// When you `import` an asset, you get its filename.
|
||||
// This loader doesn't use a "test" so it will catch all modules
|
||||
// that fall through the other loaders.
|
||||
{
|
||||
loader: require.resolve('file-loader'),
|
||||
// Exclude `js` files to keep "css" loader working as it injects
|
||||
// it's runtime that would otherwise processed through "file" loader.
|
||||
// Also exclude `html` and `json` extensions so they get processed
|
||||
// by webpacks internal loaders.
|
||||
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
|
||||
options: {
|
||||
name: 'static/media/[name].[hash:8].[ext]',
|
||||
},
|
||||
},
|
||||
// ** STOP ** Are you adding a new loader?
|
||||
// Make sure to add the new loader(s) before the "file" loader.
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
// Makes some environment variables available in index.html.
|
||||
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
|
||||
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// In production, it will be an empty string unless you specify "homepage"
|
||||
// in `package.json`, in which case it will be the pathname of that URL.
|
||||
|
||||
// Generates an `index.html` file with the <script> injected.
|
||||
...htmlWebpackPlugins,
|
||||
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
|
||||
// Makes some environment variables available to the JS code, for example:
|
||||
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
|
||||
// It is absolutely essential that NODE_ENV was set to production here.
|
||||
// Otherwise React will be compiled in the very slow development mode.
|
||||
new webpack.DefinePlugin(env.stringified),
|
||||
// Minify the code.
|
||||
// new webpack.optimize.UglifyJsPlugin({
|
||||
// compress: {
|
||||
// warnings: false,
|
||||
// // Disabled because of an issue with Uglify breaking seemingly valid code:
|
||||
// // https://github.com/facebookincubator/create-react-app/issues/2376
|
||||
// // Pending further investigation:
|
||||
// // https://github.com/mishoo/UglifyJS2/issues/2011
|
||||
// comparisons: false,
|
||||
// },
|
||||
// mangle: {
|
||||
// safari10: true,
|
||||
// },
|
||||
// output: {
|
||||
// comments: false,
|
||||
// // Turned on because emoji and regex is not minified properly using default
|
||||
// // https://github.com/facebookincubator/create-react-app/issues/2488
|
||||
// ascii_only: true,
|
||||
// },
|
||||
// sourceMap: shouldUseSourceMap,
|
||||
// }),
|
||||
// Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
|
||||
// new ExtractTextPlugin({
|
||||
// filename: cssFilename,
|
||||
// }),
|
||||
|
||||
|
||||
new miniCssExtractPlugin({
|
||||
filename: cssFilename
|
||||
}),
|
||||
// Generate a manifest file which contains a mapping of all asset filenames
|
||||
// to their corresponding output file so that tools can pick it up without
|
||||
// having to parse `index.html`.
|
||||
new ManifestPlugin({
|
||||
fileName: 'asset-manifest.json',
|
||||
}),
|
||||
// Generate a service worker script that will precache, and keep up to date,
|
||||
// the HTML & assets that are part of the Webpack build.
|
||||
new SWPrecacheWebpackPlugin({
|
||||
// By default, a cache-busting query parameter is appended to requests
|
||||
// used to populate the caches, to ensure the responses are fresh.
|
||||
// If a URL is already hashed by Webpack, then there is no concern
|
||||
// about it being stale, and the cache-busting can be skipped.
|
||||
dontCacheBustUrlsMatching: /\.\w{8}\./,
|
||||
filename: 'service-worker.js',
|
||||
logger(message) {
|
||||
if (message.indexOf('Total precache size is') === 0) {
|
||||
// This message occurs for every build and is a bit too noisy.
|
||||
return;
|
||||
}
|
||||
if (message.indexOf('Skipping static resource') === 0) {
|
||||
// This message obscures real errors so we ignore it.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2612
|
||||
return;
|
||||
}
|
||||
console.log(message);
|
||||
},
|
||||
minify: true,
|
||||
// For unknown URLs, fallback to the index page
|
||||
navigateFallback: publicUrl + '/index.html',
|
||||
// Ignores URLs starting from /__ (useful for Firebase):
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
|
||||
navigateFallbackWhitelist: [/^(?!\/__).*/],
|
||||
// Don't precache sourcemaps (they're large) and build asset manifest:
|
||||
staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
|
||||
}),
|
||||
// Moment.js is an extremely popular library that bundles large locale files
|
||||
// by default due to how Webpack interprets its code. This is a practical
|
||||
// solution that requires the user to opt into importing specific locales.
|
||||
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
|
||||
// You can remove this if you don't use Moment.js:
|
||||
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
|
||||
],
|
||||
// Some libraries import Node modules but don't use them in the browser.
|
||||
// Tell Webpack to provide empty mocks for them so importing them works.
|
||||
node: {
|
||||
dgram: 'empty',
|
||||
fs: 'empty',
|
||||
net: 'empty',
|
||||
tls: 'empty',
|
||||
child_process: 'empty',
|
||||
},
|
||||
mode: 'production',
|
||||
optimization: {
|
||||
minimize: true
|
||||
}
|
||||
};
|
|
@ -0,0 +1,108 @@
|
|||
'use strict';
|
||||
|
||||
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
|
||||
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
|
||||
const ignoredFiles = require('react-dev-utils/ignoredFiles');
|
||||
const config = require('./webpack.config.dev');
|
||||
const paths = require('./paths');
|
||||
|
||||
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
|
||||
const host = process.env.HOST || '0.0.0.0';
|
||||
|
||||
// const fileList = require('./entry');
|
||||
|
||||
// let rewrites = [];
|
||||
|
||||
// fileList.forEach(function (item) {
|
||||
|
||||
// rewrites.push({ from: new RegExp('^\/' + item + '.html', 'g'), to: '/build/' + item + '.html' })
|
||||
|
||||
// });
|
||||
|
||||
|
||||
|
||||
module.exports = function(proxy, allowedHost) {
|
||||
return {
|
||||
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
|
||||
// websites from potentially accessing local content through DNS rebinding:
|
||||
// https://github.com/webpack/webpack-dev-server/issues/887
|
||||
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
|
||||
// However, it made several existing use cases such as development in cloud
|
||||
// environment or subdomains in development significantly more complicated:
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2271
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2233
|
||||
// While we're investigating better solutions, for now we will take a
|
||||
// compromise. Since our WDS configuration only serves files in the `public`
|
||||
// folder we won't consider accessing them a vulnerability. However, if you
|
||||
// use the `proxy` feature, it gets more dangerous because it can expose
|
||||
// remote code execution vulnerabilities in backends like Django and Rails.
|
||||
// So we will disable the host check normally, but enable it if you have
|
||||
// specified the `proxy` setting. Finally, we let you override it if you
|
||||
// really know what you're doing with a special environment variable.
|
||||
disableHostCheck:
|
||||
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
|
||||
// Enable gzip compression of generated files.
|
||||
compress: true,
|
||||
// Silence WebpackDevServer's own logs since they're generally not useful.
|
||||
// It will still show compile warnings and errors with this setting.
|
||||
clientLogLevel: 'none',
|
||||
// By default WebpackDevServer serves physical files from current directory
|
||||
// in addition to all the virtual build products that it serves from memory.
|
||||
// This is confusing because those files won’t automatically be available in
|
||||
// production build folder unless we copy them. However, copying the whole
|
||||
// project directory is dangerous because we may expose sensitive files.
|
||||
// Instead, we establish a convention that only files in `public` directory
|
||||
// get served. Our build script will copy `public` into the `build` folder.
|
||||
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
|
||||
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
|
||||
// Note that we only recommend to use `public` folder as an escape hatch
|
||||
// for files like `favicon.ico`, `manifest.json`, and libraries that are
|
||||
// for some reason broken when imported through Webpack. If you just want to
|
||||
// use an image, put it in `src` and `import` it from JavaScript instead.
|
||||
contentBase: paths.appPublic,
|
||||
// By default files from `contentBase` will not trigger a page reload.
|
||||
watchContentBase: true,
|
||||
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
|
||||
// for the WebpackDevServer client so it can learn when the files were
|
||||
// updated. The WebpackDevServer client is included as an entry point
|
||||
// in the Webpack development configuration. Note that only changes
|
||||
// to CSS are currently hot reloaded. JS changes will refresh the browser.
|
||||
hot: true,
|
||||
// It is important to tell WebpackDevServer to use the same "root" path
|
||||
// as we specified in the config. In development, we always serve from /.
|
||||
publicPath: config.output.publicPath,
|
||||
// WebpackDevServer is noisy by default so we emit custom message instead
|
||||
// by listening to the compiler events with `compiler.plugin` calls above.
|
||||
quiet: true,
|
||||
// Reportedly, this avoids CPU overload on some systems.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/293
|
||||
// src/node_modules is not ignored to support absolute imports
|
||||
// https://github.com/facebookincubator/create-react-app/issues/1065
|
||||
watchOptions: {
|
||||
ignored: ignoredFiles(paths.appSrc),
|
||||
},
|
||||
// Enable HTTPS if the HTTPS environment variable is set to 'true'
|
||||
https: protocol === 'https',
|
||||
host: host,
|
||||
overlay: false,
|
||||
historyApiFallback: {
|
||||
// Paths with dots should still use the history fallback.
|
||||
// See https://github.com/facebookincubator/create-react-app/issues/387.
|
||||
disableDotRule: true
|
||||
//rewrites: rewrites
|
||||
},
|
||||
public: allowedHost,
|
||||
proxy,
|
||||
before(app) {
|
||||
// This lets us open files from the runtime error overlay.
|
||||
app.use(errorOverlayMiddleware());
|
||||
// This service worker file is effectively a 'no-op' that will reset any
|
||||
// previous service worker registered for the same host:port combination.
|
||||
// We do this in development to avoid hitting the production cache if
|
||||
// it used the same host and port.
|
||||
// https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
|
||||
app.use(noopServiceWorkerMiddleware());
|
||||
},
|
||||
};
|
||||
};
|
|
@ -0,0 +1,21 @@
|
|||
# See https://help.github.com/ignore-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
|
@ -0,0 +1,151 @@
|
|||
{
|
||||
"name": "my-app",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@babel/cli": "^7.0.0",
|
||||
"@babel/core": "^7.2.2",
|
||||
"@babel/plugin-proposal-class-properties": "^7.2.3",
|
||||
"@babel/plugin-proposal-decorators": "^7.2.3",
|
||||
"@babel/plugin-proposal-function-bind": "^7.2.0",
|
||||
"@babel/plugin-proposal-object-rest-spread": "^7.2.0",
|
||||
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
|
||||
"@babel/preset-env": "^7.2.3",
|
||||
"@babel/preset-react": "^7.0.0",
|
||||
"@babel/runtime": "^7.2.0",
|
||||
"autoprefixer": "7.1.6",
|
||||
"babel-core": "^7.0.0-bridge.0",
|
||||
"babel-loader": "^8.0.5",
|
||||
"babel-eslint": "7.2.3",
|
||||
"babel-jest": "20.0.3",
|
||||
"case-sensitive-paths-webpack-plugin": "2.1.1",
|
||||
"chalk": "1.1.3",
|
||||
"css": "^2.2.4",
|
||||
"css-loader": "^1.0.1",
|
||||
"dotenv": "4.0.0",
|
||||
"dotenv-expand": "4.2.0",
|
||||
"eslint": "^4.18.2",
|
||||
"eslint-config-prettier": "^3.1.0",
|
||||
"eslint-loader": "1.9.0",
|
||||
"eslint-plugin-flowtype": "2.39.1",
|
||||
"eslint-plugin-import": "2.8.0",
|
||||
"eslint-plugin-jsx-a11y": "5.1.1",
|
||||
"eslint-plugin-prettier": "^3.0.0",
|
||||
"extract-text-webpack-plugin": "^4.0.0-beta.0",
|
||||
"file": "^0.2.2",
|
||||
"file-loader": "^2.0.0",
|
||||
"fs-extra": "3.0.1",
|
||||
"html-webpack-plugin": "^4.0.0-beta.5",
|
||||
"jest": "20.0.4",
|
||||
"less": "^3.9.0",
|
||||
"less-loader": "^4.1.0",
|
||||
"mini-css-extract-plugin": "^0.5.0",
|
||||
"object-assign": "4.1.1",
|
||||
"omi": "latest",
|
||||
"omio": "latest",
|
||||
"omiu": "latest",
|
||||
"omi-router": "latest",
|
||||
"optimize-css-assets-webpack-plugin": "^5.0.1",
|
||||
"postcss-flexbugs-fixes": "3.2.0",
|
||||
"postcss-loader": "2.0.8",
|
||||
"prettier": "^1.14.3",
|
||||
"promise": "8.0.1",
|
||||
"raf": "3.4.0",
|
||||
"react-dev-utils": "^7.0.1",
|
||||
"resolve": "1.6.0",
|
||||
"style-loader": "0.19.0",
|
||||
"sw-precache-webpack-plugin": "^0.11.5",
|
||||
"to-string-loader": "^1.1.5",
|
||||
"url": "^0.11.0",
|
||||
"url-loader": "^1.1.2",
|
||||
"webpack": "^4.28.3",
|
||||
"webpack-cli": "^3.2.0",
|
||||
"webpack-dev-server": "^3.1.10",
|
||||
"webpack-manifest-plugin": "^2.0.4",
|
||||
"webpack-merge": "^4.2.1",
|
||||
"whatwg-fetch": "2.0.3",
|
||||
"clean-css": "4.2.1",
|
||||
"express": "4.16.4",
|
||||
"express-history-api-fallback": "2.2.1",
|
||||
"highland": "2.13.0",
|
||||
"html-minifier": "3.5.21",
|
||||
"minimalcss": "0.8.1",
|
||||
"mkdirp": "0.5.1",
|
||||
"puppeteer": "^1.8.0",
|
||||
"serve-static": "1.13.2",
|
||||
"sourcemapped-stacktrace-node": "2.1.8"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node scripts/start.js",
|
||||
"build": "PUBLIC_URL=. node scripts/build.js",
|
||||
"build-windows": "set PUBLIC_URL=.&& node scripts/build.js",
|
||||
"fix": "eslint src --fix",
|
||||
"postbuild": "node config/snap/run.js"
|
||||
},
|
||||
"jest": {
|
||||
"collectCoverageFrom": [
|
||||
"src/**/*.{js,jsx,mjs}"
|
||||
],
|
||||
"setupFiles": [
|
||||
"<rootDir>/config/polyfills.js"
|
||||
],
|
||||
"testMatch": [
|
||||
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
|
||||
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
|
||||
],
|
||||
"testEnvironment": "node",
|
||||
"testURL": "http://localhost",
|
||||
"transform": {
|
||||
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
|
||||
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
|
||||
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
|
||||
},
|
||||
"transformIgnorePatterns": [
|
||||
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
|
||||
],
|
||||
"moduleNameMapper": {
|
||||
"^react-native$": "react-native-web"
|
||||
},
|
||||
"moduleFileExtensions": [
|
||||
"web.js",
|
||||
"js",
|
||||
"json",
|
||||
"web.jsx",
|
||||
"jsx",
|
||||
"node",
|
||||
"mjs"
|
||||
]
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
[
|
||||
"@babel/preset-react",
|
||||
{
|
||||
"pragma": "Omi.h"
|
||||
}
|
||||
]
|
||||
],
|
||||
"plugins": [
|
||||
"@babel/plugin-proposal-class-properties",
|
||||
[
|
||||
"@babel/plugin-proposal-decorators",
|
||||
{
|
||||
"legacy": true
|
||||
}
|
||||
],
|
||||
"@babel/plugin-proposal-function-bind",
|
||||
"@babel/plugin-proposal-object-rest-spread",
|
||||
"@babel/plugin-syntax-dynamic-import"
|
||||
]
|
||||
},
|
||||
"prettier": {
|
||||
"singleQuote": true,
|
||||
"semi": false,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
},
|
||||
"alias": {
|
||||
"omi": "omio"
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 66 KiB |
|
@ -0,0 +1,40 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
<meta name="theme-color" content="#000000">
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is added to the
|
||||
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>Omi</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
You need to enable JavaScript to run this app.
|
||||
</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"short_name": "Omi App",
|
||||
"name": "Omi Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": "./index.html",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
|
@ -0,0 +1,150 @@
|
|||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'production';
|
||||
process.env.NODE_ENV = 'production';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const path = require('path');
|
||||
const chalk = require('chalk');
|
||||
const fs = require('fs-extra');
|
||||
const webpack = require('webpack');
|
||||
const config = require('../config/webpack.config.prod');
|
||||
const paths = require('../config/paths');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
|
||||
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
|
||||
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
|
||||
const printBuildError = require('react-dev-utils/printBuildError');
|
||||
|
||||
const measureFileSizesBeforeBuild =
|
||||
FileSizeReporter.measureFileSizesBeforeBuild;
|
||||
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
|
||||
const useYarn = fs.existsSync(paths.yarnLockFile);
|
||||
|
||||
// These sizes are pretty large. We'll warn for bundles exceeding them.
|
||||
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
|
||||
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// First, read the current file sizes in build directory.
|
||||
// This lets us display how much they changed later.
|
||||
measureFileSizesBeforeBuild(paths.appBuild)
|
||||
.then(previousFileSizes => {
|
||||
// Remove all content but keep the directory so that
|
||||
// if you're in it, you don't end up in Trash
|
||||
fs.emptyDirSync(paths.appBuild);
|
||||
// Merge with the public folder
|
||||
copyPublicFolder();
|
||||
// Start the webpack build
|
||||
return build(previousFileSizes);
|
||||
})
|
||||
.then(
|
||||
({ stats, previousFileSizes, warnings }) => {
|
||||
if (warnings.length) {
|
||||
console.log(chalk.yellow('Compiled with warnings.\n'));
|
||||
console.log(warnings.join('\n\n'));
|
||||
console.log(
|
||||
'\nSearch for the ' +
|
||||
chalk.underline(chalk.yellow('keywords')) +
|
||||
' to learn more about each warning.'
|
||||
);
|
||||
console.log(
|
||||
'To ignore, add ' +
|
||||
chalk.cyan('// eslint-disable-next-line') +
|
||||
' to the line before.\n'
|
||||
);
|
||||
} else {
|
||||
console.log(chalk.green('Compiled successfully.\n'));
|
||||
}
|
||||
|
||||
console.log('File sizes after gzip:\n');
|
||||
printFileSizesAfterBuild(
|
||||
stats,
|
||||
previousFileSizes,
|
||||
paths.appBuild,
|
||||
WARN_AFTER_BUNDLE_GZIP_SIZE,
|
||||
WARN_AFTER_CHUNK_GZIP_SIZE
|
||||
);
|
||||
console.log();
|
||||
|
||||
const appPackage = require(paths.appPackageJson);
|
||||
const publicUrl = paths.publicUrl;
|
||||
const publicPath = config.output.publicPath;
|
||||
const buildFolder = path.relative(process.cwd(), paths.appBuild);
|
||||
printHostingInstructions(
|
||||
appPackage,
|
||||
publicUrl,
|
||||
publicPath,
|
||||
buildFolder,
|
||||
useYarn
|
||||
);
|
||||
},
|
||||
err => {
|
||||
console.log(chalk.red('Failed to compile.\n'));
|
||||
printBuildError(err);
|
||||
process.exit(1);
|
||||
}
|
||||
);
|
||||
|
||||
// Create the production build and print the deployment instructions.
|
||||
function build(previousFileSizes) {
|
||||
console.log('Creating an optimized production build...');
|
||||
|
||||
let compiler = webpack(config);
|
||||
return new Promise((resolve, reject) => {
|
||||
compiler.run((err, stats) => {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
const messages = formatWebpackMessages(stats.toJson({}, true));
|
||||
if (messages.errors.length) {
|
||||
// Only keep the first error. Others are often indicative
|
||||
// of the same problem, but confuse the reader with noise.
|
||||
if (messages.errors.length > 1) {
|
||||
messages.errors.length = 1;
|
||||
}
|
||||
return reject(new Error(messages.errors.join('\n\n')));
|
||||
}
|
||||
if (
|
||||
process.env.CI &&
|
||||
(typeof process.env.CI !== 'string' ||
|
||||
process.env.CI.toLowerCase() !== 'false') &&
|
||||
messages.warnings.length
|
||||
) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'\nTreating warnings as errors because process.env.CI = true.\n' +
|
||||
'Most CI servers set it automatically.\n'
|
||||
)
|
||||
);
|
||||
return reject(new Error(messages.warnings.join('\n\n')));
|
||||
}
|
||||
return resolve({
|
||||
stats,
|
||||
previousFileSizes,
|
||||
warnings: messages.warnings,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function copyPublicFolder() {
|
||||
fs.copySync(paths.appPublic, paths.appBuild, {
|
||||
dereference: true,
|
||||
filter: file => file !== paths.appHtml,
|
||||
});
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'development';
|
||||
process.env.NODE_ENV = 'development';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const fs = require('fs');
|
||||
const chalk = require('chalk');
|
||||
const webpack = require('webpack');
|
||||
const WebpackDevServer = require('webpack-dev-server');
|
||||
const clearConsole = require('react-dev-utils/clearConsole');
|
||||
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
|
||||
const {
|
||||
choosePort,
|
||||
createCompiler,
|
||||
prepareProxy,
|
||||
prepareUrls,
|
||||
} = require('react-dev-utils/WebpackDevServerUtils');
|
||||
const openBrowser = require('react-dev-utils/openBrowser');
|
||||
const paths = require('../config/paths');
|
||||
const config = require('../config/webpack.config.dev');
|
||||
const createDevServerConfig = require('../config/webpackDevServer.config');
|
||||
|
||||
const useYarn = fs.existsSync(paths.yarnLockFile);
|
||||
const isInteractive = process.stdout.isTTY;
|
||||
|
||||
// Warn and crash if required files are missing
|
||||
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Tools like Cloud9 rely on this.
|
||||
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
|
||||
if (process.env.HOST) {
|
||||
console.log(
|
||||
chalk.cyan(
|
||||
`Attempting to bind to HOST environment variable: ${chalk.yellow(
|
||||
chalk.bold(process.env.HOST)
|
||||
)}`
|
||||
)
|
||||
);
|
||||
console.log(
|
||||
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
|
||||
);
|
||||
console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
|
||||
console.log();
|
||||
}
|
||||
|
||||
// We attempt to use the default port but if it is busy, we offer the user to
|
||||
// run on a different port. `choosePort()` Promise resolves to the next free port.
|
||||
choosePort(HOST, DEFAULT_PORT)
|
||||
.then(port => {
|
||||
if (port == null) {
|
||||
// We have not found a port.
|
||||
return;
|
||||
}
|
||||
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
|
||||
const appName = require(paths.appPackageJson).name;
|
||||
const urls = prepareUrls(protocol, HOST, port);
|
||||
// Create a webpack compiler that is configured with custom messages.
|
||||
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
|
||||
// Load proxy config
|
||||
const proxySetting = require(paths.appPackageJson).proxy;
|
||||
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
|
||||
// Serve webpack assets generated by the compiler over a web sever.
|
||||
const serverConfig = createDevServerConfig(
|
||||
proxyConfig,
|
||||
urls.lanUrlForConfig
|
||||
);
|
||||
const devServer = new WebpackDevServer(compiler, serverConfig);
|
||||
// Launch WebpackDevServer.
|
||||
devServer.listen(port, HOST, err => {
|
||||
if (err) {
|
||||
return console.log(err);
|
||||
}
|
||||
if (isInteractive) {
|
||||
clearConsole();
|
||||
}
|
||||
console.log(chalk.cyan('Starting the development server...\n'));
|
||||
openBrowser(urls.localUrlForBrowser);
|
||||
});
|
||||
|
||||
['SIGINT', 'SIGTERM'].forEach(function(sig) {
|
||||
process.on(sig, function() {
|
||||
devServer.close();
|
||||
process.exit();
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(err => {
|
||||
if (err && err.message) {
|
||||
console.log(err.message);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
|
@ -0,0 +1,27 @@
|
|||
'use strict';
|
||||
|
||||
// Do this as the first thing so that any code reading it knows the right env.
|
||||
process.env.BABEL_ENV = 'test';
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.PUBLIC_URL = '';
|
||||
|
||||
// Makes the script crash on unhandled rejections instead of silently
|
||||
// ignoring them. In the future, promise rejections that are not handled will
|
||||
// terminate the Node.js process with a non-zero exit code.
|
||||
process.on('unhandledRejection', err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Ensure environment variables are read.
|
||||
require('../config/env');
|
||||
|
||||
const jest = require('jest');
|
||||
let argv = process.argv.slice(2);
|
||||
|
||||
// Watch unless on CI or in coverage mode
|
||||
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
|
||||
argv.push('--watch');
|
||||
}
|
||||
|
||||
|
||||
jest.run(argv);
|
|
@ -0,0 +1,6 @@
|
|||
import { render } from 'omi'
|
||||
import './assets/index.css'
|
||||
import './elements/hello'
|
||||
import store from './store/admin-store'
|
||||
|
||||
render(<hello-element />, '#root', store)
|
|
@ -0,0 +1,5 @@
|
|||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: sans-serif;
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
.app-intro {
|
||||
font-size: large;
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
import { define, WeElement } from 'omi'
|
||||
import style from './_index.css'
|
||||
|
||||
define('app-intro', class extends WeElement {
|
||||
css() {
|
||||
return (
|
||||
style +
|
||||
`
|
||||
code{
|
||||
color: ${Math.random() > 0.5 ? 'red' : 'blue'}
|
||||
}`
|
||||
)
|
||||
}
|
||||
|
||||
render(props, data) {
|
||||
return (
|
||||
<p class="app-intro">
|
||||
To get started, edit <code>src/elements/*/*.*</code> and save to reload.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
})
|
|
@ -0,0 +1,32 @@
|
|||
.app {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.app-logo {
|
||||
animation: app-logo-spin infinite 20s linear;
|
||||
height: 80px;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
background-color: #222;
|
||||
height: 150px;
|
||||
padding: 20px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.app-title {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
.app-logo {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@keyframes app-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
import { define, WeElement } from 'omi'
|
||||
import logo from './logo.svg'
|
||||
import style from './_index.css'
|
||||
import '../app-intro'
|
||||
import 'omiu/button'
|
||||
|
||||
define('my-app', class extends WeElement {
|
||||
name = ''
|
||||
|
||||
clickHandler = () => {
|
||||
this.name = 'Omio'
|
||||
this.update()
|
||||
}
|
||||
|
||||
installed = ()=>{
|
||||
setTimeout(()=>{
|
||||
this.name='sfsdfsf'
|
||||
this.update()
|
||||
},3000)
|
||||
|
||||
|
||||
}
|
||||
css() {
|
||||
return style
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div class="app">
|
||||
<header class="app-header">
|
||||
<img
|
||||
src={logo}
|
||||
onClick={this.clickHandler}
|
||||
class="app-logo"
|
||||
alt="logo"
|
||||
/>
|
||||
<h1 class="app-title">Welcome to {this.name}</h1>
|
||||
</header>
|
||||
<app-intro />
|
||||
<o-button style='width:200px;'>I am omiu button.</o-button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
|
@ -0,0 +1,23 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="529px" height="529px" viewBox="0 0 529 529" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>OMI</title>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-1">
|
||||
<stop stop-color="#FFD4DE" offset="0%"></stop>
|
||||
<stop stop-color="#D0021B" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-2">
|
||||
<stop stop-color="#00375E" offset="0%"></stop>
|
||||
<stop stop-color="#9ECAFD" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="linearGradient-3">
|
||||
<stop stop-color="#B4EC51" offset="0%"></stop>
|
||||
<stop stop-color="#429321" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g id="OMI" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<path d="M360.461194,392.400665 L331.766299,363.852923 C362.137315,342.610697 382,307.374938 382,267.5 C382,242.280821 374.054892,218.917322 360.531177,199.776002 L264.653589,295.653589 L249.205844,280.205844 L249.063708,280.34798 L168.478308,199.762579 C154.948823,218.906399 147,242.274926 147,267.5 C147,307.374938 166.862685,342.610697 197.233701,363.852923 L168.538806,392.400665 C131.116001,363.605836 107,318.369215 107,267.5 C107,216.869975 130.889745,171.819699 168.011797,143.006609 L222.432893,197.148622 L264.511454,239.227182 L311.034034,192.704602 L360.988203,143.006609 C398.110255,171.819699 422,216.869975 422,267.5 C422,318.369215 397.883999,363.605836 360.461194,392.400665 Z" id="M" fill="url(#linearGradient-1)" fill-rule="nonzero"></path>
|
||||
<path d="M264.5,472 C149.900914,472 57,379.099086 57,264.5 C57,149.900914 149.900914,57 264.5,57 C379.099086,57 472,149.900914 472,264.5 C472,379.099086 379.099086,472 264.5,472 Z M263.5,436 C357.112265,436 433,360.112265 433,266.5 C433,172.887735 357.112265,97 263.5,97 C169.887735,97 94,172.887735 94,266.5 C94,360.112265 169.887735,436 263.5,436 Z" id="O" fill="url(#linearGradient-2)" fill-rule="nonzero"></path>
|
||||
<circle id="I-Dot" fill="url(#linearGradient-3)" fill-rule="nonzero" cx="319" cy="142" r="20"></circle>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 2.3 KiB |
|
@ -0,0 +1,10 @@
|
|||
.hello {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.omi {
|
||||
width: 143px;
|
||||
height: 59px;
|
||||
margin: 0 auto;
|
||||
background-image: url(./omi.png);
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
import { define, WeElement } from 'omi'
|
||||
import style from './_index.css'
|
||||
|
||||
define('hello-element', class extends WeElement {
|
||||
installed() {
|
||||
setTimeout(() => {
|
||||
this.store.name = 'Good Job!'
|
||||
this.update()
|
||||
}, 1000)
|
||||
}
|
||||
css() {
|
||||
return style
|
||||
}
|
||||
|
||||
render(props, data) {
|
||||
return (
|
||||
<div class="hello">
|
||||
<h1> {this.store.name} </h1>
|
||||
<div> I am hello element.</div>
|
||||
<div class="omi" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
})
|
Binary file not shown.
After Width: | Height: | Size: 3.2 KiB |
|
@ -0,0 +1,7 @@
|
|||
import { render } from 'omi'
|
||||
import './assets/index.css'
|
||||
import './elements/app'
|
||||
|
||||
render(<my-app />, '#root', {
|
||||
merge: document.querySelector('#root').firstChild
|
||||
})
|
|
@ -0,0 +1,6 @@
|
|||
export default {
|
||||
name: 'I am admin page',
|
||||
rename(name) {
|
||||
this.name = name
|
||||
}
|
||||
}
|
|
@ -0,0 +1,160 @@
|
|||
/**
|
||||
* mappingjs v2.0.0 by dntzhang
|
||||
* Objects mapping for javascript. Omi MVVM's best partner.
|
||||
* @method mapping
|
||||
* @param {from} options
|
||||
* @param {to} options
|
||||
* @param {rule} options
|
||||
* @return {Object} To Object
|
||||
*/
|
||||
|
||||
var ARRAYTYPE = '[object Array]'
|
||||
var OBJECTTYPE = '[object Object]'
|
||||
|
||||
function mapping(from, to, rule) {
|
||||
var tempRule = Object.assign({}, rule)
|
||||
var res = to || {}
|
||||
Object.keys(from).forEach(function(key) {
|
||||
var obj = from[key]
|
||||
if (isArray(obj)) {
|
||||
res[key] = res[key] || []
|
||||
arrayMapping(obj, res[key], tempRule, key)
|
||||
} else if (isObject(obj)) {
|
||||
res[key] = res[key] || {}
|
||||
objMapping(obj, res[key], tempRule, key)
|
||||
} else {
|
||||
res[key] = obj
|
||||
}
|
||||
})
|
||||
|
||||
rule &&
|
||||
Object.keys(tempRule).forEach(function(key) {
|
||||
var arr = key
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
|
||||
if (arr.length === 1) {
|
||||
res[key] = tempRule[key].call ? tempRule[key].call(from) : tempRule[key]
|
||||
delete tempRule[key]
|
||||
}
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
function arrayMapping(from, to, rule, path) {
|
||||
if (from.length < to.length) {
|
||||
if (to.size) {
|
||||
//obaa extend method
|
||||
to.size(from.length)
|
||||
} else {
|
||||
to.length = from.length
|
||||
}
|
||||
}
|
||||
|
||||
from.forEach(function(item, index) {
|
||||
//push method can trigger obaa callback
|
||||
if (index > to.length - 1) {
|
||||
if (isArray(item)) {
|
||||
to.push(arrayMapping(item, to[index], rule, path + '[' + index + ']'))
|
||||
} else if (isObject(item)) {
|
||||
to.push(objMapping(item, to[index], rule, path + '[' + index + ']'))
|
||||
} else {
|
||||
to.push(item)
|
||||
}
|
||||
} else {
|
||||
if (isArray(item)) {
|
||||
to[index] = to[index] || []
|
||||
arrayMapping(item, to[index], rule, path + '[' + index + ']')
|
||||
} else if (isObject(item)) {
|
||||
to[index] = objMapping(item, to[index], rule, path + '[' + index + ']')
|
||||
} else {
|
||||
to[index] = item
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
rule &&
|
||||
Object.keys(rule).forEach(function(key) {
|
||||
var arr = key
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
var pathArr = path
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
|
||||
var dl = arr.length - pathArr.length
|
||||
if (dl === 1 && equalArr(arr, pathArr)) {
|
||||
to[arr[arr.length - 1]] = rule[key].call
|
||||
? rule[key].call(from)
|
||||
: rule[key]
|
||||
delete rule[key]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function objMapping(from, to, rule, path) {
|
||||
var res = to || {}
|
||||
Object.keys(from).forEach(function(key) {
|
||||
var obj = from[key]
|
||||
if (isArray(obj)) {
|
||||
res[key] = res[key] || []
|
||||
arrayMapping(obj, res[key], rule, path + '.' + key)
|
||||
} else if (isObject(obj)) {
|
||||
res[key] = res[key] || {}
|
||||
objMapping(obj, res[key], rule, path + '.' + key)
|
||||
} else {
|
||||
res[key] = obj
|
||||
}
|
||||
})
|
||||
|
||||
rule &&
|
||||
Object.keys(rule).forEach(function(key) {
|
||||
var arr = key
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
var pathArr = path
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
|
||||
if (arr.length - pathArr.length === 1 && equalArr(arr, pathArr)) {
|
||||
res[arr[arr.length - 1]] = rule[key].call
|
||||
? rule[key].call(from)
|
||||
: rule[key]
|
||||
if (arr.indexOf('*') === -1) {
|
||||
delete rule[key]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
function equalArr(arrA, arrB) {
|
||||
var i = 0,
|
||||
len = arrB.length
|
||||
for (; i < len; i++) {
|
||||
if (arrA[i] !== arrB[i] && !(arrA[i] === '*' && !isNaN(Number(arrB[i])))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function isArray(obj) {
|
||||
return Object.prototype.toString.call(obj) === ARRAYTYPE
|
||||
}
|
||||
|
||||
function isObject(obj) {
|
||||
return Object.prototype.toString.call(obj) === OBJECTTYPE
|
||||
}
|
||||
|
||||
//Compatible with older versions
|
||||
mapping.auto = mapping
|
||||
|
||||
export default mapping
|
|
@ -0,0 +1,144 @@
|
|||
/**
|
||||
* mappingjs v2.0.0 by dntzhang
|
||||
* Objects mapping for javascript. Omi MVVM's best partner.
|
||||
* @method mapping
|
||||
* @param {from} options
|
||||
* @param {to} options
|
||||
* @param {rule} options
|
||||
* @return {Object} To Object
|
||||
*/
|
||||
|
||||
var ARRAYTYPE = '[object Array]'
|
||||
var OBJECTTYPE = '[object Object]'
|
||||
|
||||
function mapping(from, to, rule) {
|
||||
var tempRule = Object.assign({}, rule)
|
||||
var res = to || {}
|
||||
Object.keys(from).forEach(function (key) {
|
||||
var obj = from[key]
|
||||
if (isArray(obj)) {
|
||||
res[key] = res[key] || []
|
||||
arrayMapping(obj, res[key], tempRule, key)
|
||||
} else if (isObject(obj)) {
|
||||
res[key] = res[key] || {}
|
||||
objMapping(obj, res[key], tempRule, key)
|
||||
} else {
|
||||
res[key] = obj
|
||||
}
|
||||
})
|
||||
|
||||
rule && Object.keys(tempRule).forEach(function (key) {
|
||||
var arr = key
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
|
||||
if (arr.length === 1) {
|
||||
res[key] = tempRule[key].call ? tempRule[key].call(from) : tempRule[key]
|
||||
delete tempRule[key]
|
||||
}
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
|
||||
function arrayMapping(from, to, rule, path) {
|
||||
if (from.length < to.length) {
|
||||
to.length = from.length
|
||||
}
|
||||
from.forEach(function (item, index) {
|
||||
if (isArray(item)) {
|
||||
to[index] = to[index] || []
|
||||
arrayMapping(item, to[index], rule, path + '[' + index + ']')
|
||||
} else if (isObject(item)) {
|
||||
to[index] = objMapping(item, to[index], rule, path + '[' + index + ']')
|
||||
} else {
|
||||
to[index] = item
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
rule && Object.keys(rule).forEach(function (key) {
|
||||
var arr = key
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
var pathArr = path
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
|
||||
var dl = arr.length - pathArr.length
|
||||
if (dl === 1 && equalArr(arr, pathArr)) {
|
||||
to[arr[arr.length - 1]] = rule[key].call ? rule[key].call(from) : rule[key]
|
||||
delete rule[key]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function objMapping(from, to, rule, path) {
|
||||
var res = to || {}
|
||||
Object.keys(from).forEach(function (key) {
|
||||
var obj = from[key]
|
||||
if (isArray(obj)) {
|
||||
res[key] = res[key] || []
|
||||
arrayMapping(obj, res[key], rule, path + '.' + key)
|
||||
} else if (isObject(obj)) {
|
||||
res[key] = res[key] || {}
|
||||
objMapping(obj, res[key], rule, path + '.' + key)
|
||||
} else {
|
||||
res[key] = obj
|
||||
}
|
||||
})
|
||||
|
||||
rule && Object.keys(rule).forEach(function (key) {
|
||||
var arr = key
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
var pathArr = path
|
||||
.replace(/]/g, '')
|
||||
.replace(/\[/g, '.')
|
||||
.split('.')
|
||||
|
||||
if (arr.length - pathArr.length === 1 && equalArr(arr, pathArr)) {
|
||||
res[arr[arr.length - 1]] = rule[key].call ? rule[key].call(from) : rule[key]
|
||||
if (arr.indexOf('*') === -1) {
|
||||
delete rule[key]
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
function equalArr(arrA, arrB) {
|
||||
var i = 0, len = arrB.length
|
||||
for (; i < len; i++) {
|
||||
if (arrA[i] !== arrB[i] && !(arrA[i] === '*' && !isNaN(Number(arrB[i])))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function isArray(obj) {
|
||||
return Object.prototype.toString.call(obj) === ARRAYTYPE
|
||||
}
|
||||
|
||||
function isObject(obj) {
|
||||
return Object.prototype.toString.call(obj) === OBJECTTYPE
|
||||
}
|
||||
|
||||
//Compatible with older versions
|
||||
mapping.auto = mapping
|
||||
|
||||
if (typeof exports == "object") {
|
||||
module.exports = mapping
|
||||
} else if (typeof define == "function" && define.amd) {
|
||||
define([], function () { return mapping })
|
||||
} else {
|
||||
window.mapping = mapping
|
||||
}
|
|
@ -153,13 +153,13 @@ input.weui-btn_plain-default{
|
|||
color:rgba(0, 0, 0, 0.2);
|
||||
border-color:rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
button.weui-btn,{
|
||||
button.weui-btn{
|
||||
width:100%;
|
||||
border-width:0;
|
||||
outline:0;
|
||||
-webkit-appearance:none;
|
||||
}
|
||||
button.weui-btn:focus,{
|
||||
button.weui-btn:focus{
|
||||
outline:0;
|
||||
}
|
||||
button.weui-btn_inline,
|
||||
|
|
Loading…
Reference in New Issue