Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

javascript - I need help adding environment variables to my TypeScript toolchain

I am requesting help setting up the compilation and dev environment for a typescript library. The library should work when consumed by a web app framework and when consumed by a script tag. I am currently using Webpack as a dev server so I can debug and TSC to build (cjs + esm). The issue that prompted this post was having to constantly switch my API strings between http://localhost:8080 to https://production.com. What tools or changes do I need in order to build dev and prod variables into my compilation?

Here is what I'm doing so far:

package.json fragment

"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"files": [
"scripts": {
    "build:esm": "tsc -p tsconfig.json --outDir lib/esm --module ES2020 --sourceMap false",
    "build:cjs": "tsc -p tsconfig.json --outdir lib/cjs --module commonjs --sourceMap false",
    "clean:build": "rimraf lib",
    "clean:serve": "rimraf dist",
    "build": "rimraf lib && npm run build:esm && npm run build:cjs",
    "serve": "rimraf dist && webpack-dev-server"


const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const SRC = path.resolve(__dirname, 'src')
const ENTRTY = path.resolve(__dirname, 'src', 'debug.ts')
const DIST = path.resolve(__dirname, 'dist')
module.exports = {
    mode: 'development',
    context: SRC,
    entry: ENTRTY,
    output: {
        path: DIST,
        filename: 'index.js',
    devtool: 'source-map',
    devServer: {
        contentBase: DIST,
        writeToDisk: true,
        host: '',
        port: 8080,
        https: true,
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin()
    resolve: {
        extensions: ['.ts', '.tsx', '.js']
    module: {
        rules: [
                test: /.tsx?$/,
                loader: 'ts-loader',
                include: [SRC]

My toolchain does not currently allow me to do do this:

import Axios from 'axios'
import SocketIO from 'socket.io-client'

export const axios = Axios.create({
    baseURL: process.env.SERVER_HTTP_URL, //<-- can't do env-vars with tsc build
    withCredentials: true

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share