Commit 2a0a7d35 authored by Master Q's avatar Master Q

项目初始化

parents
{
"presets": [
// ["@babel/preset-env", {
// "targets": "> 0.25%, not dead"
// }],
"@babel/preset-typescript"
],
"plugins": [
// ["@babel/plugin-transform-runtime", {
// // "corejs": 3
// }],
"@babel/plugin-proposal-optional-chaining",
"./babel-plugins/babel-plugins-test.js"
]
}
\ No newline at end of file
# project ignores
node_modules
released
.DS_Store
.idea
output.js
output.js.map
\ No newline at end of file
const targetCalleeName = ['log', 'info'].map(i => `console.${i}`)
const _pluginSyntaxJsx = require('@babel/plugin-syntax-jsx')
const _core = require('@babel/core')
const _helperModuleImports = require('@babel/helper-module-imports')
const PluginName = '@babel/plugin-test'
const defaultConfig = {
moduleName: './Dream',
pragma: 'Dream.createElement'
}
const JSX_SOURCE_ANNOTATION_REGEX = /^\s*\*?\s*@jsxImportSource\s+([^\s]+)\s*$/m;
const JSX_RUNTIME_ANNOTATION_REGEX = /^\s*\*?\s*@jsxRuntime\s+([^\s]+)\s*$/m;
const JSX_ANNOTATION_REGEX = /^\s*\*?\s*@jsx\s+([^\s]+)\s*$/m;
const mapIns = new Map()
const set = (k, v, map=mapIns) => map.set(`${PluginName}/${k}`, v)
const get = (k, map=mapIns) => map.get(`${PluginName}/${k}`)
function toMemberExpression(id) {
return id.split(".").map(name => _core.types.identifier(name)).reduce((object, property) => _core.types.memberExpression(object, property));
}
function call(pass, name, args) {
const node = _core.types.callExpression(get(`id/${name}`, pass)(), args);
// if (PURE_ANNOTATION != null ? PURE_ANNOTATION : get(pass, "defaultPure")) (0, _helperAnnotateAsPure.default)(node);
return node;
}
/**
* 转换 attribute 的value
* @param {*} node
* @returns
*/
function convertAttributeValue(node) {
if (_core.types.isJSXExpressionContainer(node)) {
return node.expression;
} else {
return node;
}
}
function accumulateAttribute(array, attribute) {
if (_core.types.isJSXSpreadAttribute(attribute.node)) {
const arg = attribute.node.argument;
if (_core.types.isObjectExpression(arg)) {
array.push(...arg.properties);
} else {
array.push(_core.types.spreadElement(arg));
}
return array;
}
const value = convertAttributeValue(attribute.node.name.name !== "key" ? attribute.node.value || _core.types.booleanLiteral(true) : attribute.node.value);
if (attribute.node.name.name === "key" && value === null) {
throw attribute.buildCodeFrameError('Please provide an explicit key value. Using "key" as a shorthand for "key={true}" is not allowed.');
}
if (_core.types.isStringLiteral(value) && !_core.types.isJSXExpressionContainer(attribute.node.value)) {
var _value$extra;
value.value = value.value.replace(/\n\s+/g, " ");
(_value$extra = value.extra) == null ? true : delete _value$extra.raw;
}
// 是否是 jsx NameSpaceName
if (_core.types.isJSXNamespacedName(attribute.node.name)) {
attribute.node.name = _core.types.stringLiteral(attribute.node.name.namespace.name + ":" + attribute.node.name.name.name);
} else if (_core.types.isValidIdentifier(attribute.node.name.name, false)) {
attribute.node.name.type = "Identifier";
} else {
attribute.node.name = _core.types.stringLiteral(attribute.node.name.name);
}
let t = _core.types.inherits(_core.types.objectProperty(attribute.node.name, value), attribute.node)
array.push(t);
return array;
}
function buildCreateElementOpeningElementAttributes(file, path, attribs) {
const objs = [];
const props = attribs.reduce(accumulateAttribute, []);
if (!defaultConfig.useSpread) {
let start = 0;
props.forEach((prop, i) => {
if (_core.types.isSpreadElement(prop)) {
if (i > start) {
objs.push(_core.types.objectExpression(props.slice(start, i)));
}
objs.push(prop.argument);
start = i + 1;
}
});
if (props.length > start) {
objs.push(_core.types.objectExpression(props.slice(start)));
}
} else if (props.length) {
objs.push(_core.types.objectExpression(props));
}
if (!objs.length) {
return _core.types.nullLiteral();
}
if (objs.length === 1) {
return objs[0];
}
if (!_core.types.isObjectExpression(objs[0])) {
objs.unshift(_core.types.objectExpression([]));
}
const helper = defaultConfig.useBuiltIns ? _core.types.memberExpression(_core.types.identifier("Object"), _core.types.identifier("assign")) : file.addHelper("extends");
return _core.types.callExpression(helper, objs);
}
/**
* 获取标签名称
* @param {*} openingPath
* @returns
*/
function getTag(openingPath) {
const tagExpr = convertJSXIdentifier(openingPath.node.name, openingPath.node);
let tagName;
if (_core.types.isIdentifier(tagExpr)) {
tagName = tagExpr.name;
} else if (_core.types.isLiteral(tagExpr)) {
tagName = tagExpr.value;
}
// isCompatTag /^[a-z]*/.test(tagName)
if (_core.types.react.isCompatTag(tagName)) {
return _core.types.stringLiteral(tagName);
} else {
return tagExpr;
}
}
function buildCreateElementCall(path, file) {
const openingPath = path.get("openingElement");
return call(file, "createElement", [getTag(openingPath),buildCreateElementOpeningElementAttributes(file, path, openingPath.get("attributes")), ..._core.types.react.buildChildren(path.node)]);
}
function convertJSXIdentifier(node, parent) {
if (_core.types.isJSXIdentifier(node)) {
//
if (node.name === "this" && _core.types.isReferenced(node, parent)) {
return _core.types.thisExpression();
} else if (_core.types.isValidIdentifier(node.name, false)) {
node.type = "Identifier";
} else {
return _core.types.stringLiteral(node.name);
}
} else if (_core.types.isJSXMemberExpression(node)) {
return _core.types.memberExpression(convertJSXIdentifier(node.object, node), convertJSXIdentifier(node.property, node));
} else if (_core.types.isJSXNamespacedName(node)) {
return _core.types.stringLiteral(`${node.namespace.name}:${node.name.name}`);
}
return node;
}
function createImportLazily(pass, path, importName, source) {
return () => {
const actualSource = source // getSource(source, importName);
if ((_helperModuleImports.isModule)(path)) {
let reference = get(`imports/${importName}`, pass);
if (reference) return _core.types.cloneNode(reference);
// reference = _helperModuleImports.addNamed(path, importName, actualSource, {
// importedInterop: "uncompiled",
// importPosition: "after"
// })
reference = _helperModuleImports.addDefault(path, actualSource, {
nameHint: importName
})
set(`imports/${importName}`, reference, pass);
return reference;
} else {
let reference = get(`requires/${actualSource}`, pass);
if (reference) {
reference = _core.types.cloneNode(reference);
} else {
reference = _helperModuleImports.addNamespace(path, actualSource, {
importedInterop: "uncompiled"
})
set(`requires/${actualSource}`, reference, pass)
}
return _core.types.memberExpression(reference, _core.types.identifier(importName));
}
};
}
module.exports = function(api, options) {
const {
types, template,
generate
} = api;
return {
inherits: _pluginSyntaxJsx.default,
visitor: {
Program: {
enter(path, state) {
const {
file
} = state;
let runtime = 'development'
let source = defaultConfig.moduleName
let pragma = defaultConfig.pragma
// if (file.ast.comments) {
// for (const comment of file.ast.comments) {
// const sourceMatches = JSX_SOURCE_ANNOTATION_REGEX.exec(comment.value);
// if (sourceMatches) {
// source = sourceMatches[1];
// }
// const runtimeMatches = JSX_RUNTIME_ANNOTATION_REGEX.exec(comment.value);
// if (runtimeMatches) {
// runtime = runtimeMatches[1];
// }
// const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
// if (jsxMatches) {
// pragma = jsxMatches[1];
// }
// }
// }
// path.traverse({
// ImportDeclaration(curPath) {
// const requirePath = curPath.get('source').node.value;
// if (requirePath === options.trackerPath) {// 如果已经引入了
// const specifierPath = curPath.get('specifiers.0');
// if (specifierPath.isImportSpecifier()) {
// state.trackerImportId = specifierPath.toString();
// } else if(specifierPath.isImportNamespaceSpecifier()) {
// state.trackerImportId = specifierPath.get('local').toString();// tracker 模块的 id
// }
// path.stop();// 找到了就终止遍历
// }
// }
// })
const createElement = toMemberExpression(pragma);
set("id/createElement", () => _core.types.cloneNode(createElement), state);
// createImportLazily(state, path, 'Dream', defaultConfig.moduleName)()
}
},
JSXSpreadChild(path) {
throw path.buildCodeFrameError("Spread children are not supported in React.");
},
CallExpression(path, state) {
const node = path.node
if (node.isSkip) return
const calleeName = path.get('callee').toString()
if (targetCalleeName.includes(calleeName)) {
const { line, column } = node.loc.start
// node.arguments.unshift(types.stringLiteral(`filename: (${line}, ${column})`))
const newNode = template.expression(`console.log('%c%s loc: %s', 'color: green', '${state.filename}', %%FILEPOSITION%%)`)({
// DATE: 'new Date().toLocaleString()',//'new Date().toLocaleString()',
FILEPOSITION: `'(${line}, ${column})'`
})
if (path.findParent(path => path.isJSXElement())) {
path.replaceWith(types.arrayExpression([newNode, node]))
path.skip()
} else {
path.insertBefore(newNode)
}
newNode.isSkip = true
node.isSkip = true
}
},
JSXElement: {
exit(path, state) {
let callExpr = buildCreateElementCall(path, state);
// inherits _core.types.inherits(callExpr, path.node)
path.replaceWith(callExpr);
}
}
}
}
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<title>Three</title>
<style>
* {
padding: 0;
margin: 0;
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
touch-action: none;
}
div {
user-select: none;
}
html,
body {
padding: 0;
margin: 0;
border: 0;
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
background-color: #ffffff;
/* background: linear-gradient(#93dbb7,#ff0,#b5d89a); */
/* background: linear-gradient(#93dbb7,#b5d89a); */
/* 背景图片,解决加载太慢,白屏问题,加了这个下面的__loading__可以删掉了 */
/* background-size: 100%;
background-position: center;
background-image: url("https://yun.duiba.com.cn/db_games/activity/game/1550472986/resource/assets/playscene/playscenebg.jpg"); */
}
</style>
<script src="//yun.duiba.com.cn/db_games/libs0924/fyge2020.min.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="ss" style="line-height:0;font-size:0;position: absolute;">
<canvas id="stage" style="width: 100%;height: 100%"></canvas>
</div>
<!-- 这里的 bundle 就是 webpack 临时打包出来 -->
<script src="output.js"></script>
<script type="module">
window.addEventListener("load", function () {
})
</script>
</body>
</html>
\ No newline at end of file
{
"name": "babeltemplate",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node ./scripts/devServer.js",
"babelbuild": "babel src --out-dir dist --extensions .ts,.tsx",
"build": "webpack --config webpack.prod.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.19.3",
"@babel/core": "^7.19.3",
"@babel/helper-module-imports": "^7.18.6",
"@babel/plugin-proposal-optional-chaining": "^7.18.9",
"@babel/plugin-syntax-jsx": "^7.18.6",
"@babel/plugin-transform-runtime": "^7.19.1",
"@babel/preset-env": "^7.19.1",
"@babel/preset-typescript": "^7.18.6",
"babel-loader": "^8.2.5",
"ts-loader": "^9.4.1",
"typescript": "^4.8.3",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1",
"webpack-merge": "^5.8.0"
}
}
const webpackDevServer = require('webpack-dev-server')
const webpack = require('webpack')
const config = require('../webpack.dev.js')
const compiler = webpack(config)
const server = new webpackDevServer(config.devServer, compiler)
const argv = process.argv;
const runServer = async () => {
const ipV4 = await webpackDevServer.internalIP('v4')
console.log('========== ipV4 ==========', ipV4)
server.options.host = ipV4
const argvPort = +argv[argv.indexOf("-p") + 1]
argvPort && (server.options.port = +argv[argv.indexOf("-p") + 1])
await server.start()
}
runServer()
\ No newline at end of file
console.log(123)
\ No newline at end of file
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
"jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
"strictPropertyInitialization": false, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
const path = require('path')
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
index: './src/index'
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /(node_modules)/,
use: [
{
loader: 'babel-loader',
}
],
exclude: /node_modules/
}
],
},
resolve: {
alias: {
'@': './src'
},
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'output.js',
path: __dirname, // path.resolve(__dirname, './dist'),
libraryTarget: 'umd'
}
}
\ No newline at end of file
const {merge} = require('webpack-merge');
const common = require('./webpack.common.js');
const path = require('path')
// const webpack = require('webpack');
// const MockWebpackPlugin = require('mock-webpack-plugin');
// const mockConfig = require('./mock/config.js');
module.exports = merge(common, {
mode: "development",
devtool: 'eval-source-map',
devServer: {
open: true,
hot: true,
host: '0.0.0.0',
static: '.'
}
});
const {merge} = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: "development",//production development
devtool: 'source-map',
plugins: [
]
});
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
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