J.M*_*ael 1 javascript reactjs webpack
我在 React 应用程序中使用绝对路径。但是 WebPack 给了我一个错误。ERROR in ./src/index.js Module not found: Error: Can't resolve 'App' in .../client/src'但是,我的文件位于此文件夹中。如何解决这个问题呢?我看到我已经写过类似的问题,但我没有在其中找到答案
网络包配置
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
publicPath: '/',
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'
},
{
test: /\.css$/, use: ['style-loader', 'css-loader'],
}
]
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './public/index/html'
}),
new MiniCssExtractPlugin({
filename: 'style.css'
})
]
};
Run Code Online (Sandbox Code Playgroud)
我的文件的层次结构
---project
--client
-public
index.html
-src
'folders'
index.js
App.js
App.css
--package.json
--webpack.config.js
--.babelrc
Run Code Online (Sandbox Code Playgroud)
您可以将其添加到您的 webpack.config 文件中。
resolve: {
extensions: ['.js', '.jsx'],
alias: {
root: __dirname,
src: path.resolve(__dirname, 'src'),
},
},
Run Code Online (Sandbox Code Playgroud)
然后你可以导入
import something from 'src/index.js'
但是,如果您使用 Webpack 以外的其他东西,例如 Jest、Storybook,那么您还需要应用这些信息。
例如开玩笑
npm install babel-plugin-module-resolver
并更新.babelrc以了解绝对路径
{
"plugins": [
[
"module-resolver",
{
"extensions": [".js", ".jsx"],
"root": ["./src"],
"alias": {
"root": ".",
"src": "/src"
}
}
]
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2481 次 |
| 最近记录: |