Comments (3)
Hi @dj0024javia I don't have much time to look into this, but if you want to take a look at my (working) config.
Note that I no longer use this plugin I made, esbuild-envfile-plugin. It does not work properly in some cases, and so I now use the dotenv package to do environment variables, from within the esbuild script, like below. I would like to re-introduce this plugin if I get back to refactoring it a bit, and can ensure it works in all cases.
Here is config for backend/node app:
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2020",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./src",
"incremental": true,
"paths": {
"app/*": ["./*"],
"api/*": ["./*"],
"lib/*": ["./lib/*"],
"src/*": ["./*"],
"exceptions/*": ["exceptions/*"],
"filters/*": ["filters/*"],
"models/*": ["models/pages/*"],
"modules/*": ["modules/*"],
"utils/*": ["./utils/*"],
},
},
"ts-node": {
"require": ["tsconfig-paths/register"]
},
"include": [
"scripts",
"src"
]
}
build.js, esbuild script for server:
var fs = require("fs");
var path = require("path");
const dotenv = require('dotenv');
const esbuild = require('esbuild');
const NODE_ENV = (process.env.NODE_ENV || 'local');
const IS_DEV = NODE_ENV == "local";
const APP_BASE = './src';
const ENTRY_FILE = `index.js`;
const OUTPUT_DIR = './static';
const OUTPUT_FILE = 'index.js';
const TARGET = 'esnext';
console.log('build() ...');
// --------------------------------------------------------------------------------
// load in environment variables as global defines for the to use
dotenv.config({ path: `.env.${NODE_ENV}` })
const define = {};
for (const k in process.env) {
// Bypass windows errors
if (k === 'CommonProgramFiles(x86)' || k === 'ProgramFiles(x86)') {
continue;
}
define[`process.env.${k}`] = JSON.stringify(process.env[k])
}
function build(entryFile, outFile) {
esbuild.build({
entryPoints: [entryFile],
outfile: outFile,
bundle: true,
target: TARGET,
logLevel: 'silent',
loader: {},
plugins: [copyPlugin],
sourcemap: false,
define
})
.then(r => { console.log(`Build ${entryFile} to ${outFile} succeeded.`) })
.catch((e) => {
console.log("Error building:", e.message);
process.exit(1)
})
}
let copyPlugin = {
name: 'copy',
setup(build) {
const fse = require('fs-extra');
//copy static folder to build
let buildFile = path.resolve(`./${APP_BASE}/${ENTRY_FILE}`);
let outFile = path.resolve(`${OUTPUT_DIR}/${OUTPUT_FILE}`);
try {
fse.copySync(buildFile, outFile, { overwrite: true });
console.log(`Copied ${buildFile} to ${outFile}`);
} catch (e) {
console.error('error: ', e);
}
}
}
function mkDirSync(dir) {
if (fs.existsSync(dir)) {
return;
}
try {
fs.mkdirSync(dir);
} catch (err) {
if (err.code == 'ENOENT') {
mkdirSync(path.dirname(dir))
mkdirSync(dir)
}
}
}
// make sure build directory exists
mkDirSync(OUTPUT_DIR);
build(`${APP_BASE}/${ENTRY_FILE}`, `${OUTPUT_DIR}/${OUTPUT_FILE}`);
This is for a React (frontend) app for the same project:
tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
"outDir": "./build/", // path to output directory
"sourceMap": true, // allow sourcemap support
"strictNullChecks": true, // enable strict null checks as a best practice
"module": "commonjs", // specifiy module code generation
"target": "ES2018", // specify ECMAScript target version
"jsx": "react", // use typescript to transpile jsx to js
"allowJs": true, // allow a partial TypeScript and JavaScript codebase
"noImplicitThis": true,
"noImplicitReturns": false,
"noImplicitAny": false,
"noUnusedLocals": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"skipLibCheck": true,
// Not sure if either of these are necessary:
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"app/*": ["./*"],
"src/*": ["./*"],
"components/*": ["components/*"],
"pages/*": ["components/pages/*"],
"lib/*": ["lib/*"],
"models/*": ["lib/models/*"],
"utils/*": ["lib/utils/*"],
"services/*": ["lib/services/*"],
"stores/*": ["lib/stores/*"],
"style/*": ["src/styles/*"],
"static/*": ["../static/*"],
"shared/*": ["../../shared/*"],
"admin/*": ["admin/*"]
},
"lib": [
"dom",
"dom.iterable",
"esnext"
]
},
"include": [
"./**/*",
"../../shared/**/*",
"../static/**/*"
],
"exclude": [
"../node_modules/**/*",
"../build/*",
"./styles/ng.reference/**/*"
]
}
build.js esbuild script for client:
var fs = require("fs");
var path = require("path");
const autoprefixer = require("autoprefixer");
const postCssPlugin = require("@deanc/esbuild-plugin-postcss");
const esbuild = require('esbuild');
const dotenv = require('dotenv');
const { mkDirSync } = require("./utils/fileUtils");
const { getNormalizedEnvVars } = require("./utils/envUtils");
// Config params (relative to where npm/script is called from):
const APP_BASE = './src';
const ENTRY_FILE = `index.jsx`;
const OUTPUT_DIR = './build';
const OUTPUT_FILE = 'app.js';
const TARGET = 'es2018';
const IS_DEV = process.env.NODE_ENV != 'production';
const NODE_ENV = (process.env.NODE_ENV || 'local');
dotenv.config({ path: `.env.${NODE_ENV}` })
const { define, defineNoQuotes } = getNormalizedEnvVars();
console.log('build.js node environment detected as: ' + NODE_ENV);
///////////////////////////////////////////////////////////////////////////////
function build(entryFile, outFile) {
console.log('build() called:', entryFile, outFile);
// make sure build directory existsSync
mkDirSync(OUTPUT_DIR);
esbuild.build({
entryPoints: [entryFile],
outfile: outFile,
bundle: true,
target: TARGET,
logLevel: 'info',
loader: { // built-in loaders: js, jsx, ts, tsx, css, json, text, base64, dataurl, file, binary
'.ttf': 'file',
'.otf': 'file',
'.png': 'file',
'.svg': 'file'
},
assetNames: 'static/[name].[hash]',
plugins: [scssPlugin, copyPlugin, postCssPlugin({ plugins: [autoprefixer] })],
sourcemap: IS_DEV ? true : false,
define
})
.then(r => { console.log(`Build ${entryFile} to ${outFile} succeeded.`) })
.catch((e) => {
console.log("Error building:", e.message);
process.exit(1)
})
}
let scssPlugin = {
name: 'scss',
setup(build) {
const fs = require('fs');
const sass = require('node-sass');
const path = require('path');
//const aliasImporter = require("node-sass-alias-importer");
build.onLoad({ filter: /\.(scss)$/ }, async (args) => {
let filePath = path.resolve(args.path);
let data = await fs.promises.readFile(filePath, 'utf8')
let contents = '';
try {
if (data) {
let result = sass.renderSync({
data,
//includePaths: [], // todo: dynamically add global imports??
sourceComments: true,
sourceMap: true,
// importer: [
// aliasImporter({
// app: "./src",
// styles: "./src/styles"
// })
// ]
});
contents = result.css;
}
return {
contents: contents,
loader: 'css'
};
} catch (e) {
throw new Error("\n\nError rendering SCSS file:\n " + filePath + " => \n\n" + e.formatted);//, { path: filePath });
}
})
}
};
let copyPlugin = {
name: 'copy',
setup(build) {
const fse = require('fs-extra');
// copy static folder to build.
try {
fse.copySync(path.resolve('./static'), path.resolve(`${OUTPUT_DIR}/static`), { overwrite: true });;
} catch (e) {
console.error('error: ', e);
}
}
}
build(`${APP_BASE}/${ENTRY_FILE}`, `${OUTPUT_DIR}/${OUTPUT_FILE}`);
Let me know if you get it working? Hope it helps.
from esbuild-envfile-plugin.
Thanks @rw3iss , i'll take a look at it.
Apologies for not providing enough information for you to look at the issue. Will try your solution and get back to you on this thread.
F.Y.I. i had issue with only the typescript errors...everything else works fine in the plugin. So, its a good plugin as far as i have used.
from esbuild-envfile-plugin.
Works just fine @rw3iss. Although i am not sure i would be much of the help for the project, but i would like to contribute to the typescript issue. Will let you know if i find any progress on the issue.
Thanks for the help.
from esbuild-envfile-plugin.
Related Issues (10)
- Does this repro accept pull request? HOT 3
- Missing comma in README example build script
- Empty .env file required for this plugin to work HOT 2
- utils.js: fs is not defined
- [ERROR] [plugin env] "path" must be a string HOT 1
- Handle missing .env files or missing ENV variables more gracefully HOT 4
- `The define key "process.env.ProgramFiles(x86)" contains invalid identifier "ProgramFiles(x86)"` HOT 1
- Could not resolve "env" in production when actual ENV variables are used and .env is missing HOT 8
- Could not resolve "env" HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from esbuild-envfile-plugin.