Skip to content

Commit

Permalink
fix(mini-runner): 优化 webpack 编译时样式处理
Browse files Browse the repository at this point in the history
  • Loading branch information
luckyadam committed Jan 7, 2020
1 parent 2adeaaf commit 6b8e540
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 17 deletions.
3 changes: 2 additions & 1 deletion packages/taro-mini-runner/src/loaders/fileParseLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
taroJsRedux,
QUICKAPP_SPECIAL_COMPONENTS,
PARSE_AST_TYPE,
NODE_MODULES_REG
NODE_MODULES_REG,
REG_STYLE
} from '../utils/constants'
import {
isNpmPkg,
Expand Down
22 changes: 21 additions & 1 deletion packages/taro-mini-runner/src/plugins/TaroLoadChunksPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as path from 'path'

import webpack, { compilation } from 'webpack'
import { ConcatSource } from 'webpack-sources'
import { urlToRequest } from 'loader-utils'

import { PARSE_AST_TYPE } from '../utils/constants'
import { PARSE_AST_TYPE, REG_STYLE } from '../utils/constants'

import { ITaroFileInfo } from './MiniPlugin'

Expand All @@ -29,6 +31,24 @@ export default class TaroLoadChunksPlugin {
})
compilation.chunkTemplate.hooks.renderWithEntry.tap(PLUGIN_NAME, (modules, chunk) => {
if (chunk.entryModule && chunk.entryModule.miniType === PARSE_AST_TYPE.ENTRY) {
compilation.hooks.afterOptimizeAssets.tap(PLUGIN_NAME, assets => {
const files = chunk.files
files.forEach(item => {
if (REG_STYLE.test(item)) {
const source = new ConcatSource()
const _source = assets[item]._source
Object.keys(assets).forEach(assetName => {
const fileName = path.basename(assetName, path.extname(assetName))
if (REG_STYLE.test(assetName) && this.commonChunks.includes(fileName)) {
source.add(`@import ${JSON.stringify(urlToRequest(assetName))}`)
source.add('\n')
source.add(_source)
assets[item]._source = source
}
})
}
})
})
const source = new ConcatSource()
commonChunks.reverse().forEach(chunkItem => {
source.add(`require(${JSON.stringify(urlToRequest(chunkItem.name))});\n`)
Expand Down
8 changes: 7 additions & 1 deletion packages/taro-mini-runner/src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ export const CSS_EXT: string[] = ['.css', '.scss', '.sass', '.less', '.styl', '.
export const SCSS_EXT: string[] = ['.scss']
export const JS_EXT: string[] = ['.js', '.jsx']
export const TS_EXT: string[] = ['.ts', '.tsx']
export const UX_EXT: string[] = ['.ux']

export const REG_JS: RegExp = /\.js(\?.*)?$/
export const REG_SCRIPT: RegExp = /\.(js|jsx)(\?.*)?$/
export const REG_TYPESCRIPT: RegExp = /\.(tsx|ts)(\?.*)?$/
export const REG_SCRIPTS: RegExp = /\.[tj]sx?$/
export const REG_SCRIPTS: RegExp = /\.[tj]sx?$/i
export const REG_SASS: RegExp = /\.(s[ac]ss)$/
export const REG_LESS: RegExp = /\.less$/
export const REG_STYLUS: RegExp = /\.styl$/
Expand All @@ -16,6 +18,10 @@ export const REG_MEDIA: RegExp = /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/
export const REG_IMAGE: RegExp = /\.(png|jpe?g|gif|bpm|svg|webp)(\?.*)?$/
export const REG_FONT: RegExp = /\.(woff2?|eot|ttf|otf)(\?.*)?$/
export const REG_JSON: RegExp = /\.json(\?.*)?$/
export const REG_UX: RegExp = /\.ux(\?.*)?$/
export const REG_WXML_IMPORT: RegExp = /<import(.*)?src=(?:(?:'([^']*)')|(?:"([^"]*)"))/gi
export const REG_URL: RegExp = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i
export const CSS_IMPORT_REG: RegExp = /@import (["'])(.+?)\1;/g

export const NODE_MODULES = 'node_modules'
export const NODE_MODULES_REG = /(.*)node_modules/
Expand Down
2 changes: 1 addition & 1 deletion packages/taro-mini-runner/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import * as resolvePath from 'resolve'
import * as t from 'babel-types'
import { mergeWith } from 'lodash'

import { CONFIG_MAP, JS_EXT, TS_EXT, NODE_MODULES_REG } from './constants'
import { CONFIG_MAP, JS_EXT, TS_EXT, NODE_MODULES_REG, MINI_APP_FILES, BUILD_TYPES, CSS_IMPORT_REG, REG_STYLE } from './constants'
import { IOption, IComponentObj } from './types'

export const isNodeModule = (filename: string) => NODE_MODULES_REG.test(filename)
Expand Down
11 changes: 9 additions & 2 deletions packages/taro-mini-runner/src/webpack/build.conf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ import {
getOutput,
getModule,
mergeOption,
getMiniPlugin
getMiniPlugin,
getMiniCssExtractPlugin
} from './chain'
import { BUILD_TYPES, PARSE_AST_TYPE } from '../utils/constants'
import { BUILD_TYPES, PARSE_AST_TYPE, MINI_APP_FILES, REG_STYLE } from '../utils/constants'
import { Targets } from '../plugins/MiniPlugin'

const emptyObj = {}
Expand Down Expand Up @@ -43,6 +44,7 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
mediaUrlLoaderOption = emptyObj,
fontUrlLoaderOption = emptyObj,
imageUrlLoaderOption = emptyObj,
miniCssExtractPluginOption = emptyObj,

postcss = emptyObj,

Expand All @@ -62,6 +64,11 @@ export default (appPath: string, mode, config: Partial<IBuildConfig>): any => {
plugin.definePlugin = getDefinePlugin([constantsReplaceList])
plugin.miniPlugin = getMiniPlugin({ buildAdapter, constantsReplaceList })

plugin.miniCssExtractPlugin = getMiniCssExtractPlugin([{
filename: `[name]${MINI_APP_FILES[buildAdapter].STYLE}`,
chunkFilename: `[id]${MINI_APP_FILES[buildAdapter].STYLE}`
}, miniCssExtractPluginOption])

const isCssoEnabled = (csso && csso.enable === false)
? false
: true
Expand Down
36 changes: 25 additions & 11 deletions packages/taro-mini-runner/src/webpack/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as path from 'path'

import * as CopyWebpackPlugin from 'copy-webpack-plugin'
import CssoWebpackPlugin from 'csso-webpack-plugin'
import * as MiniCssExtractPlugin from 'mini-css-extract-plugin'
import * as sass from 'node-sass'
import { partial } from 'lodash'
import { mapKeys, pipe } from 'lodash/fp'
Expand Down Expand Up @@ -101,6 +102,12 @@ export const getFileLoader = pipe(mergeOption, partial(getLoader, 'file-loader')
export const getFileParseLoader = pipe(mergeOption, partial(getLoader, path.resolve(__dirname, '../loaders/fileParseLoader')))
export const getWxTransformerLoader = pipe(mergeOption, partial(getLoader, path.resolve(__dirname, '../loaders/wxTransformerLoader')))

const getExtractCssLoader = () => {
return {
loader: MiniCssExtractPlugin.loader
}
}
export const getMiniCssExtractPlugin = pipe(mergeOption, listify, partial(getPlugin, MiniCssExtractPlugin))
export const getDefinePlugin = pipe(mergeOption, listify, partial(getPlugin, webpack.DefinePlugin))
export const getUglifyPlugin = ([enableSourceMap, uglifyOptions]) => {
return new UglifyJsPlugin({
Expand Down Expand Up @@ -182,6 +189,8 @@ export const getModule = (appPath: string, {
cssLoaderOption
]

const extractCssLoader = getExtractCssLoader()

const cssLoader = getCssLoader(cssOptions)
const cssLoaders: {
include?;
Expand Down Expand Up @@ -230,11 +239,11 @@ export const getModule = (appPath: string, {

const stylusLoader = getStylusLoader([{ sourceMap: enableSourceMap }, stylusLoaderOption])

const fileLoader = getFileLoader([{
useRelativePath: true,
name: `[path][name]${MINI_APP_FILES[buildAdapter].STYLE}`,
context: sourceDir
}])
// const fileLoader = getFileLoader([{
// useRelativePath: true,
// name: `[path][name]${MINI_APP_FILES[buildAdapter].STYLE}`,
// context: sourceDir
// }])

const fileParseLoader = getFileParseLoader([{
babel,
Expand Down Expand Up @@ -264,18 +273,23 @@ export const getModule = (appPath: string, {
enforce: 'pre',
use: [stylusLoader]
},
// css: {
// test: REG_STYLE,
// oneOf: cssLoaders
// },
styleFiles: {
css: {
test: REG_STYLE,
use: [fileLoader]
oneOf: cssLoaders
},
// styleFiles: {
// test: REG_STYLE,
// use: [fileLoader]
// },
postcss: {
test: REG_STYLE,
use: [postcssLoader]
},
customStyle: {
test: REG_STYLE,
enforce: 'post',
use: [extractCssLoader]
},
script: {
test: REG_SCRIPTS,
use: [fileParseLoader, wxTransformerLoader],
Expand Down
1 change: 1 addition & 0 deletions packages/taro/types/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export interface IMiniAppConfig {
mediaUrlLoaderOption: IOption,
fontUrlLoaderOption: IOption,
imageUrlLoaderOption: IOption,
miniCssExtractPluginOption: IOption,

customFilesTypes: IMINI_APP_FILE_TYPE
}
Expand Down

0 comments on commit 6b8e540

Please sign in to comment.