所以對于我的 ReactJs 專案,我使用絕對路徑進行匯入,就像這樣
import {button} from /buttons
而不是這樣的相對路徑:
import {button} from ../../buttons
它適用于npm start,但是當我嘗試構建時,npm run build出現以下錯誤:
ERROR in ./src/Admin/Setting/Components/StepTwo.js 25:0-54
Module not found: Error: Can't resolve 'assets/theme/logoicon/edit.png' in 'C:\Users\nayeer\source\repos\project\src\Admin\Setting\Components'
@ ./src/Admin/Setting/index.js 3:0-43 16:59-66
@ ./src/Admin/Setting/index.js 175:0-92 685:15-30
@ ./src/AdminLayout/AppMain/index.js
@ ./src/Admin/MainAdmin/index.js 29:0-48 187:46-53
@ ./src/index.js 7:0-42 62:10-19
如何使用相對路徑構建專案?
這是我的 jsconfig.json :
{
"compilerOptions": {
"baseUrl": "./src"
},
"include": ["src"]
}
這是我的 webpack.config.js。我在 resolve.alias 中添加了我的基本檔案夾,src但它似乎不起作用:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const isProduction = process.env.NODE_ENV == "production";
const stylesHandler = isProduction
? MiniCssExtractPlugin.loader
: "style-loader";
const config = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "build"),
},
devServer: {
open: true,
host: "localhost",
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: "babel-loader",
},
{
test: /\.s[ac]ss$/i,
use: [stylesHandler, "css-loader", "postcss-loader", "sass-loader"],
},
{
test: /\.css$/i,
use: [stylesHandler, "css-loader", "postcss-loader"],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: "asset",
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
resolve: {
alias: {
Components: path.resolve(__dirname, 'src')
}
},
};
module.exports = () => {
if (isProduction) {
config.mode = "production";
config.plugins.push(new MiniCssExtractPlugin());
config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
} else {
config.mode = "development";
}
return config;
};
uj5u.com熱心網友回復:
在 Webpack 組態檔中,添加resolve.alias以便更輕松地創建別名和匯入模塊。
module.exports = {
//...
resolve: {
alias: {
Components: path.resolve(__dirname, 'src/components/')
}
}
}
例如,內部的所有模塊src/components/現在都可以使用絕對路徑。
并且為了VS code識別path
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"components/*": ["src/components/*"]
}
},
"exclude": ["node_modules"]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448483.html
標籤:javascript 节点.js 反应 npm 网页包
