# webpack 中 noParse 与 external 的区别
# 1. 介绍
module.noParse :
- 说明: 不参与编译(解析),但会进入 bundle
- 场景: 适用于引入 src 目录下的
xx.min.js
文件 - 注意:
xx.min.js
文件里不应使用import
等模块导入语法 - 参考: https://webpack.js.org/configuration/module/#modulenoparse (opens new window)
externals :
- 说明: 不参与编译(解析),也不会进入 bundle
- 适用: 适用于外部引入的 js,或开发第三方包时排除依赖
- 参考: https://webpack.js.org/configuration/externals/#root (opens new window)
# 2. module.noParse
目录:
src/
libs/
jquery.js
index.js
webpack.config.js:
const path = require('path');
module.exports = {
mode: "development",
entry: './src/index.js',
output: { filename: 'main.js', path: path.resolve(__dirname, 'dist') },
module: {
noParse: /jquery/,
}
};
index.js:
// import $ from 'jquery';
import $ from './libs/jquery'; // + noParse, 等价于从 node_modules 中引入
console.log($)
# 3. externals
目录:
src/
libs/
jquery.js
index.js
webpack.config.js:
const path = require('path');
module.exports = {
mode: "development",
entry: './src/index.js',
output: { filename: 'main.js', path: path.resolve(__dirname, 'dist') },
module: {
// 模块ID: 暴露出来的全局变量/导出变量
jquery: 'jQuery'
}
};
index.js:
import $ from 'jquery';
console.log($)
main.js: (编译后的代码)
var __webpack_modules__ = ({
"./src/index.js":
((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "jquery");
var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
console.log((jquery__WEBPACK_IMPORTED_MODULE_0___default()))
//# sourceURL=webpack://external/./src/index.js?");
}),
"jquery":
((module) => {
module.exports = jQuery;
})
});
index.html:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
<script src="main.js"></script>
# 4. 参考
上一篇: 下一篇:
本章目录