1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import path from 'path'; 17 18import { 19 ESMODULE 20} from './common/ark_define'; 21import { ModuleSourceFile } from './module/module_source_file'; 22import { 23 isAotMode, 24 isCommonJsPluginVirtualFile, 25 isDebug, 26 isJsonSourceFile, 27 isJsSourceFile, 28 isTsOrEtsSourceFile 29} from './utils'; 30import { toUnixPath } from '../../utils'; 31 32export let newSourceMaps: Object = {}; 33 34/** 35 * rollup transform hook 36 * @param {string} code: transformed source code of an input file 37 * @param {string} id: absolute path of an input file 38 */ 39export function transformForModule(code: string, id: string) { 40 if (this.share.projectConfig.compileMode === ESMODULE) { 41 const projectConfig: any = Object.assign(this.share.arkProjectConfig, this.share.projectConfig); 42 if (isTsOrEtsSourceFile(id) && !isAotMode(projectConfig)) { 43 preserveSourceMap(id, this.getCombinedSourcemap(), projectConfig); 44 ModuleSourceFile.newSourceFile(id, code); 45 } 46 47 if (isJsSourceFile(id) || isJsonSourceFile(id)) { 48 let code: string = this.getModuleInfo(id).originalCode; 49 if (isJsSourceFile(id)) { 50 const transformedResult: any = transformJsByBabelPlugin(code); 51 code = transformedResult.code; 52 preserveSourceMap(id, transformedResult.map, projectConfig); 53 } 54 ModuleSourceFile.newSourceFile(id, code); 55 } 56 } 57} 58 59function preserveSourceMap(sourceFilePath: string, sourcemap: any, projectConfig: any): void { 60 if (isCommonJsPluginVirtualFile(sourceFilePath)) { 61 // skip automatic generated files like 'jsfile.js?commonjs-exports' 62 return; 63 } 64 65 const relativeSourceFilePath = toUnixPath(sourceFilePath.replace(projectConfig.projectRootPath + path.sep, '')); 66 sourcemap['sources'] = [ relativeSourceFilePath ]; 67 sourcemap['file'] = path.basename(relativeSourceFilePath); 68 sourcemap.sourcesContent && delete sourcemap.sourcesContent; 69 newSourceMaps[relativeSourceFilePath] = sourcemap; 70} 71 72function transformJsByBabelPlugin(code: string): any { 73 const transformed: any = require('@babel/core').transformSync(code, 74 { 75 plugins: [ 76 [require("@babel/plugin-proposal-class-properties"), { "loose": true }] 77 ], 78 compact: false, 79 sourceMaps: true 80 } 81 ); 82 return transformed; 83} 84