Skip to content

Commit

Permalink
fix: mode set to development when build (#439)
Browse files Browse the repository at this point in the history
Co-authored-by: brightwwu <[email protected]>
  • Loading branch information
wre232114 and brightwwu authored Jun 28, 2023
1 parent 8834c3c commit de18942
Show file tree
Hide file tree
Showing 12 changed files with 93 additions and 37 deletions.
5 changes: 5 additions & 0 deletions .changeset/great-laws-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@farmfe/core': patch
---

Fix that build env set to development
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,6 @@ dist
target

build
!crates/**/build
.swc
.DS_Store
2 changes: 2 additions & 0 deletions crates/compiler/src/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub(crate) mod load;
pub(crate) mod parse;
pub(crate) mod resolve;
pub(crate) mod transform;
pub mod validate_config;

pub(crate) struct ResolveModuleIdResult {
pub module_id: ModuleId,
Expand All @@ -56,6 +57,7 @@ enum ResolveModuleResult {
impl Compiler {
pub(crate) fn build(&self) -> Result<()> {
self.context.plugin_driver.build_start(&self.context)?;
validate_config::validate_config(&self.context.config);

let (thread_pool, err_sender, err_receiver) = Self::create_thread_pool();

Expand Down
27 changes: 27 additions & 0 deletions crates/compiler/src/build/validate_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use farmfe_core::config::Config;
use farmfe_toolkit::fs::{ENTRY_NAME, RESOURCE_NAME};

/// Check possible errors in config
pub fn validate_config(config: &Config) {
let mut errors = vec![];

if config.input.len() > 1 && !config.output.entry_filename.contains(ENTRY_NAME) {
errors.push(format!(
"When `input` is more than one, `output.entry_filename` must contain {}",
ENTRY_NAME
));
}

if config.partial_bundling.module_buckets.len() <= 1
&& !config.output.filename.contains(RESOURCE_NAME)
{
errors.push(format!(
"When `partial_bundling.module_buckets` is not configured `output.filename` must contain {}",
RESOURCE_NAME
));
}

if !errors.is_empty() {
panic!("Config Validation Error: \n{}", errors.join("\n"));
}
}
20 changes: 12 additions & 8 deletions crates/plugin_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use farmfe_core::{
config::Config,
context::CompilationContext,
error::Result,
plugin::{Plugin, PluginHookContext, PluginResolveHookParam, PluginResolveHookResult},
plugin::{
Plugin, PluginHookContext, PluginResolveHookParam, PluginResolveHookResult, ResolveKind,
},
};
use farmfe_toolkit::regex::Regex;
use farmfe_utils::parse_query;
Expand Down Expand Up @@ -58,13 +60,15 @@ impl Plugin for FarmPluginResolve {
Path::new(&self.root).to_path_buf()
};

if [
"@swc/helpers/_/_interop_require_default",
"@swc/helpers/_/_interop_require_wildcard",
"@swc/helpers/_/_export_star",
]
.into_iter()
.all(|s| source != s)
// Entry module and internal modules should not be external
if !matches!(param.kind, ResolveKind::Entry(_))
&& [
"@swc/helpers/_/_interop_require_default",
"@swc/helpers/_/_interop_require_wildcard",
"@swc/helpers/_/_export_star",
]
.into_iter()
.all(|s| source != s)
{
// check external first, if the source is set as external, return it immediately
if context.config.external.iter().any(|e| {
Expand Down
21 changes: 13 additions & 8 deletions crates/toolkit/src/fs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ use farmfe_core::error::{CompilationError, Result};

use crate::hash::sha256;

pub const RESOURCE_NAME: &str = "[resourceName]";
pub const CONTENT_HASH: &str = "[contentHash]";
pub const EXT: &str = "[ext]";
pub const ENTRY_NAME: &str = "[entryName]";

/// read content of the path, return utf8 string.
pub fn read_file_utf8(path: &str) -> Result<String> {
let raw = read_file_raw(path)?;
Expand All @@ -26,17 +31,17 @@ pub fn transform_output_filename(
) -> String {
let mut res = filename_config;

if res.contains("[resourceName]") {
res = res.replace("[resourceName]", name);
if res.contains(RESOURCE_NAME) {
res = res.replace(RESOURCE_NAME, name);
}

if res.contains("[contentHash]") {
if res.contains(CONTENT_HASH) {
let content_hash = sha256(bytes, 8);
res = res.replace("[contentHash]", &content_hash);
res = res.replace(CONTENT_HASH, &content_hash);
}

if res.contains("[ext]") {
res = res.replace("[ext]", ext);
if res.contains(EXT) {
res = res.replace(EXT, ext);
}

res
Expand All @@ -51,8 +56,8 @@ pub fn transform_output_entry_filename(
) -> String {
let mut res = entry_filename_config;

if res.contains("[entryName]") {
res = res.replace("[entryName]", entry_filename);
if res.contains(ENTRY_NAME) {
res = res.replace(ENTRY_NAME, entry_filename);
}

transform_output_filename(res, name, bytes, ext)
Expand Down
1 change: 1 addition & 0 deletions examples/react-antd/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"@ant-design/icons": "^5.0.1",
"antd": "^5.4.2",
"clsx": "^1.2.1",
"core-js": "^3.30.1",
"react": "18",
"react-dom": "18",
"react-router-dom": "^6.13.0"
Expand Down
20 changes: 14 additions & 6 deletions packages/core/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,22 @@ export function loadEnv(
env[key] = value;
}
}

for (const key in process.env) {
if (key.startsWith(prefix)) {
env[key] = process.env[key] as string;
}
}
// Do not inject project process.env by default, cause it's unsafe
// for (const key in process.env) {
// if (key.startsWith(prefix)) {
// env[key] = process.env[key] as string;
// }
// }

config();
expand({ parsed });
return env;
}

export type CompilationMode = 'development' | 'production';

export function setProcessEnv(mode: CompilationMode) {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = mode;
}
}
25 changes: 11 additions & 14 deletions packages/core/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
isObject,
normalizePath
} from '../utils/index.js';
import { loadEnv } from './env.js';
import { CompilationMode, loadEnv } from './env.js';

export * from './types.js';
export const DEFAULT_CONFIG_NAMES = [
Expand All @@ -31,29 +31,22 @@ export const DEFAULT_CONFIG_NAMES = [
'farm.config.mjs'
];

type CompilationMode = 'development' | 'production';

/**
* Normalize user config and transform it to rust compiler compatible config
* @param config
* @returns resolved config that parsed to rust compiler
*/
export async function normalizeUserCompilationConfig(
userConfig: UserConfig,
mode = 'development',
env: CompilationMode = 'development'
mode: CompilationMode = 'development'
): Promise<Config> {
// resolve root path
const resolvedRootPath = normalizePath(
userConfig.root ? path.resolve(userConfig.root) : process.cwd()
);

const nodeEnv = !!process.env.NODE_ENV;
if (!nodeEnv) {
process.env.NODE_ENV = env;
}
const isProduction = process.env.NODE_ENV === 'production';
const isDevelopment = process.env.NODE_ENV === 'development';
const isProduction = mode === 'production';
const isDevelopment = mode === 'development';

const config: Config['config'] = merge(
{
Expand All @@ -74,7 +67,7 @@ export async function normalizeUserCompilationConfig(
// TODO load env variables from .env file
config.env = {
...userEnv,
NODE_ENV: process.env.NODE_ENV
NODE_ENV: process.env.NODE_ENV || mode
};
config.define = Object.assign(config.define ?? {}, config.env);

Expand Down Expand Up @@ -110,6 +103,10 @@ export async function normalizeUserCompilationConfig(
}
}

if (config.mode === undefined) {
config.mode = mode;
}

if (isProduction) {
if (!config.output) {
config.output = {};
Expand Down Expand Up @@ -341,10 +338,10 @@ async function readConfigFile(
const normalizedConfig = await normalizeUserCompilationConfig({
compilation: {
input: {
config: configFilePath
[fileName]: configFilePath
},
output: {
entryFilename: fileName,
entryFilename: '[entryName]',
path: outputPath,
targetEnv: 'node'
},
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ import { Config } from '../binding/index.js';
import { compilerHandler } from './utils/build.js';

import type { FarmCLIOptions } from './config/types.js';
import { setProcessEnv } from './config/env.js';

export async function start(
inlineConfig: FarmCLIOptions & UserConfig
): Promise<void> {
const logger = inlineConfig.logger ?? new DefaultLogger();
setProcessEnv('development');
const config: UserConfig = await resolveUserConfig(inlineConfig, logger);
const normalizedConfig = await normalizeUserCompilationConfig(config);

Expand Down Expand Up @@ -59,6 +61,7 @@ export async function build(
options: FarmCLIOptions & UserConfig
): Promise<void> {
const logger = options.logger ?? new DefaultLogger();
setProcessEnv('production');
const userConfig: UserConfig = await resolveUserConfig(options, logger);
const normalizedConfig = await normalizeUserCompilationConfig(
userConfig,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/tests/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export async function getCompiler(
},
output: {
path: path.join('dist', p),
entryFilename: 'index.mjs',
entryFilename: '[entryName].mjs',
targetEnv: 'node'
},
lazyCompilation: false,
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit de18942

Please sign in to comment.