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- compilation . chunks . forEach ( commonChunk => {
15- const { files, chunks : childChunks , name } = commonChunk ;
16- let commonWxssFile = files . find ( item => item . endsWith ( '.wxss' ) ) ;
17-
18- if ( commonsChunkNames . indexOf ( name ) > - 1 && commonWxssFile ) {
19- childChunks . forEach ( item => {
20- let wxssFile = item . files . find ( item => item . endsWith ( '.wxss' ) ) ;
21- if ( item . name === 'app' && wxssFile ) { // 过滤 app
22- return ;
23- }
24- try {
25- if ( compilation . assets [ wxssFile ] ) {
26- let wxss = compilation . assets [ wxssFile ] . source ( ) ;
27- wxss = `@import "/${ commonWxssFile } ";\n${ wxss } ` ;
28- 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 } ` ;
2923 }
30- } catch ( error ) {
31- console . error ( error , wxssFile )
32- }
24+ } )
25+ compilation . assets [ filePath ] . source = ( ) => content ;
3326 } )
34- }
35- } ) ;
27+ } )
28+ } )
3629 callback ( ) ;
3730 } ) ;
3831} ;
3932
40- module . exports = MpvuePlugin ;
33+ module . exports = MpvuePlugin ;
0 commit comments