npm引用jquery


1、創建項目

  執行npm init -y,初始化包管理配置文件package.json

2、新建src源代碼目錄,新建src/index.html和src/index.js腳本文件

3、npm install jquery -S

4、index.js

  //使用ES6導入語法

  import $ from 'jquery'

  $(function(){

    $('li:odd').css('background-color','pink')

  })

  

  在index.html中引用index.js <script src='./index.js'></script>

5、安裝webpack

  npm install webpack@5.42.1 webpack-cli@4.7.2 -D

6、項目配置webpack

  ①在項目根目錄中,創建名webpack.config.js的webpack配置文件,並初始化如下的基本配置:  

const path=require('path')
module.exports = { 
  entry:{
    index:path.join(__dirname, './src/index.js')
  },
  output:{
    filename:'main.js',
    path:path.resolve(__dirname,'./dist')
  },
  mode: 'development' //mode用來指定構建模式。可選值有development 和 production(會壓縮打包文件)
}

  ②在package.json 的 scripts節點下,新增dev腳本如下:

    "scripts" : {

      "dev" : "webpack"  //script節點下的腳本,可以通過npm run 執行。例如npm run dev

      "build" : "webpack --mode production" //打包發布

    }

  ③在終端中運行npm run dev命令,啟動webpack進行項目的打包構建

7、引用dist下js

  在index.html中引用index.js <script src='../dist/main.js'></script>

 

8、webpack插件

  ① webpack-dev-server,修改源代碼不需要每次重新npm run dev

    npm install webpack-dev-server@3.11.2 -D

    修改package.json -> scripts 中的dev命令如下:

 "scripts": {
  "dev" :"webpack serve",//script節點下的腳本,可以通過 npm run 執行

}

再次運行npm run dev命令,重新進行項目的打包
在瀏覽器中訪問http://localhost:8080地址,查看自動打包效果

在index.html中引用index.js <script src='/main.js'></script> 讀取內存中的main.js

 

 ②html-webpack-plugin 復制src/index.html到根目錄,方便訪問http://localhost:8080地址時不再次點擊src目錄

  npm install html-webpack-plugin@5.3.2 -D

//導入 html-webpack-plugin這個插件,得到插件的構造函數
const HtmlPlugin = require('html-webpack-plugin')

//new構造函數,創建插件的實例對象
const htmlPlugin = new HtmlPlugin({
  //指定要復制哪個頁面
  template: './src/index.html ',
  //指定復制出來的文件名和存放路徑
  filename: './index.html'
})

//在moudle.exports中加入

     plugins: [htmlPlugin]

    //在moudle.exports中加入

devServer: {
  //首次打包成功后,自動打開瀏覽器
  open: true,
  port: 8080,
  //指定運行的主機地址
  host:'127.0.0.1'
}

 

在index.html中會自動填充內存的index.js <script src='/main.js'></script> ,所以頁面中的引用去掉就可以

8、webpack的loader

  ①babel-loader 打包高級js語法,例如裝飾器

  npm install -D babel-loader @babel/core @babel/plugin-proposal-decorators  (另一個視頻 @babel/ plugin-proposal-class-properties)

rules: [
  {
    test: /\.m?js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
      loader: 'babel-loader'
    }
  }
]

 

  babel.config.js

  module.exports =

  { "plugins": [["@babel/plugin-proposal-decorators",{legacy:true}] ]}

9、webpack配置

  SourceMap

  devtool 開發環境為eval-source-map(定位正確行號,顯示源碼),生產環境為nosources-source-map(定位正確行號,不顯示源碼)

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM