Skip to content

Commit

Permalink
拆分打包 background-content-page (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
riophae authored and LitoMore committed Aug 26, 2019
1 parent c54027d commit a390c8e
Show file tree
Hide file tree
Showing 87 changed files with 110 additions and 135 deletions.
1 change: 1 addition & 0 deletions .babelrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ module.exports = {
'@babel/plugin-proposal-do-expressions',
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-proposal-function-bind',
'macros',
],

env: {
Expand Down
2 changes: 1 addition & 1 deletion build/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ const generateFileLoaderForImages = ({ publicPath }) => ({
// 大部分文件不应进行编码,因为可能降低页面加载性能
const generateUrlLoaderForImages = () => ({
test: input => reImageExt.test(input) && reBase64.test(input),
use: [ {
use: [ 'cache-loader', {
loader: 'url-loader',
options: {
limit: 2048,
Expand Down
5 changes: 4 additions & 1 deletion build/webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
module.exports = [
require('./webpack.js.config'),
require('./webpack.js.config')('background', 'background-content-page'),
require('./webpack.js.config')('content', 'background-content-page'),
require('./webpack.js.config')('page', 'background-content-page'),
require('./webpack.js.config')('settings', 'settings'),
require('./webpack.css.config'),
]
2 changes: 1 addition & 1 deletion build/webpack.css.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const {
generateUrlLoaderForImages,
} = require('./shared')

module.exports = (env, { mode } = defaultArgv) => ({
module.exports = (_, { mode } = defaultArgv) => ({
name: 'css',

entry: {
Expand Down
28 changes: 24 additions & 4 deletions build/webpack.js.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,11 @@ const {
generateFileLoaderForOtherAssets,
} = require('./shared')

module.exports = (env, { mode } = defaultArgv) => ({
module.exports = (id, entryFile) => (_, { mode } = defaultArgv) => ({
name: 'js',

entry: {
'background-content-page': approot('src/entries/background-content-page.js'),
'settings': approot('src/entries/settings.js'),
[id]: approot(`src/entries/${entryFile}.js`),
},

output: {
Expand All @@ -28,7 +27,28 @@ module.exports = (env, { mode } = defaultArgv) => ({

module: {
rules: [
{ test: /\.js$/, use: [ 'cache-loader', 'babel-loader' ] },
{
test: /\.js$/,
use: [
{
loader: 'cache-loader',
options: {
cacheIdentifier: require('cache-loader/package').version + mode + id,
},
},
'babel-loader',
{
loader: 'ifdef-loader',
options: {
DEVELOPMENT: mode === 'development',
PRODUCTION: mode === 'production',
ENV_BACKGROUND: id === 'background',
ENV_CONTENT: id === 'content',
ENV_PAGE: id === 'page',
},
},
],
},
generateStyleLoader({ mode }),
generateUrlLoaderForImages(),
generateFileLoaderForImages({ publicPath: `${EXTENSION_ORIGIN_PLACEHOLDER}/` }),
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"babel-eslint": "^10.0.1",
"babel-jest": "^24.7.1",
"babel-loader": "^8.0.4",
"babel-plugin-macros": "^2.6.1",
"cache-loader": "^4.0.0",
"chalk": "^2.4.2",
"copy-webpack-plugin": "^5.0.2",
Expand All @@ -99,6 +100,8 @@
"eslint-plugin-react": "^7.12.4",
"esm": "^3.2.22",
"file-loader": "^4.0.0",
"ifdef-loader": "^2.1.4",
"import-all.macro": "^2.0.3",
"jest": "^24.7.1",
"jest-webpack-resolver": "^0.3.0",
"less": "^3.9.0",
Expand Down
4 changes: 0 additions & 4 deletions src/background/feature/createFeatureClass.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ export default ({ messaging, bridge, settings, modules }) => class Feature {
}

async init() {
if (!this.subfeatures.length) {
return
}

await this.loadOptionValues()
await this.migrate()

Expand Down
6 changes: 0 additions & 6 deletions src/constants/envs.js

This file was deleted.

2 changes: 1 addition & 1 deletion src/constants/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ function loadConstants() {
}, {})
}

Object.assign(exports, loadConstants())
module.exports = Object.assign(exports, loadConstants())
2 changes: 1 addition & 1 deletion src/content/environment/injectScript.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import loadAsset, { appendToRoot } from '@libs/loadAsset'

export default () => {
const URL_INJECTED_JS = chrome.runtime.getURL('background-content-page.js')
const URL_INJECTED_JS = chrome.runtime.getURL('page.js')

// 保证先于饭否的脚本执行
loadAsset({ type: 'script', url: URL_INJECTED_JS, mount: appendToRoot })
Expand Down
2 changes: 1 addition & 1 deletion src/content/feature/createSubfeatureClass.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import every from '@libs/promiseEvery'
import log from '@libs/log'

export default ({ messaging, bridge, modules }) => class Subfeature {
constructor({ featureName, subfeatureName, script, style, parent }) {
constructor({ featureName, subfeatureName, style, script, parent }) {
this.featureName = featureName
this.subfeatureName = subfeatureName
this.parent = parent
Expand Down
42 changes: 20 additions & 22 deletions src/entries/background-content-page.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,41 @@
import features from '@features'
import safelyInvokeFn from '@libs/safelyInvokeFn'
import detectEnv from '@libs/detectEnv'
import { ENV_BACKGROUND, ENV_CONTENT, ENV_PAGE } from '@constants'

async function init({ createEnvironment, modules, createFeatureClass, createSubfeatureClass }) {
const environment = await createEnvironment()
const Feature = createFeatureClass({ ...environment, modules })
const Subfeature = createSubfeatureClass({ ...environment, modules })

for (const [ featureName, { metadata, subfeatures } ] of Object.entries(features)) {
if (!subfeatures) continue

const feature = new Feature({
featureName,
metadata,
})

for (const [ subfeatureName, { envType, loadScript, loadStyle } ] of Object.entries(subfeatures)) {
if (envType === detectEnv()) {
const subfeature = new Subfeature({
featureName,
subfeatureName,
script: loadScript ? loadScript() : null,
style: loadStyle ? loadStyle() : null,
parent: feature,
})
for (const [ subfeatureName, { style, script } ] of Object.entries(subfeatures)) {
const subfeature = new Subfeature({
featureName,
subfeatureName,
/// #if ENV_CONTENT || ENV_PAGE
style,
/// #endif
script,
parent: feature,
})

feature.addSubfeature(subfeature)
}
feature.addSubfeature(subfeature)
}

safelyInvokeFn(::feature.init)
}
}

function bootstrap() {
switch (detectEnv()) {
case ENV_BACKGROUND: return init(require('@background'))
case ENV_CONTENT: return init(require('@content'))
case ENV_PAGE: return init(require('@page'))
default:
}
}
bootstrap()
/// #if ENV_BACKGROUND
init(require('@background'))
/// #elif ENV_CONTENT
init(require('@content'))
/// #elif ENV_PAGE
init(require('@page'))
/// #endif
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
96 changes: 36 additions & 60 deletions src/features/index.js
Original file line number Diff line number Diff line change
@@ -1,73 +1,54 @@
import importAll from 'import-all.macro'
import dotProp from 'dot-prop'
import pick from 'just-pick'
import casey from 'casey-js'
import parseFilename from '@libs/parseFilename'
import replaceExtensionOrigin from '@libs/replaceExtensionOrigin'

const componentPathRe = do {
const beginning = String.raw`^\.`
const ending = '$'
const slash = String.raw`/`
function loadComponent(path, module) {
const [ , featureName, filename ] = path.split('/')

const metadata = '(?<isMetadata>metadata)'
const script = '(?<isScript>script)'
const style = '(?<isStyle>style)'

const featureName = '(?<featureName>[a-z-]+)'
const subfeatureName = String.raw`\[(?<subfeatureName>[a-z-]+)\]`

const envType = String.raw`\((?<envType>background|content|page)\)`
const extName = String.raw`\.(js|css|less)`

const or = (...branches) => `(?:${branches.join('|')})`
const optional = x => `(?:${x})?`

new RegExp([
beginning + slash + featureName + slash,
or(
metadata,
or(script, style) + envType + optional(subfeatureName),
),
extName + ending,
].join(''))
}

function loadComponent(key, loadModule) {
const result = (key.match(componentPathRe) || {}).groups
const { featureName, subfeatureName = 'default', envType } = result || {}

if (!result) throw new Error(`非法路径:${key}`)

if (result.isMetadata) return {
if (filename === 'metadata.js') return {
featureName,
type: 'metadata',
loadModule,
module,
}

if (result.isScript) return {
const { basename, extname } = parseFilename(filename)
const atPos = basename.lastIndexOf('@')
const subfeatureName = atPos === 0
? 'default'
: basename.substring(0, atPos)

if ([ '.less', '.css' ].includes(extname)) return {
featureName,
subfeatureName,
type: 'script',
envType,
loadModule: () => loadModule().default,
type: 'style',
module: replaceExtensionOrigin(module),
}

if (result.isStyle) return {
if (extname === '.js') return {
featureName,
subfeatureName,
type: 'style',
envType,
loadModule: () => replaceExtensionOrigin(loadModule()),
type: 'script',
module: module.default,
}
}

function loadComponents() {
const context = require.context(
'./',
true,
// webpack 要求这里的正则表达式必须使用字面量
/\/(metadata\.js|(script|style)\((background|content|page)\)(\[.+\])?\.(js|css|less))$/,
)
const components = context.keys().map(key => loadComponent(key, () => context(key)))
const modules = {
...importAll.sync('./*/metadata.js'),
/// #if ENV_BACKGROUND
...importAll.sync('./*/*@background.js'),
/// #elif ENV_CONTENT
...importAll.sync('./*/*@content.{less,css}'),
...importAll.sync('./*/*@content.js'),
/// #elif ENV_PAGE
...importAll.sync('./*/*@page.{less,css}'),
...importAll.sync('./*/*@page.js'),
/// #endif
}
const components = Object.entries(modules)
.map(([ path, module ]) => loadComponent(path, module))

return components
}
Expand Down Expand Up @@ -132,23 +113,18 @@ function processMetadata(featureName, metadata) {
function loadFeatures() {
const features = {}

for (const { featureName, subfeatureName, type, envType, loadModule } of loadComponents()) {
for (const { featureName, subfeatureName, type, module } of loadComponents()) {
if (type === 'metadata') {
dotProp.set(
features,
`${featureName}.metadata`,
processMetadata(featureName, loadModule()),
processMetadata(featureName, module),
)
} else {
dotProp.set(
features,
`${featureName}.subfeatures.${subfeatureName}.envType`,
envType,
)
dotProp.set(
features,
`${featureName}.subfeatures.${subfeatureName}.${casey.toCamelCase(`load-${type}`)}`,
loadModule,
`${featureName}.subfeatures.${subfeatureName}.${type}`,
module,
)
}
}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default context => {
textarea: { selector: '#phupdate textarea' },
})

function backupEvents() {
function backupEventListeners() {
const { Event } = window.YAHOO.util
let formSubmit, textareaKeyup

Expand All @@ -39,7 +39,7 @@ export default context => {
})
}

function restoreEvents() {
function restoreEventListeners() {
const { Event } = window.YAHOO.util

Event.addListener(elementCollection.get('form'), 'submit', eventsBackup.formSubmit)
Expand All @@ -57,11 +57,11 @@ export default context => {
waitReady: () => requireFanfouLib('YAHOO'),

onLoad() {
backupEvents()
backupEventListeners()
},

onUnload() {
restoreEvents()
restoreEventListeners()
},
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
15 changes: 0 additions & 15 deletions src/libs/detectEnv.js

This file was deleted.

Loading

0 comments on commit a390c8e

Please sign in to comment.