webpack的简单实例学习

webpack工具的使用
一、实现js打包
1.1、创建项目testwebpack
// 在文件夹 testwebpack
// 初始化 package.json
npm init

// 安装项目依赖 node_modules
npm install webpack –save-dev
1.2、创建文件夹app 和 build      app:放源代码      build: 编译之后的输出路径    1.2.1、app文件夹内创建 app.js和hello.js        代码编写遵循 nodejs的 commonjs 规范
// app.js
// exports 导出创建的标签 hello
module.exports = function(){
var hello = document.createElement(“div”);
hello.textContent = ‘hello webpack’;
return hello;
}

// build.js
// require 引入
var hello = require(“./hello.js”);
// 将标签放到root中
document.getElementById(“root”).appendChild(hello);
    1.2.2、build文件夹内创建 index.html
<body>
<!– 根容器 –>
<div id=”root”></div>
</body>

1.3、使用 webpack进行编译,将app文件中源代码编译到build文件中
// webpack 版本4 和 webpack 版本2 的写法不一样。主要注意
// webpack2 app/app.js 是要编译的文件 build/bundle.js 是要输出文件
// webpack app/app.js build/bundle.js

// webpack4
npx webpack app/app.js –output-filename build/bundle.js –output-path . –mode development
编译时可能出现报错:
1、报错
webpack不是内部命令

–需要全局安装webpack & webpack-cli
npm install webpack -g
npm install webpack-cli -g

2、报错
WARNING in configuration
The ‘mode’ option has not been set, webpack will fallback to ‘production’ for th
is value. Set ‘mode’ option to ‘development’ or ‘production’ to enable defaults
for each environment.
You can also set it to ‘none’ to disable any default behavior. Learn more: https
://webpack.js.org/concepts/mode/

ERROR in multi ./app/app.js build/bundle.js
Module not found: Error: Can’t resolve ‘build/bundle.js’ in ‘E:\test\1webpack’
@ multi ./app/app.js build/bundle.js main[1]

–查看安装webpack的版本,我安装的版本4,执行了webpack2的编译方法。
需要执行webpack4的编译方法,不然会出错。
1.4、编译完成后会在build文件中生成bundled.js文件引入到index.html 中就可以用了。
<script type=”text/javascript” src=”bundle.js”></script>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理