学习webpack
-
管理员身份运行cmd,输入
cnpm install webpack -g
,cnpm install webpack-cli -g
-
新建文件夹
webpack-test
-
在
webpack-test
下新建modules
文件夹,在文件夹中编写main.js
和hello.js
<!-- hello.js --> // 暴露一个方法 exports.sayHi=function(){ document.write("<h1>ES6新特性</h1>") } exports.sayHi1=function(){ document.write("<h1>ES6新特性</h1>") } exports.sayHi2=function(){ document.write("<h1>ES6新特性</h1>") } exports.sayHi3=function(){ document.write("<h1>ES6新特性</h1>") }
<!-- main.js --> var hello = require("./hello"); hello.sayHi();
-
在
webpack-test
主目录下编写webpack.config.js
<!-- webpack.config.js --> module.exports = { entry: './modules/main.js', // 入口 output:{ filename: "./js/bundle.js" //最终打包形成的文件 } }
-
管理员模式打开终端,进入
webpack-test
文件夹,输入webpack
E:\WebFrontEnd\webpack-test>webpack asset ./js/bundle.js 412 bytes [compared for emit] [minimized] (name: main) ./modules/main.js 47 bytes [built] [code generated] ./modules/hello.js 324 bytes [built] [code generated] WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this 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/configuration/mode/ webpack 5.30.0 compiled with 1 warning in 211 ms
-
打开
dist/js
目录下生成的bundle.js
(()=>{var t={645:(t,i)=>{i.sayHi=function(){document.write("<h1>ES6新特性</h1>")},i.sayHi1=function(){document.write("<h1>ES6新特性</h1>")},i.sayHi2=function(){document.write("<h1>ES6新特性</h1>")},i.sayHi3=function(){document.write("<h1>ES6新特性</h1>")}}},i={};(function n(r){var e=i[r];if(void 0!==e)return e.exports;var o=i[r]={exports:{}};return t[r](o,o.exports,n),o.exports})(645).sayHi()})();
-
新建
index.html
,在<script>
标签中引入bundle.js
,即可使用之前的js脚本