当前位置:首页 > Web开发 > 正文

webpack简单搭建基础感悟

2024-03-31 Web开发

实现局部webpack搭建并打包。

npm init 弄出一个package.json

首先npm i webpack webpack-cli -D

建立一个index.js,content.js.index.html

index.html里面引入index.js,

index.js里面的内容是 :

import content from ‘./content‘

console.log(content())

content.js里面的内容是:

const fn = ()=>{

return ‘ok‘

}

export default fn

正常打开index.html是报错的,因为浏览器不支持import语法。

这时因为是局部的webpack,所以执行

npx webpack index.js

这时就会在你的文件夹生成一个dist文件夹,里面会有一个叫main.js文件

 

下面我们将content.js里面输出方式换一个。

moudle.exports = fn

执行 npx webpack index.js我们删除dist,会发现又生成一个dist文件。

在dist文件里面创建一个index.html.

引入这个dist文件夹里面的main.js

在浏览器打开这个index.html

发现浏览器可以打印‘ok‘

 

 

下面我来更改package.json里面的配置文件用npm run build来进行打包

 

创建一个webpack.config.js

如下:

const path = require(‘path‘)

module.exports = {

entry:{

main:‘./src/index.js‘

},

output:{

filename:‘bundle.js‘,

path:path.resolve(__dirname,‘dist‘)

}

}

package.json:

{

"name": "blood",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1",

"build": "webpack"

},

"author": "",

"license": "ISC",

"devDependencies": {

"webpack": "^4.41.4",

"webpack-cli": "^3.3.10"

}

}

创建一个src文件夹,放入刚才index.js,content.js

这时执行npm run build这时就可以新创建出一个dist文件夹里面会有bundle.js这时打包就成功了,dist文件夹中index.html引入这个bundle.js在浏览器中打开就可以看到’ok‘

 

 

 

webpack简单搭建基础感悟

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/39888.html