Skip to content

Commit

Permalink
feat(mini-runner): 保证快应用文件生成正确
Browse files Browse the repository at this point in the history
  • Loading branch information
luckyadam committed Jan 7, 2020
1 parent 5e33381 commit 0b2e882
Show file tree
Hide file tree
Showing 10 changed files with 275 additions and 98 deletions.
85 changes: 84 additions & 1 deletion packages/taro-cli/src/mini/helper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import * as fs from 'fs-extra'
import * as path from 'path'
import { execSync } from 'child_process'

import chalk from 'chalk'
import * as _ from 'lodash'
import * as ora from 'ora'
import { Config } from '@tarojs/taro'
import { IProjectConfig, ITaroManifestConfig } from '@tarojs/taro/types/compile'
import wxTransformer from '@tarojs/transformer-wx'
Expand Down Expand Up @@ -32,8 +35,12 @@ import {
recursiveFindNodeModules,
getBabelConfig,
extnameExpRegOf,
generateAlipayPath
generateAlipayPath,
unzip,
shouldUseYarn,
shouldUseCnpm
} from '../util'
import { downloadGithubRepoLatestRelease } from '../util/dowload'
import { resolveNpmPkgMainPath } from '../util/resolve_npm_files'
import { resolveNpmSync } from '../util/npm'

Expand Down Expand Up @@ -393,3 +400,79 @@ export function getImportTaroSelfComponents (filePath, taroSelfComponents) {
})
return importTaroSelfComponents
}

export async function prepareQuickAppEnvironment (buildData: IBuildData) {
let isReady = false
let needDownload = false
let needInstall = false
const originalOutputDir = buildData.originalOutputDir
console.log()
if (fs.existsSync(path.join(buildData.originalOutputDir, 'sign'))) {
needDownload = false
} else {
needDownload = true
}
if (needDownload) {
const getSpinner = ora('开始下载快应用运行容器...').start()
await downloadGithubRepoLatestRelease('NervJS/quickapp-container', buildData.appPath, originalOutputDir)
await unzip(path.join(originalOutputDir, 'download_temp.zip'))
getSpinner.succeed('快应用运行容器下载完成')
} else {
console.log(`${chalk.green('✔ ')} 快应用容器已经准备好`)
}
process.chdir(originalOutputDir)
console.log()
if (fs.existsSync(path.join(originalOutputDir, 'node_modules'))) {
needInstall = false
} else {
needInstall = true
}
if (needInstall) {
let command
if (shouldUseYarn()) {
command = 'NODE_ENV=development yarn install'
} else if (shouldUseCnpm()) {
command = 'NODE_ENV=development cnpm install'
} else {
command = 'NODE_ENV=development npm install'
}
const installSpinner = ora(`安装快应用依赖环境, 需要一会儿...`).start()
try {
const stdout = execSync(command)
installSpinner.color = 'green'
installSpinner.succeed('安装成功')
console.log(`${stdout}`)
isReady = true
} catch (error) {
installSpinner.color = 'red'
installSpinner.fail(chalk.red(`快应用依赖环境安装失败,请进入 ${path.basename(originalOutputDir)} 重新安装!`))
console.log(`${error}`)
isReady = false
}
} else {
console.log(`${chalk.green('✔ ')} 快应用依赖已经安装好`)
isReady = true
}
return isReady
}

export async function runQuickApp (isWatch: boolean | void, buildData: IBuildData, port?: number, release?: boolean) {
const originalOutputDir = buildData.originalOutputDir
const { compile } = require(require.resolve('hap-toolkit/lib/commands/compile', { paths: [originalOutputDir] }))
if (isWatch) {
const { launchServer } = require(require.resolve('@hap-toolkit/server', { paths: [originalOutputDir] }))
launchServer({
port: port || 12306,
watch: isWatch,
clearRecords: false,
disableADB: false
})
compile('native', 'dev', true)
} else {
if (!release) {
compile('native', 'dev', false)
} else {
compile('native', 'prod', false)
}
}
}
4 changes: 3 additions & 1 deletion packages/taro-mini-runner/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"ora": "^3.4.0",
"postcss-loader": "^3.0.0",
"postcss-pxtransform": "^1.3.2",
"request": "^2.88.0",
"resolve": "^1.11.1",
"sass-loader": "^7.1.0",
"stylus-loader": "^3.0.2",
Expand All @@ -64,7 +65,8 @@
"virtual-module-webpack-plugin": "^0.4.1",
"webpack": "^4.31.0",
"webpack-chain": "^6.0.0",
"webpack-format-messages": "^2.0.5"
"webpack-format-messages": "^2.0.5",
"yauzl": "2.10.0"
},
"devDependencies": {
"@types/babel-core": "^6.25.6",
Expand Down
14 changes: 9 additions & 5 deletions packages/taro-mini-runner/src/loaders/fileParseLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,8 @@ function processAst (
template(`import Taro from '${taroMiniAppFramework}'`, babylonConfig as any)() as any
)
}
node.body.push(template(`export default require('${taroMiniAppFramework}').default.createApp(${exportVariableName})`, babylonConfig as any)() as any)
node.body.push(template(`exportRes = require('${taroMiniAppFramework}').default.createApp(${exportVariableName})`, babylonConfig as any)() as any)
node.body.push(template(`export default exportRes`, babylonConfig as any)() as any)
} else {
node.body.push(template(`App(require('${taroMiniAppFramework}').default.createApp(${exportVariableName}))`, babylonConfig as any)() as any)
}
Expand All @@ -451,7 +452,8 @@ function processAst (
template(`import Taro from '${taroMiniAppFramework}'`, babylonConfig as any)() as any
)
}
node.body.push(template(`export default require('${taroMiniAppFramework}').default.createComponent(${exportVariableName}, '${pagePath}')`, babylonConfig as any)() as any)
node.body.push(template(`exportRes = require('${taroMiniAppFramework}').default.createComponent(${exportVariableName}, '${pagePath}')`, babylonConfig as any)() as any)
node.body.push(template(`export default exportRes`, babylonConfig as any)() as any)
} else {
node.body.push(template(`Page(require('${taroMiniAppFramework}').default.createComponent(${exportVariableName}, true))`, babylonConfig as any)() as any)
}
Expand All @@ -463,7 +465,8 @@ function processAst (
template(`import Taro from '${taroMiniAppFramework}'`, babylonConfig as any)() as any
)
}
node.body.push(template(`export default require('${taroMiniAppFramework}').default.createComponent(${exportVariableName})`, babylonConfig as any)() as any)
node.body.push(template(`exportRes = require('${taroMiniAppFramework}').default.createComponent(${exportVariableName})`, babylonConfig as any)() as any)
node.body.push(template(`export default exportRes`, babylonConfig as any)() as any)
} else {
node.body.push(template(`Component(require('${taroMiniAppFramework}').default.createComponent(${exportVariableName}))`, babylonConfig as any)() as any)
}
Expand All @@ -484,7 +487,8 @@ export default function fileParseLoader (source, ast) {
constantsReplaceList,
buildAdapter,
designWidth,
deviceRatio
deviceRatio,
sourceDir
} = getOptions(this)
const filePath = this.resourcePath
const newAst = transformFromAst(ast, '', {
Expand All @@ -494,7 +498,7 @@ export default function fileParseLoader (source, ast) {
]
}).ast as t.File
const miniType = this._module.miniType || PARSE_AST_TYPE.NORMAL
const result = processAst(newAst, buildAdapter, miniType, designWidth, deviceRatio, filePath, this.context)
const result = processAst(newAst, buildAdapter, miniType, designWidth, deviceRatio, filePath, sourceDir)
const code = generate(result).code
const res = transform(code, babelConfig)
return res.code
Expand Down
75 changes: 55 additions & 20 deletions packages/taro-mini-runner/src/plugins/MiniPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ import * as LoaderTargetPlugin from 'webpack/lib/LoaderTargetPlugin'
import { merge, defaults, kebabCase } from 'lodash'
import * as t from 'babel-types'
import traverse from 'babel-traverse'
import { Config as IConfig } from '@tarojs/taro'
import { Config as IConfig, PageConfig } from '@tarojs/taro'
import * as _ from 'lodash'

import { REG_TYPESCRIPT, BUILD_TYPES, PARSE_AST_TYPE, MINI_APP_FILES, NODE_MODULES_REG, CONFIG_MAP, taroJsFramework, taroJsComponents, QUICKAPP_SPECIAL_COMPONENTS, taroJsQuickAppComponents } from '../utils/constants'
import { REG_TYPESCRIPT, BUILD_TYPES, PARSE_AST_TYPE, MINI_APP_FILES, NODE_MODULES_REG, CONFIG_MAP, taroJsFramework } from '../utils/constants'
import { IComponentObj } from '../utils/types'
import { resolveScriptPath, buildUsingComponents, isNpmPkg, resolveNpmSync, isEmptyObject, promoteRelativePath } from '../utils'
import TaroSingleEntryDependency from '../dependencies/TaroSingleEntryDependency'
import { getTaroJsQuickAppComponentsPath, generateQuickAppUx, getImportTaroSelfComponents } from '../utils/helper'
import { getTaroJsQuickAppComponentsPath, generateQuickAppUx, getImportTaroSelfComponents, generateQuickAppManifest } from '../utils/helper'
import parseAst from '../utils/parseAst'

import TaroLoadChunksPlugin from './TaroLoadChunksPlugin'
Expand All @@ -32,6 +32,8 @@ interface IMiniPluginOptions {
nodeModulesPath: string,
sourceDir: string,
outputDir: string,
quickappJSON?: any,
designWidth: number,
commonChunks: string[]
}

Expand Down Expand Up @@ -60,7 +62,7 @@ export const createTarget = function createTarget (name) {
new JsonpTemplatePlugin().apply(compiler)
new FunctionModulePlugin(options.output).apply(compiler)
new NodeSourcePlugin(options.node).apply(compiler)
new LoaderTargetPlugin('web').apply(compiler)
new LoaderTargetPlugin('node').apply(compiler)
}
}

Expand Down Expand Up @@ -133,20 +135,23 @@ export default class MiniPlugin {
outputDir: string
context: string
appConfig: IConfig
pageConfigs: Map<string, PageConfig>

constructor (options = {}) {
this.options = defaults(options || {}, {
buildAdapter: BUILD_TYPES.WEAPP,
nodeModulesPath: '',
sourceDir: '',
outputDir: '',
designWidth: 750,
commonChunks: ['runtime', 'vendors']
})
this.sourceDir = this.options.sourceDir
this.outputDir = this.options.outputDir

this.pages = new Set()
this.components = new Set()
this.pageConfigs = new Map()
}

tryAsync = fn => async (arg, callback) => {
Expand Down Expand Up @@ -189,7 +194,7 @@ export default class MiniPlugin {

new TaroLoadChunksPlugin({
commonChunks: this.options.commonChunks,
taroFileTypeMap
buildAdapter: this.options.buildAdapter
}).apply(compiler)

new TaroNormalModulesPlugin().apply(compiler)
Expand Down Expand Up @@ -374,10 +379,11 @@ export default class MiniPlugin {
}
this.getSubPackages(configObj)
this.generateTabBarFiles(compiler, configObj)
const template = ''
taroFileTypeMap[this.appEntry] = {
type: PARSE_AST_TYPE.ENTRY,
config: configObj,
template: transformResult.template,
template,
code: transformResult.code
}
this.pages = new Set([
Expand All @@ -403,7 +409,7 @@ export default class MiniPlugin {
componentName = componentPath.replace(this.sourceDir, '').replace(/\\/g, '/').replace(path.extname(componentPath), '')
}

return componentName
return componentName.replace(/^(\/|\\)/, '')
}

getComponents (fileList: Set<IComponent>, isRoot: boolean) {
Expand Down Expand Up @@ -465,6 +471,10 @@ export default class MiniPlugin {
})
let parseAstRes = parseAst(transformResult.ast, buildAdapter)
configObj = parseAstRes.configObj
if (isRoot) {
const showPath = file.path.replace(this.sourceDir, '').replace(path.extname(file.path), '')
this.pageConfigs.set(showPath, configObj)
}
taroSelfComponents = parseAstRes.taroSelfComponents
const usingComponents = configObj.usingComponents
if (usingComponents) {
Expand All @@ -487,11 +497,7 @@ export default class MiniPlugin {
if (isQuickApp) {
const scriptPath = file.path
const outputScriptPath = scriptPath.replace(this.sourceDir, this.outputDir).replace(path.extname(scriptPath), MINI_APP_FILES[buildAdapter].SCRIPT)
const stylePath = outputScriptPath.replace(path.extname(outputScriptPath), MINI_APP_FILES[buildAdapter].STYLE)
const templPath = outputScriptPath.replace(path.extname(outputScriptPath), MINI_APP_FILES[buildAdapter].TEMPL)
const styleRelativePath = promoteRelativePath(path.relative(outputScriptPath, stylePath))
const scriptRelativePath = promoteRelativePath(path.relative(templPath, outputScriptPath))
const importTaroSelfComponents = getImportTaroSelfComponents(outputScriptPath, this.options.nodeModulesPath, taroSelfComponents)
const importTaroSelfComponents = getImportTaroSelfComponents(outputScriptPath, this.options.nodeModulesPath, this.outputDir, taroSelfComponents)
const usingComponents = configObj.usingComponents
let importUsingComponent: any = new Set([])
if (usingComponents) {
Expand All @@ -510,8 +516,6 @@ export default class MiniPlugin {
}))
template = generateQuickAppUx({
template,
script: scriptRelativePath,
style: styleRelativePath,
imports: new Set([...importTaroSelfComponents, ...importUsingComponent, ...importCustomComponents])
})
}
Expand Down Expand Up @@ -586,19 +590,50 @@ export default class MiniPlugin {
const extname = path.extname(item)
const templatePath = relativePath.replace(extname, MINI_APP_FILES[buildAdapter].TEMPL)
const jsonPath = relativePath.replace(extname, MINI_APP_FILES[buildAdapter].CONFIG)
const scriptPath = relativePath.replace(extname, MINI_APP_FILES[buildAdapter].SCRIPT)
const stylePath = relativePath.replace(extname, MINI_APP_FILES[buildAdapter].STYLE)
const itemInfo = taroFileTypeMap[item]
if (itemInfo.type !== PARSE_AST_TYPE.ENTRY) {
compilation.assets[templatePath] = {
size: () => itemInfo.template!.length,
source: () => itemInfo.template
}
}
let template = itemInfo.template
if (!isQuickApp) {
const jsonStr = JSON.stringify(itemInfo.config)
compilation.assets[jsonPath] = {
size: () => jsonStr.length,
source: () => jsonStr
}
} else {
let hitScriptItem
Object.keys(compilation.assets).forEach(item => {
if (stylePath.indexOf(item) >= 0) {
const relativeStylePath = promoteRelativePath(path.relative(scriptPath, stylePath))
template = `<style src='${relativeStylePath}'></style>\n` + template
}
if (scriptPath.indexOf(item) >= 0) {
let scriptContent = compilation.assets[item]._source.source()
scriptContent = `let exportRes;\n${scriptContent}\nexport default exportRes;`
hitScriptItem = item
template += `\n<script>${scriptContent}</script>`
}
})
if (hitScriptItem) {
delete compilation.assets[hitScriptItem]
}
const quickappJSON = generateQuickAppManifest({
appConfig: this.appConfig,
designWidth: this.options.designWidth,
pageConfigs: this.pageConfigs,
quickappJSON: this.options.quickappJSON
})
const quickappJSONStr = JSON.stringify(quickappJSON)
compilation.assets['./manifest.json'] = {
size: () => quickappJSONStr.length,
source: () => quickappJSONStr
}
}
if (template) {
compilation.assets[templatePath] = {
size: () => template!.length,
source: () => template
}
}
if (itemInfo.taroSelfComponents) {
itemInfo.taroSelfComponents.forEach(item => {
Expand Down
Loading

0 comments on commit 0b2e882

Please sign in to comment.