[英]How to dynamically change import paths in webpack?
I have a set of exports that I normally import from one directory: 我有一组导出,我通常从一个目录导入:
import { myThing } from 'path/to/dir/es5/things'
However, if I run webpack with a specific NODE_ENV set, I would like the root of all such imports to be treated as es6 instead: 但是,如果我使用特定的NODE_ENV集运行webpack,我希望所有这些导入的根被视为es6:
import { myThing } from 'path/to/dir/es6/things'
How can I do this, eg have webpack dynamically resolve path/to/dir/es5/*
to path/to/dir/es6/*
? 我怎么能这样做,例如让webpack动态地将
path/to/dir/es5/*
解析为path/to/dir/es6/*
?
You can use an alias for that. 您可以使用别名。
For example, in your webpack configuration, you can use something like: 例如,在您的webpack配置中,您可以使用以下内容:
const alias = {};
if (NODE_ENV === ...) {
alias['path/to/dir/es5'] = 'path/to/dir/es6'
}
Further reading: https://webpack.js.org/configuration/resolve/ 进一步阅读: https : //webpack.js.org/configuration/resolve/
Here is my way of handling this stuff. 这是我处理这些东西的方式。
in your package.json, add env variable in following way 在package.json中,按以下方式添加env变量
"script": "... webpack --env.SOME_ENV_VAR=value -p"
Then, add your DefinePlugin inside your webpack.config file 然后,在webpack.config文件中添加DefinePlugin
plugins: [
...
new webpack.DefinePlugin({
SOME_ENV_VAR: env.SOME_ENV_VAR,
}),
...
]
Then you can use SOME_ENV_VAR as global variable inside your code 然后,您可以在代码中使用SOME_ENV_VAR作为全局变量
/* global SOME_ENV_VAR */
const esX = SOME_ENV_VAR === value ? 'es5' : 'es6';
myThing = require(`path/to/dir/${esX}/things`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.