【发布时间】:2019-02-13 21:28:01
【问题描述】:
我想导入一些可能不存在的静态文件。我想修改这些外部静态文件并将它们加载到我的应用程序中,但是 Webpack 给出了“找不到模块”
我的文件夹结构在 dev 中如下所示:
- 源
- 静态
- 配置
- cfg.json
- 文件夹 1
- file1.js
- 文件夹2
- file2.js
- 配置
- 组件
- Main.js
- 静态
在生产环境中,webpack 构建所有内容,然后复制静态资源,使文件夹结构如下:
- 配置(内部文件和文件夹相同,但之后可能会被删除或更改)
- app.js
- 样式等
我想要做的是从 Main.js 中获取静态资产中 config 文件夹中的文件。
静态资产可能存在,也可能不存在。所以我尝试将'require'放在try/catch块中,在这种情况下,如果找不到所需的文件,那么我在catch中使用另一个流。
我可以在 Main.js ('../static/config/cfg.json') 中将此路径与 require 一起使用,但是 Webpack 会捆绑所有这些,所以如果我在生产中修改 config 文件夹中的文件,应用程序中看不到更改。
在生产和开发中,我可以通过http://localhost:3000/config/cfg.json 或http://localhost:3000/config/folder1/file1.js 访问静态文件
我可以使用 fetch 但我不知道如何读取在 file1.js 中导出的默认变量,我只能使用 FileReader 将整个文件作为字符串读取。
而且使用 fetch 代码看起来真的很混乱。 有什么方法可以通过 require 并选择相应的路径,而 Webpack 不会抛出“找不到模块”?
示例代码
try {
let config = require('../static/config/cfg.json'); // if the cfg.json doesn't exist go straight to catch
if (!config.active) {
// throw error
}
// continue flow and read the js files
// if the js files don't exist go straight to catch
}
catch(e => {
// follow another flow
})
正如我所说,此代码有效,但如果我在生产中修改静态文件中的任何内容,则不会看到更改,因为 Webpack 需要它捆绑的文件。
我希望看到对我的外部文件所做的更改,但 Webpack 需要它构建的静态文件。
提前谢谢你!
编辑:---添加了 webpack 配置条目---
// ------------------------------------
// Entry Points
// ------------------------------------
// config.clientDir is the 'src' folder
// main.js is a file located in the 'src' folder, where React.DOM is called.
// so APP_ENTRY_PATH = 'src/main.js'
// config.compiler.publicPath = /app-name/ui // in this format...
const APP_ENTRY_PATH = paths.base(config.clientDir) + '/main.js';
webpackConfig.entry = {
app: __DEV__ ?
[APP_ENTRY_PATH, `webpack-hot-middleware/client?path=${config.compiler.publicPath}__webpack_hmr`] :
[APP_ENTRY_PATH],
vendor: config.compiler.vendor
};
【问题讨论】:
-
能否在您的
webpack.config.js中添加有关entry的部分?? -
添加了来自 webpack.config.js 的条目 :)
标签: javascript reactjs webpack