babel---webpack重要工具的使用

臧欣怿
2023-12-01

1.接入Babel

module: {
    rules: [
      {
        test: /\.js$/,
        use: ['babel-loader'],
      },
    ]
  }

2.设置babel的配置文件(其中plugins 需要那些插件,Presets预设新的语法特性)

// a.可以使用.babelrc
{
  "presets": [
    ["env", {
      "modules": false
    }],
    "stage-2"
  ],
  "plugins": ["transform-runtime"]
}
{
  "plugins": [
    [
      "transform-runtime",
      {
        "polyfill": false
      }
    ]
   ],
  "presets": [
    [
      "es2015",
      {
        "modules": false
      }
    ],
    "stage-2",	// 标准
    "react",	// 如果使用react,必须要加上
  ]
}

// b.可以使用.babel.config.js
module.exports = {
  presets: [
    '@vue/app'
  ],
  plugins: [
    ['import', {libraryName: 'ant-design-vue', style: 'css'}, 'ant-design-vue'],
    ['import', {
      libraryName: 'lodash',
      libraryDirectory: '',
      camel2DashComponentName: false,  // default: true
    }]
  ]
};

3.需要下载的插件

# babel正常运行需要它减少冗余代码,辅助函数替换导入语句
transform-runtime:npm i -D babel-plugin-transform-runtime	
# Webpack 接入 Babel 必须依赖的模块
npm i -D babel-core babel-loader 
# Plugins 或 Presets 根据你的需求选择不同的
npm i -D babel-preset-env
// react支持JSX语法
babel-preset-react

4.接入TS

# tsconfig.js 新建
{
    "compilerOptions": {
        "noImplicitAny": true,
        "removeComments": true,
        "importHelpers" : true,	// 不让辅助函数重复多个
    },
    "exclude": {
		"node_modules"
	}
    "awesomeTypescriptLoaderOptions": {
        /* ... */
    }
}
// vue项目
{
  "compilerOptions": {
    // 构建出 ES5 版本的 JavaScript,与 Vue 的浏览器支持保持一致
    "target": "es5",
    // 开启严格模式,这可以对 `this` 上的数据属性进行更严格的推断
    "strict": true,
    // TypeScript 编译器输出的 JavaScript 采用 es2015 模块化,使 Tree Shaking 生效
    "module": "es2015",
    "moduleResolution": "node"
  }
}
# [typescript ts => js](https://github.com/s-panferov/awesome-typescript-loader)
npm install -g  typescript // 全局安装不推荐
# loader 推荐使用,速度更快
npm install awesome-typescript-loader --save-dev

 类似资料: