Commit e07c1664 authored by rockyl's avatar rockyl

init

parents
Pipeline #121330 failed with stages
in 0 seconds
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless
#!/usr/bin/env node
/**
* Created by rockyl on 2019-04-26.
*/
const os = require('os');
const path = require('path');
const fs = require('fs-extra');
const program = require('commander');
const {compile} = require('../src/index');
program
.version('1.0.0')
.description('scilla ts compiler')
.option('-i, --input [string]', 'input file')
.option('-p, --projectPath [string]', 'path of project')
.option('-v, --verbose [boolean]', 'verbose mode', false)
.parse(process.argv);
if(!program.input || !program.output){
console.warn('parameter is incorrect');
process.exit(1);
}
const projectPath = program.projectPath || path.join(os.homedir(), '.scilla', 'components');
const tsconfig = fs.readJsonSync(path.join(projectPath, 'tsconfig.json'));
const inputFile = program.input;
const declareFile = path.join(path.dirname(inputFile), 'declare.json');
const outputFile = inputFile.replace('.ts', '.js');
const declares = fs.readJsonSync(declareFile);
const externalArr = declares.dependencies.filter(item => !item.startsWith('.'));
async function execute(){
await compile(
inputFile,
outputFile,
projectPath,
'debug',
null,
[],
tsconfig,
null,
externalArr
).catch(e=>{
console.error(e);
process.exit(2);
});
}
execute();
{
"name": "scilla-ts-compiler",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"fs-extra": "^7.0.1",
"resolve": "^1.10.1",
"rollup": "^1.10.1",
"rollup-plugin-commonjs": "^9.3.4",
"rollup-plugin-node-resolve": "^4.2.3",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-uglify": "^6.0.2",
"rollup-pluginutils": "^2.6.0",
"tslib": "^1.9.3",
"typescript": "^3.4.5"
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
/**
* Created by rockyl on 2019-04-29.
*/
const path = require('path');
const rollup = require('rollup');
const typescript = require('typescript');
const rpUglify = require('rollup-plugin-uglify');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const rpt = require('./rollup-plugin-typescript.es');
const replace = require('rollup-plugin-replace');
exports.compile = async function(inputFile, outputFile, projectPath, mode, moduleName, includePaths, tsconfig, tslib, externalArr = []) {
let tsPaths = includePaths ? includePaths.concat() : [];
let external = ['tslib'].concat(externalArr);
const pathsConfig = tsconfig.compilerOptions.paths;
if (pathsConfig) {
for (let key in pathsConfig) {
let paths = pathsConfig[key];
for (let basePath of paths) {
if (basePath[basePath.length - 1] === '*') {
basePath += '*/*.ts';
} else if(key[key.length - 1] === '*'){
basePath = basePath.replace(/\*\/index$/, '**/*.ts')
}else{
try {
basePath = basePath.replace(/index$/, '**/*.ts')
} catch (e) {
console.log(e);
}
}
tsPaths.push(basePath);
}
}
}
tsPaths = tsPaths.map(item => {
return path.resolve(projectPath, item);
});
//console.log(tsPaths);
let plugins = [
resolve({
browser: true,
}),
rpt({
typescript,
include: tsPaths,
tsconfig: tsconfig,
baseUrl: projectPath,
removeComments: true,
tslib,
}),
commonjs(),
];
if (mode === 'build') {
plugins.push(rpUglify.uglify({
//keep_fnames: true,
//toplevel: true,
mangle: {
//properties: true,+
reserved: [moduleName, 'startup', 'userAgent'],
}
}));
plugins.push(
replace({
'DEBUG': JSON.stringify(false),
'RELEASE': JSON.stringify(true),
})
)
} else {
plugins.push(
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
'process.env.VUE_ENV': JSON.stringify('browser'),
'DEBUG': JSON.stringify(true),
'RELEASE': JSON.stringify(false),
})
)
}
let writeConfig = {
file: outputFile,
format: 'esm',
name: moduleName,
};
if (mode === 'debug') {
writeConfig.sourcemap = true;
}
// create a bundle
const bundle = await rollup.rollup({
input: inputFile,
plugins,
external,
onwarn: warning => {
console.log('warning:', warning);
//throw new Error(warning);
}
})/*.catch(e=>{
console.log(e);
})*/;
// or write the bundle to disk
await bundle.write(writeConfig);
}
const ts = require('typescript');
const { createFilter } = require('rollup-pluginutils');
const { existsSync, readFileSync, statSync } = require('fs');
const resolveId = require('resolve');
const { sep } = require('path');
function endsWith ( str, tail ) {
return !tail.length || str.slice( -tail.length ) === tail;
}
function getDefaultOptions () {
return {
noEmitHelpers: true,
module: 'ESNext',
sourceMap: true,
importHelpers: true
};
}
// Gratefully lifted from 'look-up', due to problems using it directly:
// https://github.com/jonschlinkert/look-up/blob/master/index.js
// MIT Licenced
function findFile ( cwd, filename ) {
var fp = cwd ? ( cwd + '/' + filename ) : filename;
if ( existsSync( fp ) ) {
return fp;
}
var segs = cwd.split( sep );
var len = segs.length;
while ( len-- ) {
cwd = segs.slice( 0, len ).join( '/' );
fp = cwd + '/' + filename;
if ( existsSync( fp ) ) {
return fp;
}
}
return null;
}
function getCompilerOptionsFromTsConfig (typescript, tsconfigPath) {
if (tsconfigPath && !existsSync(tsconfigPath)) {
throw new Error(("Could not find specified tsconfig.json at " + tsconfigPath));
}
var existingTsConfig = tsconfigPath || findFile( process.cwd(), 'tsconfig.json' );
if (!existingTsConfig) {
return {};
}
var tsconfig = typescript.readConfigFile( existingTsConfig, function (path) { return readFileSync( path, 'utf8' ); } );
if ( !tsconfig.config || !tsconfig.config.compilerOptions ) { return {}; }
return tsconfig.config.compilerOptions;
}
function adjustCompilerOptions ( typescript, options ) {
// Set `sourceMap` to `inlineSourceMap` if it's a boolean
// under the assumption that both are never specified simultaneously.
if ( typeof options.inlineSourceMap === 'boolean' ) {
options.sourceMap = options.inlineSourceMap;
delete options.inlineSourceMap;
}
// Delete the `declaration` option to prevent compilation error.
// See: https://github.com/rollup/rollup-plugin-typescript/issues/45
delete options.declaration;
}
var resolveHost = {
directoryExists: function directoryExists ( dirPath ) {
try {
return statSync( dirPath ).isDirectory();
} catch ( err ) {
return false;
}
},
fileExists: function fileExists ( filePath ) {
try {
return statSync( filePath ).isFile();
} catch ( err ) {
return false;
}
}
};
var TSLIB_ID = '\0tslib';
function typescript ( options ) {
if ( options === void 0 ) options = {};
options = Object.assign( {}, options );
var filter = createFilter(
options.include || [ '*.ts+(|x)', '**/*.ts+(|x)' ],
options.exclude || [ '*.d.ts', '**/*.d.ts' ] );
delete options.include;
delete options.exclude;
// Allow users to override the TypeScript version used for transpilation and tslib version used for helpers.
var typescript = options.typescript || ts;
var tslib = options.tslib ||
readFileSync(resolveId.sync('tslib/tslib.es6.js', { basedir: __dirname }), 'utf-8' );
delete options.typescript;
delete options.tslib;
// Load options from `tsconfig.json` unless explicitly asked not to.
var tsconfig;
if(typeof options.tsconfig === 'object'){
tsconfig = options.tsconfig.compilerOptions;
}else{
tsconfig = options.tsconfig === false ?
{} :
getCompilerOptionsFromTsConfig( typescript, options.tsconfig );
}
delete options.tsconfig;
// Since the CompilerOptions aren't designed for the Rollup
// use case, we'll adjust them for use with Rollup.
adjustCompilerOptions( typescript, tsconfig );
adjustCompilerOptions( typescript, options );
options = Object.assign( tsconfig, getDefaultOptions(), options );
// Verify that we're targeting ES2015 modules.
var moduleType = options.module.toUpperCase();
if ( moduleType !== 'ES2015' && moduleType !== 'ES6' && moduleType !== 'ESNEXT' && moduleType !== 'COMMONJS' ) {
throw new Error( ("rollup-plugin-typescript: The module kind should be 'ES2015' or 'ESNext, found: '" + (options.module) + "'") );
}
var parsed = typescript.convertCompilerOptionsFromJson( options, process.cwd() );
if ( parsed.errors.length ) {
parsed.errors.forEach( function (error) { return console.error( ("rollup-plugin-typescript: " + (error.messageText)) ); } );
throw new Error( "rollup-plugin-typescript: Couldn't process compiler options" );
}
var compilerOptions = parsed.options;
return {
name: 'typescript',
resolveId: function resolveId ( importee, importer ) {
if ( importee === 'tslib' ) {
return TSLIB_ID;
}
if ( !importer ) { return null; }
importer = importer.split('\\').join('/');
var result = typescript.nodeModuleNameResolver(importee, importer, compilerOptions, resolveHost);
if ( result.resolvedModule && result.resolvedModule.resolvedFileName ) {
if ( endsWith( result.resolvedModule.resolvedFileName, '.d.ts' ) ) {
return null;
}
return result.resolvedModule.resolvedFileName;
}
return null;
},
load: function load ( id ) {
if ( id === TSLIB_ID ) {
return tslib;
}
},
transform: function transform ( code, id ) {
if ( !filter( id ) ) { return null; }
var transformed = typescript.transpileModule( code, {
fileName: id,
reportDiagnostics: true,
compilerOptions: compilerOptions
});
// All errors except `Cannot compile modules into 'es6' when targeting 'ES5' or lower.`
var diagnostics = transformed.diagnostics ?
transformed.diagnostics.filter( function (diagnostic) { return diagnostic.code !== 1204; } ) : [];
var fatalError = false;
var errorLogs = [];
diagnostics.forEach( function (diagnostic) {
var message = typescript.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
var e;
if ( diagnostic.file ) {
var ref = diagnostic.file.getLineAndCharacterOfPosition( diagnostic.start );
var line = ref.line;
var character = ref.character;
e = (diagnostic.file.fileName) + "(" + (line + 1) + "," + (character + 1) + "): error TS" + (diagnostic.code) + ": " + message;
} else {
e = "Error: " + message;
}
console.error(e);
errorLogs.push(e);
if ( diagnostic.category === ts.DiagnosticCategory.Error || diagnostic.category === ts.DiagnosticCategory.Warning ) {
fatalError = true;
}
});
if ( fatalError ) {
throw new Error( errorLogs.join('\n') );
}
return {
code: transformed.outputText,
// Rollup expects `map` to be an object so we must parse the string
map: transformed.sourceMapText ? JSON.parse(transformed.sourceMapText) : null
};
}
};
}
module.exports = typescript;
/**
* Created by rockyl on 2019-04-29.
*/
const fs = require('fs-extra');
const path = require('path');
const {compile} = require('../src/index');
const projectPath = '/Users/rockyl/.scilla/components';
const inputFile = '/Users/rockyl/.scilla/components/src/renderer/GraphicRenderer/1.0.0/index.ts';
const tsconfigFile = path.join(projectPath, 'tsconfig.json');
const tsconfig = fs.readJsonSync(tsconfigFile);
function test(){
const declareFile = path.join(path.dirname(inputFile), 'declare.json');
const outputFile = inputFile.replace('.ts', '.js');
const declares = fs.readJsonSync(declareFile);
const externalArr = declares.dependencies.filter(item => !item.startsWith('.'));
compile(
inputFile,
outputFile,
projectPath,
'debug',
null,
[],
tsconfig,
null,
externalArr
);
}
test();
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment