1 Introduction
Before the ES6 modular specification was born, the Javascript community had tried and proposed modular specifications such as AMD, CMD, and CommonJS.
However, the modular standards proposed by these communities still have certain differences and limitations, and they are not common modular standards for browsers and servers. For example:
● AMD and CMD are suitable for browser-side Javascript modularization
● CommonJS is suitable for Server-side Javascript modularization
Therefore, in the ES6 grammar specification, the ES6 modularization specification is defined at the language level, which is a common modular development specification for the browser side and the server side.
ES6 modular specification defines:
● Each js file is an independent module
● Import module members use the import keyword
● Expose module members use the export keyword
2. ES6 modularity
2.1 Default export and default import
● The default export syntax export default The default exported members
● The default import syntax import
receives the name from
module identifier. The imported name can be customized
2.2 On-demand export and on-demand import
● Export grammar export let s1 = 10
on demand ● Import grammar'module import { s1 } from
identifier' on demand
webpack
Webpack is a popular front-end project construction tool (packaging tool) that can solve the current dilemma faced in web development. webpack provides friendly 模块化支持
, and 代码压缩混淆
, 处理js兼容问题
, 性能优化
and other powerful features, allowing programmers to focus our work on the concrete realization of the function, improve maintainability and development efficiency projects.
1. Define the package exit
const path = require('path');
module.exports = {
entry: './src/index.js',//定义打包的入口文件
output: {
path: path.resolve(__dirname, 'dist'),//定义打包的出口文件
filename: 'bundle.js'
}
};
supplement:
- Join is to connect the various path fragments together, and resolve takes'/' as the root directory
- Join directly splicing fields, resolve parses the path and returns
2. Configure automatic packaging
3. Configure the home page preview page
4. Automatic packaging related parameters
Open the browser page automatically after packaging is complete
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --host 127.0.0.1 --port 8888"
},
5. Loader configuration
In the actual development process, webpack default can only be packaged processed. Js extension module at the end of other non .js extension knot
the end of the module, webpack default could not handle, call the loader before the loader can be packaged properly, otherwise it will error !
5.1 Packaging and processing css files
- Run npm i style-loader css-loader -D to darkly convert the loader that processes the css file
- Add loader rules to the module->rules array in webpack.config.js.
Note:
The order of loaders in the use array is fixed.
The order of calling multiple loaders is from back to front.