├── .babelrc ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── LICENSE ├── README.md ├── package.json ├── src └── index.js └── test ├── plugin.test.js └── resources └── classes.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "env", 5 | { 6 | "modules": false, 7 | "loose": true 8 | } 9 | ], 10 | "stage-2" 11 | ] 12 | } 13 | 14 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | test/** 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "extends": "standard" 3 | }; -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | lib/ 4 | package-lock.json 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 相学长 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Webpack Babel Plugin 2 | 3 | ## Install 4 | 5 | ```bash 6 | npm i webpack-babel-plugin -D 7 | ``` 8 | 9 | ## Usage 10 | 11 | [Document of Webpack Plugins](https://webpack.js.org/configuration/plugins/) 12 | 13 | Add the plugin to the list of plugins,like so: 14 | 15 | ```javascript 16 | import BabelPlugin from 'webpack-babel-plugin' 17 | 18 | plugins: [ 19 | new BabelPlugin({ 20 | test: /\.js$/, 21 | babelOptions: { 22 | compact: false, 23 | sourceMap: false 24 | } 25 | }) 26 | ] 27 | ``` 28 | 29 | ## BabelOptions 30 | 31 | See the babel [options](https://babeljs.io/docs/usage/api/#options). 32 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "webpack-babel-plugin", 3 | "version": "0.0.2", 4 | "description": "babel plugin for webpack", 5 | "main": "./lib/index.js", 6 | "module": "./src/index.js", 7 | "scripts": { 8 | "build": "babel src/ --out-dir lib/", 9 | "prepublish": "rimraf lib/ && npm run build", 10 | "test": "jest" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/wuomzfx/webpack-babel-plugin.git" 15 | }, 16 | "keywords": [ 17 | "babel", 18 | "plugin", 19 | "webpack" 20 | ], 21 | "author": "相学长 <75851654@qq.com>", 22 | "license": "MIT", 23 | "bugs": { 24 | "url": "https://github.com/wuomzfx/webpack-babel-plugin/issues" 25 | }, 26 | "engines": { 27 | "node": ">= 8.9.1" 28 | }, 29 | "homepage": "https://github.com/wuomzfx/webpack-babel-plugin#readme", 30 | "dependencies": { 31 | "source-map": "^0.6.1", 32 | "webpack-sources": "^1.1.0" 33 | }, 34 | "peerDependencies": { 35 | "@babel/core": "7 || ^7.0.0-beta || ^7.0.0-rc", 36 | "webpack": "2 || 3" 37 | }, 38 | "devDependencies": { 39 | "@babel/core": "^7.0.0-beta.37", 40 | "babel-cli": "^6.26.0", 41 | "babel-preset-env": "^1.6.1", 42 | "babel-preset-stage-2": "^6.24.1", 43 | "eslint": "^4.15.0", 44 | "eslint-config-standard": "^11.0.0-beta.0", 45 | "eslint-plugin-import": "^2.8.0", 46 | "eslint-plugin-node": "^5.2.1", 47 | "eslint-plugin-promise": "^3.6.0", 48 | "eslint-plugin-standard": "^3.0.1", 49 | "jest": "^22.0.5", 50 | "rimraf": "^2.6.2", 51 | "webpack": "^3.10.0" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const babel = require('babel-core') 2 | const { SourceMapConsumer } = require('source-map') 3 | const { RawSource, SourceMapSource } = require('webpack-sources') 4 | const RequestShortener = require('webpack/lib/RequestShortener') 5 | const ModuleFilenameHelpers = require('webpack/lib/ModuleFilenameHelpers') 6 | 7 | module.exports = class BabelPlugin { 8 | constructor (options = {}) { 9 | this.babelOptions = { 10 | sourceRoot: process.cwd(), 11 | sourceMap: true, 12 | compact: true, 13 | ...options.babelOptions 14 | } 15 | delete options.babelOptions 16 | this.options = { 17 | test: /\.js$/i, 18 | ...options 19 | } 20 | } 21 | apply (compiler) { 22 | compiler.plugin('compilation', compilation => { 23 | // 现在设置回调来访问编译中的步骤: 24 | const requestShortener = new RequestShortener(compiler.context) 25 | const compiledAssets = new WeakSet() 26 | compilation.plugin('optimize-chunk-assets', (chunks, callback) => { 27 | chunks 28 | .reduce((acc, chunk) => acc.concat(chunk.files || []), []) 29 | .concat(compilation.additionalChunkAssets || []) 30 | .filter(ModuleFilenameHelpers.matchObject.bind(null, this.options)) 31 | .forEach(file => 32 | this.compile(file, compilation, compiledAssets, requestShortener) 33 | ) 34 | callback() 35 | }) 36 | }) 37 | } 38 | compile (file, compilation, compiledAssets, requestShortener) { 39 | const asset = compilation.assets[file] 40 | if (compiledAssets.has(asset)) { 41 | return 42 | } 43 | let sourceMap 44 | try { 45 | let input 46 | let inputSourceMap 47 | 48 | if (this.options.sourceMap && asset.sourceAndMap) { 49 | const { source, map } = asset.sourceAndMap() 50 | input = source 51 | inputSourceMap = map 52 | if (map) sourceMap = new SourceMapConsumer(inputSourceMap) 53 | } else { 54 | input = asset.source() 55 | inputSourceMap = null 56 | } 57 | 58 | const { code, map } = babel.transform(input, { 59 | ...this.babelOptions, 60 | inputSourceMap, 61 | filename: file 62 | }) 63 | 64 | const outputSource = this.options.sourceMap 65 | ? new SourceMapSource(code, file, map, input, inputSourceMap) 66 | : new RawSource(code) 67 | 68 | compiledAssets.add((compilation.assets[file] = outputSource)) 69 | } catch (error) { 70 | compilation.errors.push( 71 | BabelPlugin.buildError(error, file, sourceMap, requestShortener) 72 | ) 73 | } 74 | } 75 | static buildError (err, file, sourceMap, requestShortener) { 76 | // Handling error which should have line, col, filename and message 77 | // copy from buildError of uglify 78 | // https://github.com/webpack-contrib/uglifyjs-webpack-plugin/blob/master/src/index.js 79 | 80 | if (err.line) { 81 | const original = 82 | sourceMap && 83 | sourceMap.originalPositionFor({ 84 | line: err.line, 85 | column: err.col 86 | }) 87 | if (original && original.source) { 88 | return new Error( 89 | `${file} from BabelLoder\n${err.message} [${requestShortener.shorten( 90 | original.source 91 | )}:${original.line},${original.column}][${file}:${err.line},${ 92 | err.col 93 | }]` 94 | ) 95 | } 96 | return new Error( 97 | `${file} from BabelLoder\n${err.message} [${file}:${err.line},${ 98 | err.col 99 | }]` 100 | ) 101 | } else if (err.stack) { 102 | return new Error(`${file} from BabelLoder\n${err.stack}`) 103 | } 104 | return new Error(`${file} from BabelLoder\n${err.message}`) 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /test/plugin.test.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const fs = require('fs') 3 | const rimraf = require('rimraf') 4 | const webpack = require('webpack') 5 | const BabelPlugin = require('../src/index') 6 | 7 | const buildDir = path.join(__dirname, 'build'); 8 | const bundleFileName = 'bundle.js' 9 | 10 | describe('BabelPlugin Works', () => { 11 | afterEach(() => { 12 | rimraf.sync(buildDir); 13 | }); 14 | 15 | test('run webpack ok', async () => { 16 | try { 17 | await runWebpack({ 18 | babelOptions: { 19 | compact: false 20 | } 21 | }) 22 | const isCompiled = getFile(bundleFileName).indexOf('class Person') === -1 23 | expect(isCompiled).toBe(true) 24 | } catch (error) { 25 | expect(error).toMatch('error'); 26 | } 27 | }) 28 | }) 29 | 30 | function getConfig (opts = {}) { 31 | return { 32 | entry: path.join(__dirname, 'resources/classes.js'), 33 | output: { 34 | filename: bundleFileName, 35 | path: buildDir, 36 | }, 37 | plugins: [ new BabelPlugin(opts) ] 38 | }; 39 | } 40 | 41 | function runWebpack (opts) { 42 | const compiler = webpack(getConfig(opts)); 43 | return new Promise((resolve, reject) => { 44 | compiler.run((err, stats) => { 45 | if (err) return reject(err); 46 | resolve(stats); 47 | }); 48 | }); 49 | } 50 | 51 | function getFile (file) { 52 | return fs.readFileSync(path.join(buildDir, file)).toString(); 53 | } 54 | 55 | -------------------------------------------------------------------------------- /test/resources/classes.js: -------------------------------------------------------------------------------- 1 | export class Apple { 2 | constructor ({ model }) { 3 | this.className = 'Apple' 4 | this.model = model 5 | } 6 | getModel () { 7 | return this.model 8 | } 9 | } 10 | 11 | export class Person { 12 | constructor ({ name, age, sex }) { 13 | this.className = 'Person' 14 | this.name = name 15 | this.age = age 16 | this.sex = sex 17 | } 18 | getName () { 19 | return this.name 20 | } 21 | } 22 | --------------------------------------------------------------------------------