我有一个运行Typescript的React App,我正在将其实现到现有的ASP.NET站点中。尝试设置环境。变量,但是一旦实现了这一点,我就会不断出错。
我曾经尝试过进行一些Google搜索,但是似乎找不到与我遇到相同问题的人。
我的package.json文件中包含以下脚本:
"scripts": {
"build": "webpack --env.ENVIRONMENT=production -p --progress --config webpack.config.js",
"dev-build": "webpack --env.ENVIRONMENT=development -p --progress --config webpack.config.js",
"test-build": "webpack --env.ENVIRONMENT=test -p --progress --config webpack.config.js",
"start": "webpack --env.ENVIRONMENT=development -d --progress --config webpack.config.js --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
然后我有了这个webpack.config.js:
const webpack = require('webpack');
const dotenv = require('dotenv');
const fs = require('fs'); // Check if the file exists
const path = require('path'); // Get the current path
module.exports = (env) => {
// Get the root path
const currentPath = path.join(__dirname);
// Create the fallback path (the production .env)
const basePath = currentPath + '/.env';
const envPath = basePath + '.' + env.ENVIRONMENT;
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
// reduce it to a nice object
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
return {
plugins: [
new webpack.DefinePlugin(envKeys)
],
devtool: "source-map", // Enable sourcemaps for debugging webpack's output
entry: __dirname + "/app", // Entry point, where webpack starts to run
mode: "production",
module: {
rules: [
{
test: /\.(t|j)sx?$/,
exclude: /node_modules/,
use: [
{
loader: "awesome-typescript-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
}
]
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
// Add '.ts', '.tsx', '.js' and '.jsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".jsx"]
},
};
}
我不断收到此错误:
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! react_implementation@1.0.0 test-build: `webpack --env.ENVIRONMENT=test -p --progress --config webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the react_implementation@1.0.0 test-build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
无论何时我执行npm run build
或其他任何命令,都会发生这种情况,但是当我在脚本的末尾添加--watch
时,它将运行而不会引发错误。我对导致此问题的原因感到困惑。
对于使用webpack还是有一些新的了解,但是能够运行不同的脚本而不会引发错误会很好。