Skip to content

Commit

Permalink
feat: js中引入外部json直接编译到js文件里面
Browse files Browse the repository at this point in the history
  • Loading branch information
ximing committed Feb 1, 2020
1 parent d8b4852 commit 1ac4dc3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mpbuild",
"version": "1.3.0",
"version": "1.4.0",
"description": "",
"main": "src/index.js",
"scripts": {
Expand Down
35 changes: 24 additions & 11 deletions src/plugin/handleJSDep.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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'
Expand Down Expand Up @@ -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
});
}
}
}
Expand Down

0 comments on commit 1ac4dc3

Please sign in to comment.