1.首先我们创建一个目录,初始化 npm,然后在本地安装webpack,接着安装 webpack-cli(此工具用于在命令行中运行 webpack):
2.目录结构:
index.html
<!doctype html>
<html>
<head>
<title>起步</title>
<!-- <script src="https://unpkg.com/lodash@4.16.6"></script> -->
</head>
<body>
<!-- <script src="./src/index.js"></script> -->
<script src="bundle.js"></script>
</body>
</html>
webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
index.js
import * as _ from 'lodash'
function component() {
var element = document.createElement('div');
// Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
注意:1.出现Module not found: Error: Cannot resolve module '@types/lodash'问题需要安装lodash
npm install --save-dev @types/lodash
npm install --save lodash
然后才能引用lodash
import * as _ from 'lodash';
_.join(['Hello', 'webpack'], ' '); // or whatever
2.全局安装 webpack-cli 及webpack后执行webpack命令发现警告ERROR in Entry module not found:SyntaxError: E:\VSCode Workspace\webpack-demo\package.json...
执行一下npm run dev 或者 npm run build即可解决