Skip to content

Commit

Permalink
Add first class Javascript/Typescript support to the Mill build tool (#…
Browse files Browse the repository at this point in the history
…4003)

### Related Issues

#3927

### Checklist

- [x] **example/jslib/basic**
- [x] 1-simple/: A minimal Typescript module demonstrating
typechecking/running/testing/bundling of a Node CLI tool
- [x] 2-react/: A minimal Typescript module demonstrating
typechecking/running/testing/bundling of a React-based web application,
served using a static HTML page
- [x] 3-custom-build-logic/: A Typescript module with custom build logic
  • Loading branch information
monyedavid authored Dec 5, 2024
1 parent 6478dc5 commit 50deaaa
Show file tree
Hide file tree
Showing 35 changed files with 896 additions and 78 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ mill.iml
bsp.log
lowered.hnir
.dotty-ide*
node_modules/
dist/
build/
*.bak
37 changes: 22 additions & 15 deletions example/javascriptlib/basic/1-simple/build.mill
Original file line number Diff line number Diff line change
@@ -1,27 +1,34 @@
package build

import mill._, javascriptlib._

object foo extends TypeScriptModule {
object bar extends TypeScriptModule {
def npmDeps = Seq("[email protected]")
}
}
object foo extends JestModule {
def npmDeps = Seq("[email protected]")

object qux extends TypeScriptModule {
def moduleDeps = Seq(foo, foo.bar)
}

// Documentation for mill.javascriptlib
// Documentation for mill.example.javascriptlib

/** Usage

> mill qux.run James Bond prof
> mill foo.run James Bond prof
Hello James Bond Professor

> mill show qux.bundle
".../out/qux/bundle.dest/bundle.js"

> node out/qux/bundle.dest/bundle.js James Bond prof
> mill foo.test
PASS .../foo.test.ts
...generateUser function
...should generate a user with all specified fields...
...should default lastName and role when they are not provided...
...should default all fields when args is empty...
...
Test Suites:...1 passed, 1 total...
Tests:...3 passed, 3 total...
Snapshots:...
Time:...
Ran all test suites matching ...

> mill show foo.bundle
Build succeeded!

> node out/foo/bundle.dest/bundle.js James Bond prof
Hello James Bond Professor

*/
4 changes: 0 additions & 4 deletions example/javascriptlib/basic/1-simple/foo/bar/src/bar.ts

This file was deleted.

28 changes: 27 additions & 1 deletion example/javascriptlib/basic/1-simple/foo/src/foo.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,33 @@
import {Map} from 'node_modules/immutable';

interface User {
firstName: string
lastName: string
role: string
}

export {User}
export const defaultRoles: Map<string, string> = Map({prof: "Professor"});

/**
* Generate a user object based on command-line arguments
* @param args Command-line arguments
* @returns User object
*/
export function generateUser(args: string[]): User {
return {
firstName: args[0] || "unknown",
lastName: args[1] || "unknown",
role: defaultRoles.get(args[2], ""),
};
}

// Main CLI logic
if (process.env.NODE_ENV !== "test") {
const args = process.argv.slice(2); // Skip 'node' and script name
const user = generateUser(args);

console.log(defaultRoles.toObject());
console.log(args[2]);
console.log(defaultRoles.get(args[2]));
console.log("Hello " + user.firstName + " " + user.lastName + " " + user.role);
}
64 changes: 64 additions & 0 deletions example/javascriptlib/basic/1-simple/foo/test/foo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import {generateUser, defaultRoles} from "../src/foo";
import {Map} from 'node_modules/immutable';

// Define the type roles object
type RoleKeys = "admin" | "user";
type Roles = {
[key in RoleKeys]: string;
};

// Mock `defaultRoles` as a global variable for testing
const mockDefaultRoles = Map<string, string>({
admin: "Administrator",
user: "User",
});

describe("generateUser function", () => {
beforeAll(() => {
process.env.NODE_ENV = "test"; // Set NODE_ENV for all tests
});

afterEach(() => {
jest.clearAllMocks();
});

test("should generate a user with all specified fields", () => {
// Override the `defaultRoles` map for testing
(defaultRoles as any).get = mockDefaultRoles.get.bind(mockDefaultRoles);

const args = ["John", "Doe", "admin"];
const user = generateUser(args);

expect(user).toEqual({
firstName: "John",
lastName: "Doe",
role: "Administrator",
});
});

test("should default lastName and role when they are not provided", () => {
(defaultRoles as any).get = mockDefaultRoles.get.bind(mockDefaultRoles);

const args = ["Jane"];
const user = generateUser(args);

expect(user).toEqual({
firstName: "Jane",
lastName: "unknown",
role: "",
});
});

test("should default all fields when args is empty", () => {
(defaultRoles as any).get = mockDefaultRoles.get.bind(mockDefaultRoles);

const args: string[] = [];
const user = generateUser(args);

expect(user).toEqual({
firstName: "unknown",
lastName: "unknown",
role: "",
});
});
});
13 changes: 13 additions & 0 deletions example/javascriptlib/basic/1-simple/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export default {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: [
'<rootDir>/**/test/**/*.test.ts',
'<rootDir>/**/test/**/*.test.js',
],
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', { tsconfig: 'tsconfig.json' }],
'^.+\\.(js|jsx)$': 'babel-jest', // Use babel-jest for JS/JSX files
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
13 changes: 0 additions & 13 deletions example/javascriptlib/basic/1-simple/qux/src/qux.ts

This file was deleted.

26 changes: 26 additions & 0 deletions example/javascriptlib/basic/2-react/build.mill
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package build

import mill._, javascriptlib._

object foo extends RsWithServeModule {
override def mkENV = Task {
super.mkENV() ++ Map("PORT" -> "3000")
}
}

// Documentation for mill.example.javascriptlib

/** Usage

> mill foo.test
PASS src/test/App.test.tsx
...renders learn react link...
Test Suites:...1 passed, 1 total
Tests:...1 passed, 1 total
Snapshots:...
Time:...
Ran all test suites...

> mill show foo.bundle # build the react app with react-scripts # `foo.run` serves static html using serve
...
*/
Binary file not shown.
43 changes: 43 additions & 0 deletions example/javascriptlib/basic/2-react/foo/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions example/javascriptlib/basic/2-react/foo/public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
3 changes: 3 additions & 0 deletions example/javascriptlib/basic/2-react/foo/public/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
38 changes: 38 additions & 0 deletions example/javascriptlib/basic/2-react/foo/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
26 changes: 26 additions & 0 deletions example/javascriptlib/basic/2-react/foo/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react';
import logo from 'src/logo.svg';
import 'src/App.css';

function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}

export default App;
13 changes: 13 additions & 0 deletions example/javascriptlib/basic/2-react/foo/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
19 changes: 19 additions & 0 deletions example/javascriptlib/basic/2-react/foo/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './app/App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Loading

0 comments on commit 50deaaa

Please sign in to comment.