gpt4 book ai didi

javascript - 使用 Webpack 或 Babel 通过前端的 import 语句使用 node_modules

转载 作者:行者123 更新时间:2023-11-30 19:31:31 24 4
gpt4 key购买 nike

所以我正在尝试使用 import 语句为我的自定义组件和我想使用的任何 node_modules 设置一个 Fontend JS 项目。 (我敢肯定还有其他方法可以做到这一点,但这是我尝试为这个项目做的方式。)

我一直读到我只需要 webpack 和 babel-loader 的某种组合,但我仍然遇到问题。

测试 lodash 时,使用这样的导入:import lodash from 'lodash';我收到 Failed to resolve module specifier “lodash”。相对引用必须以“/”开头../etc

对于 ./node_modules/lodash/lodash.js,直接导入完整路径给出了 404

这是我的 webpack.config.js

module.exports = {
entry: './src/app.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
devServer: {
contentBase: './src',
port: 9000,
historyApiFallback: {
index: 'index.html'
}
}
};

我试过不排除 node_modules

和我的 babel.config.js

const presets = [
"@babel/preset-env"
];
const plugins = [
"@babel/plugin-proposal-class-properties"
];

有什么明显的我做错了吗?

我在 git 仓库中有很多这样的东西 here

最佳答案

我检查了您的代码,发现您的配置没有创建 index.html

devServer.contentBase 指向导致错误的 ./src。它应该指向输出,即 ./dist 文件夹。

我更新了你的 webpack 配置

var HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path')

module.exports = {
context: path.join(process.cwd(), 'src'),
entry: './app.js',
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}]
},
resolve: {
modules: [
path.join(process.cwd(), 'node_modules'),
]
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: 'index.html'
})
],
devServer: {
contentBase: './dist',
port: 9000,
overlay: true,
}
};

在你的 index.html 上,移除指向 app.js 的脚本标签

关于javascript - 使用 Webpack 或 Babel 通过前端的 import 语句使用 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com