Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webpack 配置抽离成插件 #6574

Merged
merged 16 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from 15 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
3 changes: 2 additions & 1 deletion lerna.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"packages/taro-plugin-babel",
"packages/taro-plugin-csso",
"packages/taro-plugin-sass",
"packages/taro-plugin-uglifyjs",
"packages/taro-plugin-terser",
"packages/taro-plugin-uglify",
"packages/taro-plugin-typescript",
"packages/taro-plugin-less",
"packages/taro-plugin-stylus",
Expand Down
5 changes: 4 additions & 1 deletion packages/taro-cli/src/commands/customCommand.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Kernel } from '@tarojs/service'

import { getPkgVersion } from '../util'

export default function customCommand (
command: string,
kernel: Kernel,
Expand All @@ -18,7 +20,8 @@ export default function customCommand (
opts: {
_: args._,
options,
isHelp: args.h
isHelp: args.h,
cliVersion: getPkgVersion()
}
})
}
Expand Down
11 changes: 9 additions & 2 deletions packages/taro-cli/src/h5/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ import {
processTypeEnum,
PROJECT_CONFIG,
REG_SCRIPTS,
REG_TYPESCRIPT
REG_TYPESCRIPT,
createBabelRegister,
getModuleDefaultExport
} from '@tarojs/helper'
import {
convertAstExpressionToVariable as toVar,
Expand Down Expand Up @@ -93,9 +95,14 @@ class Compiler {
isUi: boolean

constructor (public appPath: string, entryFile?: string, isUi?: boolean) {
createBabelRegister({
only: [
filePath => filePath.indexOf(path.dirname(path.join(appPath, PROJECT_CONFIG))) >= 0
]
})
const projectConfig = recursiveMerge({
h5: defaultH5Config
}, require(resolveScriptPath(path.join(appPath, PROJECT_CONFIG)))(merge))
}, getModuleDefaultExport(require(resolveScriptPath(path.join(appPath, PROJECT_CONFIG))))(merge))
this.projectConfig = projectConfig
const sourceDir = projectConfig.sourceRoot || CONFIG.SOURCE_DIR
this.sourceRoot = sourceDir
Expand Down
65 changes: 65 additions & 0 deletions packages/taro-cli/src/presets/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default (ctx) => {
configPath,
projectConfig: ctx.initialConfig
})
await checkPlugin(ctx, isWatch)
if (checkResult.lines.length) {
const NOTE_VALID = chalk.yellow('[!] ')
const NOTE_INVALID = chalk.red('[✗] ')
Expand Down Expand Up @@ -127,3 +128,67 @@ async function checkConfig ({ projectConfig, configPath }) {
})
return result
}

function findFilesWithExt (dirname, ext) {
const glob = require('glob')
const pattern = Array.isArray(ext) ? `${dirname}/**/*{${ext.join(',')}}` : `${dirname}/**/*${ext}`
const files = glob.sync(pattern)
return files
}

const PLUGIN_SASS = '@tarojs/plugin-sass'
const PLUGIN_LESS = '@tarojs/plugin-less'
const PLUGIN_STYLUS = '@tarojs/plugin-stylus'
const PLUGIN_UGLIFY = '@tarojs/plugin-uglify'
const PLUGIN_TERSER = '@tarojs/plugin-terser'

const PLUGINS_CONFIG_DOC = 'https://nervjs.github.io/taro/docs/config-detail#plugins'

function hadAddPlugin (plugins, pluginName) {
let hadAdd = false
plugins.forEach(item => {
if (item.id === pluginName || item.name === pluginName) {
hadAdd = true
}
})
return hadAdd
}

async function checkPlugin (ctx, isWatch) {
const plugins = ctx.plugins
const sassFiles = findFilesWithExt(ctx.paths.sourcePath, ['.scss', '.sass'])
if (sassFiles.length && !hadAddPlugin(plugins, PLUGIN_SASS)) {
console.log()
console.log(ctx.helper.chalk.red(`当前项目使用了 sass,请安装插件 ${PLUGIN_SASS},并且在 plugins 中进行配置,否则将无法编译 sass 文件!`))
console.log(ctx.helper.chalk.red(`参考文档:${PLUGINS_CONFIG_DOC}`))
console.log()
process.exit(1)
}

const lessFiles = findFilesWithExt(ctx.paths.sourcePath, '.less')
if (lessFiles.length && !hadAddPlugin(plugins, PLUGIN_LESS)) {
console.log()
console.log(ctx.helper.chalk.red(`当前项目使用了 sass,请安装插件 ${PLUGIN_LESS},并且在 plugins 中进行配置,否则将无法编译 less 文件!`))
console.log(ctx.helper.chalk.red(`参考文档:${PLUGINS_CONFIG_DOC}`))
console.log()
process.exit(1)
}

const stylusFiles = findFilesWithExt(ctx.paths.sourcePath, '.styl')
if (stylusFiles.length && !hadAddPlugin(plugins, PLUGIN_STYLUS)) {
console.log()
console.log(ctx.helper.chalk.red(`当前项目使用了 sass,请安装插件 ${PLUGIN_STYLUS},并且在 plugins 中进行配置,否则将无法编译 stylus 文件!`))
console.log(ctx.helper.chalk.red(`参考文档:${PLUGINS_CONFIG_DOC}`))
console.log()
process.exit(1)
}

if (!isWatch) {
if (!hadAddPlugin(plugins, PLUGIN_UGLIFY) && !hadAddPlugin(plugins, PLUGIN_TERSER)) {
console.log()
console.log(ctx.helper.chalk.yellow(`检测到当前项目没有安装压缩插件 ${PLUGIN_UGLIFY} 或 ${PLUGIN_TERSER},打包时将无法压缩 JS 代码,请安装插件(安装其一即可),并且在 plugins 中进行配置!`))
console.log(ctx.helper.chalk.yellow(`参考文档:${PLUGINS_CONFIG_DOC}`))
console.log()
}
}
}
5 changes: 4 additions & 1 deletion packages/taro-cli/templates/default/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ const config = {
}]
]
},
plugins: [],
plugins: [<% if (css !== 'none') {%>
'@tarojs/plugin-<%= css %>',<%}%>
'@tarojs/plugin-terser'
],
defineConstants: {
},
mini: {
Expand Down
4 changes: 4 additions & 0 deletions packages/taro-cli/templates/default/pkg
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"build:h5": "taro build --type h5",
"build:rn": "taro build --type rn",
"build:qq": "taro build --type qq",
"build:jd": "taro build --type jd",
"build:quickapp": "taro build --type quickapp",
"dev:weapp": "npm run build:weapp -- --watch",
"dev:swan": "npm run build:swan -- --watch",
Expand All @@ -24,6 +25,7 @@
"dev:h5": "npm run build:h5 -- --watch",
"dev:rn": "npm run build:rn -- --watch",
"dev:qq": "npm run build:qq -- --watch",
"dev:jd": "npm run build:jd -- --watch",
"dev:quickapp": "npm run build:quickapp -- --watch"
},
"author": "",
Expand All @@ -50,6 +52,8 @@
"@types/react": "^16.4.6",
"@types/webpack-env": "^1.13.6",
"@tarojs/mini-runner": "<%= version %>",
"@tarojs/plugin-<%= css %>": "<%= version %>",<%}%>
"@tarojs/plugin-terser": "<%= version %>",
"@tarojs/webpack-runner": "<%= version %>",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
Expand Down
10 changes: 0 additions & 10 deletions packages/taro-mini-runner/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"homepage": "https://github.com/NervJS/taro#readme",
"dependencies": {
"@tarojs/helper": "^2.2.7",
"@tarojs/runner-utils": "^2.2.7",
"@tarojs/taro": "^2.2.7",
"@tarojs/transformer-wx": "^2.2.7",
"babel-core": "^6.26.3",
Expand All @@ -52,26 +51,17 @@
"csso-webpack-plugin": "^2.0.0-beta.1",
"file-loader": "^4.0.0",
"fs-extra": "^8.0.1",
"less": "^3.10.3",
"less-loader": "^5.0.0",
"loader-utils": "^1.2.3",
"lodash": "^4.17.11",
"mini-css-extract-plugin": "^0.7.0",
"node-sass": "^4.12.0",
"ora": "^3.4.0",
"postcss-import": "12.0.1",
"postcss-loader": "^3.0.0",
"postcss-pxtransform": "^2.2.7",
"postcss-url": "^8.0.0",
"request": "^2.88.0",
"resolve": "^2.0.0-next.0",
"sass-loader": "^7.1.0",
"sax": "^1.2.4",
"scss-bundle": "^2.5.1",
"stylus": "0.54.7",
"stylus-loader": "^3.0.2",
"tapable": "1.1.3",
"uglifyjs-webpack-plugin": "^2.2.0",
"url-loader": "^2.0.0",
"webpack": "4.41.6",
"webpack-chain": "4.9.0",
Expand Down
21 changes: 7 additions & 14 deletions packages/taro-mini-runner/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as webpack from 'webpack'
import { getSassLoaderOption } from '@tarojs/runner-utils'
import { PARSE_AST_TYPE } from '@tarojs/helper'

import { IBuildConfig, IOption } from './utils/types'
import { IBuildConfig } from './utils/types'
import { printBuildError, bindProdLogger, bindDevLogger } from './utils/logHelper'
import baseConf from './webpack/base.conf'
import buildConf from './webpack/build.conf'

const customizeChain = async (chain, modifyWebpackChainFunc: Function, customizeFunc?: Function) => {
Expand All @@ -15,24 +15,17 @@ const customizeChain = async (chain, modifyWebpackChainFunc: Function, customize
}
}

const makeConfig = async (buildConfig: IBuildConfig) => {
const sassLoaderOption: IOption = await getSassLoaderOption(buildConfig)
return {
...buildConfig,
sassLoaderOption
}
}

export default async function build (appPath: string, config: IBuildConfig) {
const mode = config.mode
const newConfig = await makeConfig(config)
const webpackChain = buildConf(appPath, mode, newConfig)
await customizeChain(webpackChain, newConfig.modifyWebpackChain, newConfig.webpackChain)
const baseWebpackChain = baseConf(appPath)
await customizeChain(baseWebpackChain, config.modifyWebpackChain, config.webpackChain)
const buildWebpackConf = buildConf(appPath, mode, config, baseWebpackChain)
const webpackChain = baseWebpackChain.merge(buildWebpackConf)
const webpackConfig = webpackChain.toConfig()
const onBuildFinish = config.onBuildFinish
const compiler = webpack(webpackConfig)
return new Promise((resolve, reject) => {
if (newConfig.isWatch) {
if (config.isWatch) {
bindDevLogger(compiler)
compiler.watch({
aggregateTimeout: 300,
Expand Down
30 changes: 4 additions & 26 deletions packages/taro-mini-runner/src/webpack/build.conf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
getDefinePlugin,
processEnvOption,
getCssoWebpackPlugin,
getUglifyPlugin,
getDevtool,
getOutput,
getModule,
Expand All @@ -17,13 +16,11 @@ import {
getMiniCssExtractPlugin,
getEntry,
} from './chain'
import getBaseConf from './base.conf'
import { createTarget } from '../plugins/MiniPlugin'

const emptyObj = {}

export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
const chain = getBaseConf(appPath)
export default (appPath: string, mode, config: Partial<IBuildConfig>, chain: any): any => {
const {
buildAdapter,
fileType = {
Expand All @@ -46,9 +43,6 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
defineConstants = emptyObj,
env = emptyObj,
cssLoaderOption = emptyObj,
sassLoaderOption = emptyObj,
lessLoaderOption = emptyObj,
stylusLoaderOption = emptyObj,
mediaUrlLoaderOption = emptyObj,
fontUrlLoaderOption = emptyObj,
imageUrlLoaderOption = emptyObj,
Expand All @@ -63,7 +57,6 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {

babel,
csso,
uglify,
commonChunks,
addChunkPages,

Expand Down Expand Up @@ -136,25 +129,14 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
? false
: true

const isUglifyEnabled = (uglify && uglify.enable === false)
? false
: true

if (mode === 'production') {
if (isUglifyEnabled) {
minimizer.push(getUglifyPlugin([
enableSourceMap,
uglify ? uglify.config : {}
]))
}

if (isCssoEnabled) {
const cssoConfig: any = csso ? csso.config : {}
plugin.cssoWebpackPlugin = getCssoWebpackPlugin([cssoConfig])
}
}
const taroBaseReg = new RegExp(`@tarojs[\\/]taro|@tarojs[\\/]${buildAdapter}`)
chain.merge({
return {
mode,
devtool: getDevtool(enableSourceMap),
watch: mode === 'development',
Expand All @@ -179,9 +161,6 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
enableSourceMap,

cssLoaderOption,
lessLoaderOption,
sassLoaderOption,
stylusLoaderOption,
fontUrlLoaderOption,
imageUrlLoaderOption,
mediaUrlLoaderOption,
Expand All @@ -191,7 +170,7 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
babel,
alias,
nodeModulesPath
}),
}, chain),
plugin,
optimization: {
minimizer,
Expand Down Expand Up @@ -226,6 +205,5 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
}
}
}
})
return chain
}
}
Loading