我开始使用 webpack(版本 3),当我尝试从我的“app.js”文件中使用 jQuery 时,什么也没有发生:我 npm install --save jquery 和:import $ from 'jquery'$('body').css('backgroundColor', '#DD0000')document.body.style.backgroundColor = "red";当我尝试使用 document.body.style.backgroundColor = "red"; 更改 CSS 时 它告诉我“无法读取 null 的属性样式”但对于其余的工作,我的意思是我成功地尝试了这个:import json from "./test"console.log(json)这是我的 HTML 头部:<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Webpack</title> <link rel="stylesheet" href="./styles.css"> <script src="./dist/bundle.js"></script></head>这是我的 webpack 配置:const path = require("path");const uglify = require("uglifyjs-webpack-plugin");module.exports = { watch: true, entry: './app.js', output: { path: path.resolve('./dist'), filename: 'bundle.js' }, module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, use: ["babel-loader"], } ] }, plugins: [ new uglify(), ]}你知道我做错了什么吗?
1 回答

呼啦一阵风
TA贡献1802条经验 获得超6个赞
您在该<head>部分中插入了脚本。而且由于 JS 是阻塞的,它在被解析和存在之前就在那里执行<body>(所以它是null)。
如果你想让它工作,或者把你的脚本放在文档的末尾,就在结束</body>标记之前,或者等待文档被加载:
window.addEventListener('DOMContentLoaded', function() {
// Here, you can use document.body
});
或者,在 jQuery 语法中:
$(function() {
// Here, you can use document.body
});
添加回答
举报
0/150
提交
取消