Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,22 @@
# megalo-entry
解析配置在 `main.js` 或者 `App.vue` 中的 [小程序全局配置](https://developers.weixin.qq.com/miniprogram/dev/framework/config.html#%E5%85%A8%E5%B1%80%E9%85%8D%E7%BD%AE)并生成webpack所需要的entry键值对

## 单独使用

``` bash
# npm i @megalo/entry -D
```

``` js
const entryPath = 'main.js或者App.vue文件路径'
const { pagesEntry, getSubPackagesRoot } = require('@megalo/entry')

pagesEntry(entryPath)
getSubPackagesRoot(entryPath)
```


参考例子: https://github.com/megalojs/megalo-cli/blob/882229133d7d92a9398c96620b9b7bc96dda74e0/packages/%40megalo/cli-plugin-mp/index.js#L255

## cli集成
`megalo-cli` 内部已经默认集成该库
24 changes: 12 additions & 12 deletions lib/extract-config.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
const babelon = require( 'babelon' )
const generate = require( 'babel-generator' ).default
const babelon = require('babelon')
const generate = require('babel-generator').default

module.exports = function ( { types: t } ) {
module.exports = function ({ types: t }) {
return {
visitor: {
ExportDefaultDeclaration( path ) {
path.node.declaration.properties.forEach( prop => {
ExportDefaultDeclaration (path) {
path.node.declaration.properties.forEach(prop => {
if (
t.isObjectProperty( prop ) &&
t.isIdentifier( prop.key, { name: 'config' } )
t.isObjectProperty(prop) &&
t.isIdentifier(prop.key, { name: 'config' })
) {
const code = generate( prop.value ).code
const code = generate(prop.value).code

path.hub.file.metadata.config = {
code: code,
node: prop.value,
value: babelon.eval( code )
value: babelon.eval(code)
}
}
} )
})

path.remove()
},
},
}
}
}
}
41 changes: 21 additions & 20 deletions lib/func/getSubPackagesRoot.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,27 @@
const { getAppObj } = require('../util')

// 获取指定目录下符合glob的所有文件
module.exports = function(file) {
let entries = {},
mainObj = {},
subpackages
module.exports = function (file) {
const entries = {}

try {
mainObj = getAppObj(file) || {}
subpackages = mainObj.subpackages || mainObj.subPackages || []
subpackages.forEach(sp=>{
let {root, pages} = sp
if(root && pages.length>0){
pages.forEach(p=>{
entries[`${root}/${p}`] = root
})
}
let mainObj = {}

let subpackages

try {
mainObj = getAppObj(file) || {}
subpackages = mainObj.subpackages || mainObj.subPackages || []
subpackages.forEach(sp => {
const { root, pages } = sp
if (root && pages.length > 0) {
pages.forEach(p => {
entries[`${root}/${p}`] = root
})

} catch (e) {
console.log(e)
}
}
})
} catch (e) {
console.log(e)
}

return entries
}
return entries
}
84 changes: 45 additions & 39 deletions lib/func/pagesEntry.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,55 @@
'use strict'
const path = require( 'path' )
const path = require('path')
const { getAppObj } = require('../util')
const fs = require('fs')

const matchPath = function (p) {
const files = [path.resolve(`src/${p}.js`),path.resolve(`src/${p}.vue`)]
// 获取指定目录下符合glob的所有文件
module.exports = function (file, whileList = []) {
const entries = {}
const srcDir = path.dirname(file)
const matchPath = function (p) {
const files = [path.resolve(srcDir, `${p}.js`), path.resolve(srcDir, `${p}.vue`)]
return fs.existsSync(files[0]) && files[0] || fs.existsSync(files[1]) && files[1]
}
}

// 获取指定目录下符合glob的所有文件
module.exports = function(file, whileList = []) {
let entries = {},
mainObj = {},
pages,
subpackages

try {
mainObj = getAppObj(file) || {}
pages = mainObj.pages || []
subpackages = mainObj.subpackages || mainObj.subPackages || []

pages.forEach(p=>{
// const _p = p.replace(/^pages(\/[^\/]*)(\/[^\/]*)?/,($0,$1,$2)=>{return `pages${$1}${$2||$1}`})
matchPath(p) && (entries[p] = matchPath(p))
})
subpackages.forEach(sp=>{
let {root, pages} = sp
if(root && pages.length>0){
pages.forEach(p=>{
// const _p = p.replace(/^pages(\/[^\/]*)(\/[^\/]*)?/,($0,$1,$2)=>{return `pages${$1}${$2||$1}`})
matchPath(`${root}/${p}`) && (entries[`${root}/${p}`] = matchPath(`${root}/${p}`))
})
}
let mainObj = {}

let pages

let subpackages

try {
mainObj = getAppObj(file) || {}
pages = mainObj.pages || []
subpackages = mainObj.subpackages || mainObj.subPackages || []

pages.forEach(p => {
if (p.startsWith('^')) {
p = p.replace(/^\^+/, '')
}
matchPath(p) && (entries[p] = matchPath(p))
})
subpackages.forEach(sp => {
const { root, pages } = sp
if (root && pages.length > 0) {
pages.forEach(p => {
if (p.startsWith('^')) {
p = p.replace(/^\^+/, '')
}
matchPath(`${root}/${p}`) && (entries[`${root}/${p}`] = matchPath(`${root}/${p}`))
})
}
})

// 白名单筛选
if(whileList.length > 0){
for(let p in entries){
whileList.indexOf(p) === -1 && (delete entries[p])
}
}

} catch (e) {
console.log(e)
// 白名单筛选
if (whileList.length > 0) {
for (const p in entries) {
whileList.indexOf(p) === -1 && (delete entries[p])
}
}
} catch (e) {
console.log(e)
}

return entries
}
return entries
}
10 changes: 5 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const pagesEntry = require( './func/pagesEntry' )
const getSubPackagesRoot = require( './func/getSubPackagesRoot' )
const pagesEntry = require('./func/pagesEntry')
const getSubPackagesRoot = require('./func/getSubPackagesRoot')

module.exports = {
pagesEntry,
getSubPackagesRoot
}
pagesEntry,
getSubPackagesRoot
}
63 changes: 63 additions & 0 deletions lib/parseConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const JSON5 = require('json5')
const yaml = require('js-yaml')
const toString = Object.prototype.toString

const handlers = {
json ({ source, filepath } = {}) {
return JSON5.parse(source)
},

yaml ({ source, filepath } = {}) {
return yaml.safeLoad(source, {
filename: filepath,
json: true
})
}
}

function parseConfig ({ source, lang, filepath } = {}, callback) {
const normalizeMap = {
json: 'json',
json5: 'json',
yaml: 'yaml',
yml: 'yaml'
}

const normalizedLang = normalizeMap[lang]

const handler = handlers[normalizedLang]

if (!handler) {
return callback(new Error(
'Invalid lang for config block: "' + lang + '", ' +
'consider using "json" or "yaml"'
))
}

let config

try {
config = handler({
source,
filepath
})

if (toString.call(config) !== '[object Object]') {
config = {}
}

if (typeof callback === 'function') {
callback(null, config)
} else {
return config
}
} catch (e) {
if (typeof callback === 'function') {
callback(e)
} else {
throw e
}
}
}

module.exports = parseConfig
33 changes: 21 additions & 12 deletions lib/util.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,41 @@
const fs = require('fs')
const path = require( 'path' )
const path = require('path')
const parseConfig = require('./parseConfig')

const extractConfigPlugin = require('./extract-config');
const babel = require('babel-core');
const extractConfigPlugin = require('./extract-config')
const babel = require('babel-core')

const babelOptions = {
plugins: [
extractConfigPlugin
]
}


function resolve (...args) {
return path.resolve( __dirname, '../', ...args)
return path.resolve(__dirname, '../', ...args)
}

function extractConfig (txt) {
const { metadata } = babel.transform(txt, babelOptions)
return metadata.config.value
}

function extractConfig(txt) {
const { metadata } = babel.transform( txt, babelOptions )
return metadata.config.value
function extractConfigFromSFC (txt, filepath = '') {
const block = txt.match(/<config\b[^>]*>([\s\S]*)<\/config>/)
if (!block) return {}
let lang = block[0].match(/<config .*?lang=\"(.+?)\"/)
lang = (lang && lang[1]) || 'json'
return parseConfig({ source: block[1], lang, filepath })
}

function getAppObj(file){
let txt = fs.readFileSync(file,'utf8')
return extractConfig(txt)
function getAppObj (file) {
const txt = fs.readFileSync(file, 'utf8')
return file.endsWith('.vue') ? extractConfigFromSFC(txt) : extractConfig(txt)
}

module.exports = {
resolve,
getAppObj,
extractConfig
extractConfig,
extractConfigFromSFC
}
18 changes: 12 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
{
"name": "@megalo/entry",
"version": "0.1.2",
"version": "0.1.5",
"description": "",
"main": "lib/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "node ./test"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/megalojs/megalo-entry.git"
"url": "git+https://github.com/megalojs/megalo-cli.git",
"directory": "packages/@megalo/entry"
},
"keywords": [
"megalo"
Expand All @@ -19,11 +23,13 @@
"author": "zwwill <https://github.com/zwwill>",
"license": "ISC",
"bugs": {
"url": "https://github.com/megalojs/megalo-entry/issues"
"url": "https://github.com/megalojs/megalo-cli/issues"
},
"homepage": "https://github.com/megalojs/megalo-entry#readme",
"dependencies": {
"babel-core": "^6.26.3",
"babelon": "^1.0.5"
"babel-generator": "^6.26.1",
"babelon": "^1.0.5",
"js-yaml": "^3.13.1",
"json5": "^2.1.0"
}
}