问题描述
我正在构建一个npm软件包,该软件包将从项目根目录接收自定义规则-类似于prettier在项目根目录中查找 .prettierrc
的方式.
I am building an npm package that will take in custom rules from the project root - similar to the way prettier looks for a .prettierrc
in the project root.
在我的程序包中,我正在使用webpack编译构建.我的应用程序使用react,我从外部将其引入,以便在运行时检索包,而不是在构建时将其捆绑.
In my package I am using webpack to compile the build. My app uses react, which I am pulling in externally so that the package is retrieved at runtime instead of being bundled at build time.
webpack.config.js
webpack.config.js
module.exports = {
entry: "./src/index.js",
output: {...},
module: {...},
resolve: {
modules: [path.resolve("./src"), path.resolve("./node_modules")],
alias: {
react: path.resolve(__dirname, "./node_modules/react"),
"react-dom": path.resolve(__dirname, "./node_modules/react-dom")
}
},
externals: {
react: {
commonjs: "react",
commonjs2: "react",
amd: "React",
root: "React"
},
"react-dom": {
commonjs: "react-dom",
commonjs2: "react-dom",
amd: "ReactDOM",
root: "ReactDOM"
}
}
};
在 externals
中,您可以看到我从构建中排除了 react
和 react-dom
.
Here in the externals
you can see that I am excluding react
and react-dom
from the build.
现在,我需要一种从项目根目录导入常规 settings.js
文件的方法,而不是从 node_modules
导入库的方法.webpack有此功能吗?
Now, I need a way to import a regular settings.js
file from the project root, rather than importing a library from the node_modules
. Does webpack have this capability?
到目前为止,我已经尝试使用 externals
像这样导入它:
So far I have tried using externals
to import it like so:
externals: {
react: {...},
"react-dom": {...},
"settings": { commonjs: "settings.js" }
}
我知道这是错误的,但是为了在运行时从项目目录导入外部 .js
文件,我可以做些类似的事情吗?
I know this is wrong, but is there something similar that I can do in order to import an external .js
file at runtime from the project directory?
推荐答案
我鼓励您捆绑而不是尝试在运行时导入内容.Webpack是捆绑器.当您尝试解决其设计工作时,事情会变得一团糟.
I would encourage you to bundle instead of trying to import things at runtime. Webpack is a bundler. Things get messy when you try to work around what its designed to do.
是的,您可以将根目录之外的文件导入到包中.这是我的一个使用外部代码的应用程序的示例.
And yes, you can import files outside of the root directory into your bundle. Here is an example from one of my apps that uses external code.
{
test: /\.js?$/,
include: [
path.resolve(__dirname),
path.resolve(__dirname, "../Public/js/src/common")
],
exclude: /node_modules/,
loader: "babel-loader"
}
我还创建了一个别名.
common: path.resolve(__dirname, "../Public/js/src/common"),
当您导入文件时,Webpack会将其与您的应用捆绑在一起.
Webpack will bundle this file with your app when you import it.
这篇关于如何使用webpack从项目根目录导入外部文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!