Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 有条件地导入npm模块?_Javascript_Reactjs_Npm_Webpack_Ecmascript 6 - Fatal编程技术网

Javascript 有条件地导入npm模块?

Javascript 有条件地导入npm模块?,javascript,reactjs,npm,webpack,ecmascript-6,Javascript,Reactjs,Npm,Webpack,Ecmascript 6,我的项目结构如下: - workspace - customPackage - customIndex.js - myProject - index.js - myProject2 - index.js 在dev中,我想从本地工作区导入包,如下所示: //index.js import something from '../customePackage/customIndex.js' //index.js import something from 'cu

我的项目结构如下:

- workspace
  - customPackage
    - customIndex.js
  - myProject
    - index.js
  - myProject2
    - index.js
在dev中,我想从本地工作区导入包,如下所示:

//index.js
import something from '../customePackage/customIndex.js'
//index.js
import something from 'customPackage';
在生产中,我需要从npm模块导入,如下所示:

//index.js
import something from '../customePackage/customIndex.js'
//index.js
import something from 'customPackage';
目的是能够使用包中的本地更改(无需经历提交周期)。最后,经过测试,该软件包可以通过npm软件包推送并正常使用

如何以一种高效的方式做到这一点,而不必每次都对代码进行更改

您可以与Webpack一起使用:

resolve: {
    alias: {
        "customPackage": process.env.NODE_ENV === "production" ? 
            "customPackage" :
            path.resolve(__dirname, "../customePackage/customIndex.js")
    }
}
然后在源代码中,您只需执行以下操作:

import something from 'customPackage';

它将指向正确的包。显然,您需要设置
NODE\u ENV
环境变量,或者根据您的构建环境进行更改。

如果您已经在使用webpack,则可以创建两个不同的入口点:

entry: {
    bundle: './Scripts/index.tsx',
    bundle2: './Scripts/index2.tsx'
},
output: {
    publicPath: "/js/",
    path: path.join(__dirname, '/wwwroot/js/'),
    filename: '[name].js'
},

然后在
index
中导入主模块,在
index2
中导入测试模块。因此,您将拥有不同的bundle文件
bundle.js
bundle2.js

,感谢您的回复。但它给了我以下错误:模块构建失败:错误:解析错误:第1行:非法导入声明。可能是因为我试图访问项目目录(已定义.babelrc)之外的文件,因此babel loader无法正确加载。是的,我正在使用eslint。我的eslint.rc中确实有“ecmaFeatures”:{“jsx”:true,“modules”:true}。仍然不起作用。另外,我不知道为什么eslint会停止babel加载程序从项目目录外加载。@SahilSharma听起来像是babel问题。你需要弄清楚如何让Webpack针对那些不在你的项目范围内的文件运行babel是的,这是我问题的第二部分。我想我会为此单独发布一个问题。谢谢你的帮助。