[英]How to have a config.js file as an external (it being required during run time and not bundled) in webpack
我是 webpack 的新手。 我正在制作一個反應應用程序,它將從外部 config.js 文件中讀取文本並將其顯示在 UI 上。 我正在嘗試擁有一個外部 config.js 文件,我不想捆綁該文件,但在運行時需要該文件。 這是我的 webpack.config.js:
const path = require('path');
const html_plugin = require("html-webpack-plugin");
module.exports = {
mode: 'development',
entry: './src/app.js',
output: {
path: path.resolve(__dirname,'build'),
filename: 'build.js'
},
externals: {
config: './config.js',
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: ['style-loader','css-loader']
}
]
},
plugins: [new html_plugin({ template: './src/index.html' })]
}
config.js 與 webpack.config.js 位於同一目錄中。 這是我的 config.js:
module.exports = {
title: 'ssup'
}
這就是我在組件中使用 config.js 的方式:
import config from 'config';
class ... {
return <h1>{config.title}</h1>
}
這是我的項目結構:
- src/
- webpack.config.js
- config.js
當我嘗試運行此應用程序時,它在我的 chrome 控制台中顯示以下錯誤:
build.js 中的第 681 行包含以下內容:
eval("module.exports = ./config.js;\n\n//# sourceURL=webpack:///external_%22./config.js%22?");
這是我的 package.json:
{
"name": "react-from-scratch",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.10.2",
"react-dom": "^16.10.2"
},
"devDependencies": {
"@babel/core": "^7.6.4",
"@babel/preset-env": "^7.6.3",
"@babel/preset-react": "^7.6.3",
"babel-loader": "^8.0.6",
"css-loader": "^3.2.0",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.1",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.2"
}
}
我究竟做錯了什么?
你不需要任何 webpack 配置來做到這一點。 將您的配置保存為 JSON 並在運行時而不是構建時fetch
它。
另外,您想使用這種技術實現什么目標? 你的用例是什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.