Remove webpack.*.ts importing values from src/ (#4992)

This commit is contained in:
Sebastian Malton authored and GitHub committed 2022-04-13 10:39:35 -04:00
1 parent d5528eb9fe
commit e977890677
21 files changed
+149 -168

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import Webpack from "webpack";
import WebpackDevServer from "webpack-dev-server";
import { webpackLensRenderer } from "./renderer";
import logger from "../src/common/logger";
import { buildDir, webpackDevServerPort } from "./vars";
/**
* API docs:
* @url https://webpack.js.org/configuration/dev-server/
* @url https://github.com/chimurai/http-proxy-middleware
*/
const config = webpackLensRenderer({ showVars: false });
const compiler = Webpack(config);
const server = new WebpackDevServer({
setupExitSignals: true,
headers: {
"Access-Control-Allow-Origin": "*",
},
allowedHosts: "all",
host: "localhost",
port: webpackDevServerPort,
static: buildDir, // aka `devServer.contentBase` in webpack@4
hot: "only", // use HMR only without errors
liveReload: false,
devMiddleware: {
writeToDisk: false,
index: "OpenLensDev.html",
publicPath: "/build",
},
proxy: {
"^/$": "/build/",
},
client: {
overlay: false, // don't show warnings and errors on top of rendered app view
logging: "error",
},
}, compiler);
logger.info(`[WEBPACK-DEV-SERVER]: created with options`, server.options);
server.start();
+77
View File
@@ -0,0 +1,77 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import path from "path";
import type webpack from "webpack";
import { cssModulesWebpackRule, fontsLoaderWebpackRules, iconsAndImagesWebpackRules } from "./renderer";
import { extensionEntry, extensionOutDir, isDevelopment } from "./vars";
export default function generateExtensionTypes(): webpack.Configuration {
return {
// Compile for Electron for renderer process
// see <https://webpack.js.org/configuration/target/>
target: "electron-renderer",
entry: extensionEntry,
// this is the default mode, so we should make it explicit to silence the warning
mode: isDevelopment ? "development" : "production",
output: {
filename: "extension-api.js",
// need to be an absolute path
path: path.resolve(extensionOutDir, "src", "extensions"),
// can be use in commonjs environments
// e.g. require('@k8slens/extensions')
libraryTarget: "commonjs",
},
cache: isDevelopment,
optimization: {
minimize: false, // speed up types compilation
},
ignoreWarnings: [
/Critical dependency: the request of a dependency is an expression/, // see who is using request: "npm ls request"
/require.extensions is not supported by webpack./, // handlebars
],
stats: "errors-warnings",
module: {
rules: [
{
test: /\.node$/,
loader: "ignore-loader",
},
{
test: /\.tsx?$/,
loader: "ts-loader",
options: {
// !! ts-loader will use tsconfig.json at folder root
// !! changes in tsconfig.json may have side effects
// !! on '@k8slens/extensions' module
compilerOptions: {
declaration: true, // output .d.ts
sourceMap: false, // to override sourceMap: true in tsconfig.json
outDir: extensionOutDir, // where the .d.ts should be located
},
},
},
cssModulesWebpackRule({ styleLoader: "style-loader" }),
...fontsLoaderWebpackRules(),
...iconsAndImagesWebpackRules(),
],
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
plugins: [
// In ts-loader's README they said to output a built .d.ts file,
// you can set "declaration": true in tsconfig.extensions.json,
// and use the DeclarationBundlerPlugin in your webpack config... but
// !! the DeclarationBundlerPlugin doesn't work anymore, author archived it.
// https://www.npmjs.com/package/declaration-bundler-webpack-plugin
// new DeclarationBundlerPlugin({
// moduleName: '@k8slens/extensions',
// out: 'extension-api.d.ts',
// })
],
};
}
+40
View File
@@ -0,0 +1,40 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import esbuild from "esbuild";
import type { Options as TSLoaderOptions } from "ts-loader";
/**
* A function returning webpack ts/tsx loader
* depends on env LENS_DEV_USE_ESBUILD_LOADER to use esbuild-loader (faster) or good-old ts-loader
* @returns ts/tsx webpack loader configuration object
*/
export default function getTypescriptLoader(options: Partial<TSLoaderOptions> = {}, testRegExp?: RegExp) {
testRegExp ??= /\.tsx?$/; // by default covers react/jsx-stuff
options.transpileOnly ??= true;
if (process.env.LENS_DEV_USE_ESBUILD_LOADER === "true") {
console.info(`\n🚀 using esbuild-loader for ts(x)`);
return {
test: testRegExp,
loader: "esbuild-loader",
options: {
loader: "tsx",
target: "ES2019", // supported by >= electron@14
implementation: esbuild,
},
};
}
return {
test: testRegExp,
exclude: /node_modules/,
use: {
loader: "ts-loader",
options,
},
};
}
+66
View File
@@ -0,0 +1,66 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import path from "path";
import type webpack from "webpack";
import ForkTsCheckerPlugin from "fork-ts-checker-webpack-plugin";
import nodeExternals from "webpack-node-externals";
import getTypeScriptLoader from "./get-typescript-loader";
import CircularDependencyPlugin from "circular-dependency-plugin";
import { iconsAndImagesWebpackRules } from "./renderer";
import type { WebpackPluginInstance } from "webpack";
import { buildDir, isDevelopment, mainDir } from "./vars";
const configs: { (): webpack.Configuration }[] = [];
configs.push((): webpack.Configuration => {
console.info("WEBPACK:main", {
isDevelopment,
mainDir,
buildDir,
});
return {
name: "lens-app-main",
context: __dirname,
target: "electron-main",
mode: isDevelopment ? "development" : "production",
devtool: isDevelopment ? "cheap-module-source-map" : "source-map",
cache: isDevelopment ? { type: "filesystem" } : false,
entry: {
main: path.resolve(mainDir, "index.ts"),
},
output: {
libraryTarget: "global",
path: buildDir,
},
resolve: {
extensions: [".json", ".js", ".ts"],
},
externals: [
nodeExternals(),
],
module: {
rules: [
{
test: /\.node$/,
use: "node-loader",
},
getTypeScriptLoader({}, /\.ts$/),
...iconsAndImagesWebpackRules(),
],
},
plugins: [
new ForkTsCheckerPlugin(),
new CircularDependencyPlugin({
cwd: __dirname,
exclude: /node_modules/,
failOnError: true,
}) as unknown as WebpackPluginInstance,
],
};
});
export default configs;
+210
View File
@@ -0,0 +1,210 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import path from "path";
import type webpack from "webpack";
import HtmlWebpackPlugin from "html-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import ForkTsCheckerPlugin from "fork-ts-checker-webpack-plugin";
import MonacoWebpackPlugin from "monaco-editor-webpack-plugin";
import CircularDependencyPlugin from "circular-dependency-plugin";
import ReactRefreshWebpackPlugin from "@pmmmwh/react-refresh-webpack-plugin";
import type { WebpackPluginInstance } from "webpack";
import getTypescriptLoader from "./get-typescript-loader";
import { assetsFolderName, isDevelopment, rendererDir, buildDir, appName, htmlTemplate, publicPath, sassCommonVars } from "./vars";
export function webpackLensRenderer({ showVars = true } = {}): webpack.Configuration {
if (showVars) {
console.info("WEBPACK:renderer", {
assetsFolderName,
isDevelopment,
rendererDir,
buildDir,
appName,
htmlTemplate,
publicPath,
});
}
return {
target: "electron-renderer",
name: "lens-app-renderer",
mode: isDevelopment ? "development" : "production",
// https://webpack.js.org/configuration/devtool/ (see description of each option)
devtool: isDevelopment ? "cheap-module-source-map" : "source-map",
cache: isDevelopment ? { type: "filesystem" } : false,
entry: {
[appName]: path.resolve(rendererDir, "bootstrap.tsx"),
},
output: {
libraryTarget: "global",
globalObject: "this",
publicPath,
path: buildDir,
filename: "[name].js",
chunkFilename: "chunks/[name].js",
assetModuleFilename: `${assetsFolderName}/[name][ext][query]`,
},
watchOptions: {
ignored: /node_modules/, // https://webpack.js.org/configuration/watch/
},
ignoreWarnings: [
/Critical dependency: the request of a dependency is an expression/,
/require.extensions is not supported by webpack./, // handlebars
/\[ReactRefreshPlugin] .*?HMR.*? is not enabled/, // enabled in webpack.dev-server
],
resolve: {
extensions: [
".js", ".jsx", ".json",
".ts", ".tsx",
],
},
externals: {
"node-fetch": "commonjs node-fetch",
},
optimization: {
minimize: false,
},
module: {
rules: [
{
test: /\.node$/,
use: "node-loader",
},
getTypescriptLoader({
getCustomTransformers: () => ({
before: isDevelopment ? [require("react-refresh-typescript")()] : [],
}),
}),
cssModulesWebpackRule(),
...iconsAndImagesWebpackRules(),
...fontsLoaderWebpackRules(),
],
},
plugins: [
new ForkTsCheckerPlugin(),
// see also: https://github.com/Microsoft/monaco-editor-webpack-plugin#options
new MonacoWebpackPlugin({
// publicPath: "/",
// filename: "[name].worker.js",
languages: ["json", "yaml"],
globalAPI: isDevelopment,
}),
new HtmlWebpackPlugin({
filename: `${appName}.html`,
template: htmlTemplate,
inject: true,
hash: true,
templateParameters: {
assetPath: `${publicPath}${assetsFolderName}`,
},
}),
new CircularDependencyPlugin({
cwd: __dirname,
exclude: /node_modules/,
failOnError: true,
}) as unknown as WebpackPluginInstance,
new MiniCssExtractPlugin({
filename: "[name].css",
}),
...(
isDevelopment
? [new ReactRefreshWebpackPlugin()]
: []
),
],
};
}
/**
* Import icons and image files.
* Read more about asset types: https://webpack.js.org/guides/asset-modules/
*/
export function iconsAndImagesWebpackRules(): webpack.RuleSetRule[] {
return [
{
test: /\.svg$/,
type: "asset/inline", // data:image/svg+xml;base64,...
},
{
test: /\.(jpg|png|ico)$/,
type: "asset/resource", // path to file, e.g. "/static/build/assets/*"
},
];
}
/**
* Import custom fonts as URL.
*/
export function fontsLoaderWebpackRules(): webpack.RuleSetRule[] {
return [
{
test: /\.(ttf|eot|woff2?)$/,
type: "asset/resource",
},
];
}
export interface CssModulesWebpackRuleOptions {
styleLoader?: string;
}
/**
* Import CSS or SASS styles with modules support (*.module.scss)
*/
export function cssModulesWebpackRule({ styleLoader }: CssModulesWebpackRuleOptions = {}): webpack.RuleSetRule {
styleLoader ??= isDevelopment
? "style-loader"
: MiniCssExtractPlugin.loader;
return {
test: /\.s?css$/,
use: [
styleLoader,
{
loader: "css-loader",
options: {
sourceMap: isDevelopment,
modules: {
auto: /\.module\./i, // https://github.com/webpack-contrib/css-loader#auto
mode: "local", // :local(.selector) by default
localIdentName: "[name]__[local]--[hash:base64:5]",
},
},
},
{
loader: "postcss-loader",
options: {
sourceMap: isDevelopment,
postcssOptions: {
plugins: [
"tailwindcss",
],
},
},
},
{
loader: "sass-loader",
options: {
sourceMap: isDevelopment,
additionalData: `@import "${path.basename(sassCommonVars)}";`,
sassOptions: {
includePaths: [
path.dirname(sassCommonVars),
],
},
},
},
],
};
}
export default webpackLensRenderer;
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "../tsconfig.json"
}
+25
View File
@@ -0,0 +1,25 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import assert from "assert";
import path from "path";
import packageInfo from "../package.json";
export const isDevelopment = process.env.NODE_ENV !== "production";
export const mainDir = path.join(process.cwd(), "src", "main");
export const buildDir = path.join(process.cwd(), "static", "build");
export const extensionEntry = path.join(process.cwd(), "src", "extensions", "extension-api.ts");
export const extensionOutDir = path.join(process.cwd(), "src", "extensions", "npm", "extensions", "dist");
export const assetsFolderName = "assets";
export const rendererDir = path.join(process.cwd(), "src", "renderer");
export const appName = isDevelopment
? `${packageInfo.productName}Dev`
: packageInfo.productName;
export const htmlTemplate = path.resolve(rendererDir, "template.html");
export const publicPath = "/build/";
export const sassCommonVars = path.resolve(rendererDir, "components/vars.scss");
export const webpackDevServerPort = Number(process.env.WEBPACK_DEV_SERVER_PORT) || 9191;
assert(Number.isInteger(webpackDevServerPort), "WEBPACK_DEV_SERVER_PORT environment variable must only be an integer");