First, solve the problem
1, how to introduce third-party libraries such as jquery, etc.
Second, the method of introducing jquery
1, download jquery.min.js into assets / lib below
2, the installation copy-webpack-plugin, a single file or an entire existing directory to build directory. Command: npm install copy-webpack-plugin --save-dev
3, configured in webpack.config.js, when the packing lib catalog copy directory member, configured as follows:
1 // copy packaged without third-party libraries 2 new new copyWebpackPlugin ([{ . 3 from: path.resolve (__ dirname, "../src/assets/lib" ), . 4 to: './assets/lib' , . 5 the ignore: [ '. *' ] . 6 }]),
4, the introduction jquery.min.js
At the bottom of the page html, body incorporated inside end tag <script src = "/ assets / lib / jquery.min.js"> </ script>, since the configuration properties htmlWebpackPlugin provided inject files packaged
Put to the bottom of the body element.
If the body into the end what will happen next label, as follows:
Why, look js load order:
We refer to jquery in index.js, then jquery has not yet introduced, naturally undefined Kazakhstan.
When put into the body jquery reference tag inside end effect is as follows:
jquery priority will be introduced, it will not appear this problem, so that we can have fun using a jquery.
5, externals use
externals: preventing certain import
packages (package) packed into the bundle, but again these externally acquired at runtime (Runtime) Extended dependent (external dependencies)
Increase the allocation in webpack.config.js
externals: {
jquery: 'window.jQuery'
}
表示:当require的参数是jquery的时候,使用winow.jQuery这个全局变量引用它,这种最简洁的externals配置方式为默认的global模式,就是在window上挂一个全局变量,然后直接可以使用这个变量
在js文件中引用
externals里面进行配置,不在js文件中引入,jquery也可以正常使用,因为在index.html通过script引用了jquery,浏览器加载时已经把jquery挂载到了window
Source Address: https://github.com/James-14/webpack4_multi_page_demo
Written by imperfect please criticism ~ ~ ~ ~ !!!!!!
Original article, please indicate the source, thank you!