From 1ac4dc3aa91f494bf281892b1500974adc258f17 Mon Sep 17 00:00:00 2001 From: ximing Date: Sat, 1 Feb 2020 15:44:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20js=E4=B8=AD=E5=BC=95=E5=85=A5=E5=A4=96?= =?UTF-8?q?=E9=83=A8json=E7=9B=B4=E6=8E=A5=E7=BC=96=E8=AF=91=E5=88=B0js?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E9=87=8C=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/plugin/handleJSDep.js | 35 ++++++++++++++++++++++++----------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index 6cb8bb0..eaf3bdb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mpbuild", - "version": "1.3.0", + "version": "1.4.0", "description": "", "main": "src/index.js", "scripts": { diff --git a/src/plugin/handleJSDep.js b/src/plugin/handleJSDep.js index 90f95e1..01583d2 100644 --- a/src/plugin/handleJSDep.js +++ b/src/plugin/handleJSDep.js @@ -6,8 +6,10 @@ const babylon = require('@babel/parser'); const t = require('@babel/types'); const babelTraverse = require('@babel/traverse').default; const generate = require('@babel/generator').default; +const template = require('@babel/template').default; const bresolve = require('browser-resolve'); const resolve = require('resolve'); +const fs = require('fs'); module.exports = class HandleJSDep { constructor() { @@ -24,7 +26,7 @@ module.exports = class HandleJSDep { babelTraverse(ast, { Expression: { enter: (astPath) => { - const { node } = astPath; + const { node, parent } = astPath; if ( node.type === 'CallExpression' && node.callee.name === 'require' @@ -109,17 +111,28 @@ module.exports = class HandleJSDep { ); libOutputPath = `${libOutputPathPrefix}.js`; } - node.arguments[0].value = path.relative( - path.parse(asset.outputFilePath).dir, - libOutputPath - ); - if (node.arguments[0].value[0] !== '.') { - node.arguments[0].value = `./${node.arguments[0].value}`; + // JSON 被直接替换 + if (libOutputPath.endsWith('.json')) { + // const [libOutputPathPrefix] = mpb.helper.splitExtension( + // libOutputPath + // ); + // libOutputPath = `${libOutputPathPrefix}.js`; + parent.right = template.ast( + `(${fs.readFileSync(libPath, 'utf-8')})` + ); + } else { + node.arguments[0].value = path.relative( + path.parse(asset.outputFilePath).dir, + libOutputPath + ); + if (node.arguments[0].value[0] !== '.') { + node.arguments[0].value = `./${node.arguments[0].value}`; + } + deps.push({ + libPath, + libOutputPath + }); } - deps.push({ - libPath, - libOutputPath - }); } } }