因此,将bundle.js链接到index.html之后,基本上我无法使用任何JavaScript。即使正在加载bundle.js,每个函数都未定义,我可以在开发工具中通过源代码访问它。但是,如果我直接链接我的JavaScript文件“ app.js”,那么一切都会按预期进行。我认为我的webpack设置很可能会出现问题,因为这是我第一次进行设置。关于此webpack.config的其他任何提示,我都会很高兴。在此先感谢:)
这是我的package.json:
{
"name": "name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode production",
"dev": "webpack --mode development",
"devs": "webpack-dev-server --mode development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^1.0.0",
"extract-loader": "^3.0.0",
"file-loader": "^2.0.0",
"font-awesome": "^4.7.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.9.4",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.23.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
}
}
webpack.config.js:
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
main: ["./src/index.js"]
},
output: {
filename: "scripts/bundle.js",
path: path.resolve(__dirname, "./dist")
},
module: {
rules: [
{
test: /\.html$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].html"
}
},
{
loader: "extract-loader"
},
{
loader: "html-loader",
options: {
attrs: ["img:src"]
}
}
]
},
{
test: /\.sass$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
},
{
test: /\.(jpg|gif|png)$/,
use: [
{
loader: "file-loader",
options: {
name: "images/[name].[ext]"
}
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "styles/[name].css",
chunkFilename: "[id].css"
})
],
watch: true,
};
Webpack主条目index.js:
require('./scripts/app.js');
require('./styles/sass/app.sass');
require("./index.html");
index.html脚本链接:
<script src="./scripts/app.js"></script>
编辑问题肯定在正在生成的bundle.js中。如果我在bundle.js的开头复制函数,那么一切都会按预期进行。这是小提琴中的bundle.js代码:
https://jsfiddle.net/ustqkg7v/
如果我在bundle.js的开头从app.js复制函数,那么一切都会按预期进行。我认为范围可能存在问题,但我不确定。
编辑2 我已经设置了具有相同文件夹结构,文件等的较小项目。完全相同的问题。这是链接:
https://www.dropbox.com/s/9f5pf6y4fbb60dw/webpack4-test.rar?dl=0
答案 0 :(得分:0)
这个问题也可能是由于path: path.resolve(__dirname, "./dist")
造成的。我假设webpack.config.js
位于项目的根目录下,所以我认为它必须是路径:path.resolve(__dirname, "dist")
>
然后在html中需要从dist文件夹中引用
<script src="./dist/app.js"></script>
在进行此检查之前,是否在dist文件夹中生成了app.js
答案 1 :(得分:-1)
在“ webpack.config.js”文件上添加:
devServer:
{
contentBase: path.resolve(__dirname, 'dist'),
writeToDisk: true,
}