1+ const path = require ( 'path' ) ;
2+ const upath = require ( 'upath' ) ;
3+ const relative = require ( 'relative' ) ;
4+
15function MpvuePlugin ( ) { }
26
37MpvuePlugin . prototype . apply = function ( compiler ) {
4- const { options : { entry, plugins} } = compiler ;
58 compiler . plugin ( 'emit' , function ( compilation , callback ) {
6- let commonsChunkNames = [ ] ;
7- // 获取所有的 chunk name
8- plugins . forEach ( item => {
9- let { chunkNames } = item ;
10- if ( item . constructor . name === 'CommonsChunkPlugin' && chunkNames ) {
11- commonsChunkNames = commonsChunkNames . concat ( chunkNames ) ;
12- }
13- } )
14- let pages = Object . keys ( entry ) ;
15- compilation . chunks . forEach ( commonChunk => {
16- const { files, chunks : childChunks , name } = commonChunk ;
17- let commonWxssFile = files . find ( item => item . endsWith ( '.wxss' ) ) ;
18-
19- if ( commonsChunkNames . indexOf ( name ) > - 1 && commonWxssFile ) {
20- childChunks . forEach ( item => {
21- let wxssFile = item . files . find ( item => item . endsWith ( '.wxss' ) ) ;
22- if ( item . name === 'app' && wxssFile ) { // 过滤 app
23- return ;
24- }
25- try {
26- if ( compilation . assets [ wxssFile ] ) {
27- let wxss = compilation . assets [ wxssFile ] . source ( ) ;
28- wxss = `@import "/${ commonWxssFile } ";\n${ wxss } ` ;
29- compilation . assets [ wxssFile ] . source = ( ) => wxss ;
9+ Object . keys ( compilation . entrypoints ) . forEach ( key => {
10+ const entry = compilation . entrypoints [ key ] ;
11+ const { chunks } = entry ;
12+ const entryChunk = chunks . pop ( ) ;
13+ entryChunk . files . forEach ( filePath => {
14+ const extname = path . extname ( filePath ) ;
15+ let content = compilation . assets [ filePath ] . source ( ) ;
16+ chunks . reverse ( ) . forEach ( chunk => {
17+ chunk . files . forEach ( childFile => {
18+ if ( path . extname ( childFile ) === extname && compilation . assets [ filePath ] ) {
19+ const relativePath = upath . normalize ( relative ( filePath , childFile ) )
20+ content = extname === '.wxss' ?
21+ `@import "${ relativePath } ";\n${ content } `
22+ : `require("${ relativePath } ");\n${ content } ` ;
3023 }
31- } catch ( error ) {
32- console . error ( error , wxssFile )
33- }
24+ } )
25+ compilation . assets [ filePath ] . source = ( ) => content ;
3426 } )
35- }
36- } ) ;
27+ } )
28+ } )
3729 callback ( ) ;
3830 } ) ;
3931} ;
4032
41- module . exports = MpvuePlugin ;
33+ module . exports = MpvuePlugin ;
0 commit comments